<?
/*********************************************************************
 *
 *  Wattmon
 *    
 *  File : configsave.cgi
 * 
 *  Description: Ajax script used to save config values
 *
 *********************************************************************
 * Company:         Cynergy Software
 *
 * Software License Agreement
 *
 * Copyright (c) 2013 Cynergy Software.  All rights reserved.
 *
 * Cynergy licenses to you the right to use, modify, copy, and 
 * distribute: 
 * (i)  the Software when used on a Wattmon device
 * (ii) the Software on any platform or device for personal use
 *
 * For commercial use please contact us via http://www.wattmon.com
 *
 * THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT 
 * WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT 
 * LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS FOR A 
 * PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL 
 * CYNERGY BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR 
 * CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF 
 * PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS 
 * BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE 
 * THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER 
 * SIMILAR COSTS, WHETHER ASSERTED ON THE BASIS OF CONTRACT, TORT 
 * (INCLUDING NEGLIGENCE), BREACH OF WARRANTY, OR OTHERWISE.
 *
 * Author               Date        Comment
 *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * Akash Heimlich       20/08/13    v1.0
 * Akash Heimlich       20/03/18    v1.x - fix in ini_get(removed format specifier)
 *						27/01/21 	added option for binary encoded values (passwords)
 ********************************************************************/
if (!$_SESSION['logged_in']) {
    print("{'status':0,'error':'Error: You must be logged in to change settings!'}");
    die();
}
if ($_SESSION['admin']==0) {
 //   header("Location: /index.cgi"); 
    if ($_SESSION['ezconfig_lite']==0) {
        log("No permission to save");
        die();     
    }
    if ((strtolower($_GET['config'])!='pc.ini') && (strtolower($_GET['config'])!='ezconfig.ini')) {
        log("Cannot save this file: ".$_GET['config']);
        die();
    }
}


function in_array($arr,$key) {
    for ($i=0;$i<sizeof($arr);$i++) {
        if ($arr[$i]==$key) return 1;
    }
    return 0;
}

$fn=$_GET['config'];
if ($fn) {
    $drive="";
    if (isset($_GET['drive'])) $drive=intval($_GET['drive']).":";
    $fn=$drive.'/config/'+$fn;
//    log($fn);
    $section=$_GET['section'];
    if ($section) {
        
        
        $psize=sizeof(&$_POST);
        $has_encoded=0;
        if ($_POST['encoded_keys']) {
            $has_encoded=1;
            $encoded_keys=explode($_POST['encoded_keys'],',');
        }
       // print_r($encoded_keys);
        if (function_exists("array_key")) {
            if ($_SERVER['HW_PLATFORM']>=20) {
                $ini_array=ini_get_array($fn);
            
                //print_r($key);die();
    //           print("<pre>");
    //            print_r($ini_array);
      //          print_r($_POST);
        //        die();
                for ($i=0;$i<$psize;$i++) {
                    $strv=array_key(&$_POST,$i);
                    if ($strv!='encoded_keys') {
    //                    $v=ini_get($fn,$section,$strv);
                        $v=$ini_array[$section][$strv];//ini_get($fn,$section,$strv);                    
                        
                        $val=$_POST[$strv];
    //                    print("Section ".$section." ".$strv." = ".$v." new = ".$val."\r\n");
                        if ( $has_encoded) {
                            if (in_array(&$encoded_keys,$strv) ) {
                            
                                if (function_exists('urlencode')) {
                                    $val = urldecode(base64_decode($val));
                                } else {
                                    $val = url_decode(base64_decode($val));
                                }
                            }
                        }
                    //   print($fn." ".$section." =".$v);
                        //print("\r\nSet key ".$strv."=".$val." old=".$v);
                        if (is_string($val)) {
                            if (strpos($val,'#'))
                                $val='"'.$val.'"';
                        }
                        
                        if (($v!=$val) || ($v==0)) {
                        //  print("Going to set ".$fn." - ".$section." ".$strv." ".$val."\r\n");
                            if (!is_array($ini_array[$section]))
                                $ini_array[$section]=array();
                            if (!is_numeric($val))
                                $ini_array[$section][$strv]=strval($val);
                            else {
                                $ini_array[$section][$strv]=$val;
                            }
                        
    /*                        if (!ini_set($fn,$section,$strv,$val)) {
                                $error=1;
                                $errormsg=$errormsg+"Unable to save field "+$strv;
                            }*/
                        }
                    }
                }
                
        //      print_r($ini_array);
                //die();
            //    print("filename=".$fn);
                ini_put_array($fn,&$ini_array);
            } else {
                for ($i=0;$i<$psize;$i++) {
                    $strv=array_key(&$_POST,$i);
                    if ($strv!='encoded_keys') {
                        $v=ini_get($fn,$section,$strv);
                        $val=$_POST[$strv];
                        
                        if ( $has_encoded) {
                            if (in_array(&$encoded_keys,$strv) ) {
                            
                                if (function_exists('urlencode')) {
                                    $val = urldecode(base64_decode($val));
                                } else {
                                    $val = url_decode(base64_decode($val));
                                }
                            }
                        }
                     //   print($fn." ".$section." =".$v);
                        //print("\r\nSet key ".$strv."=".$val." old=".$v);
                        
                        if (($v!=$val) || ($v==0)) {
                          //  print("Going to set ".$fn." - ".$section." ".$strv." ".$val."\r\n");
                            if (!ini_set($fn,$section,$strv,$val)) {
                                $error=1;
                                $errormsg=$errormsg+"Unable to save field "+$strv;
                            }
                        }
                    }
                }
            }
        } else {
        // version 1.953 introduced an option to pass a pointer to array_keys to reduce memory
            $key=array_keys($_POST);
    
    //        print_r($key);die();
            for ($i=0;$i<$psize;$i++) {
                $strv=$key[$i];
                if ($strv!='encoded_keys') {
                    $v=ini_get($fn,$section,$strv);
                    //print("\r\nCheck key ".$key[$i]);
                    
                    $val=$_POST[$key[$i]];
                    if ($has_encoded && in_array(&$encoded_keys,$strv)) {
                        
                        if (function_exists('urlencode')) {
                            $val = urldecode(base64_decode($val));
                        } else {
                            $val = url_decode(base64_decode($val));
                        }
                    }
                    if ($v!=$val) {
                        if (!ini_set($fn,$section,$key[$i],$val)) {
                            $error=1;
                            $errormsg=$errormsg+"Unable to save field "+$key[$i];
                        }
                    }
                }
            }
        }
        
        if (!$error) {
            if ($_GET['config']=='battery.ini') {
                ini_set("/config/setup.ini","setup","setup1status",1);
            }
            if ($_GET['config']=='user.ini') {
                ini_set("/config/setup.ini","setup","setup2status",1);
            }
            print('{"status":1,"sysmsg":"You may need to reboot the device for changes to take effect!", "error":"'+$errormsg+'"}');
            $_GLOBALS['needreboot']=1;
        } else print('{"status":0}'); 
    } else print('{"status":0,"error":"Missing section"}');
} else {
    print('{"status":0,"error":"Missing filename"}');
}


function url_decode($input)
{
	$input_length = strlen($input);

	$output_length = ($input_length + 1) ;
	$working = '';
	$output = '';//working;
	
	$idx=0;
	while($idx<$input_length)
	{
	    $input_char=charat($input,$idx);
		if(chr($input_char) == '%')
		{
			$c1=charat($input,$idx+1);
			$c2=charat($input,$idx+2);
			$c1_chr=chr($c1);
			$c2_chr=chr($c2);
			$v = 0;
			if (($c1_chr>='0') && ($c1_chr<='9')) {
			    $v+= ($c1-ord('0')) * 16;
			}
			if (($c1_chr>='a') && ($c1_chr<='z')) {
			    $v+= ($c1-ord('a')+10) * 16;
			}
			if (($c1_chr>='A') && ($c1_chr<='Z')) {
			    $v+= ($c1-ord('A')+10) * 16;
			}
			if (($c2_chr>='0') && ($c2_chr<='9')) {
			    $v+= ($c2-ord('0')) ;
			}
			if (($c2_chr>='a') && ($c2_chr<='z')) {
			    $v+= ($c2-ord('a')+10) ;
			}
			if (($c2_chr>='A') && ($c2_chr<='Z')) {
			    $v+= ($c2-ord('A')+10) ;
			}
			
			$working.=chr($v); 
			$idx += 3;
		}
		else
		{
			$working.=chr($input_char);
			$idx++;
		}
	}

	
	return $working;
}
?>

