<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Autoupdate extends CI_Controller {
	function index(){
		if($this->session->userdata('is_logged_in')==FALSE){
			redirect('login');
		}

		if($this->session->userdata('idgroup')>1){
			show_404();
		}
		$data['page_title'] = '';
		$data['main_body'] = 'update/autoupdate';
		$data['app_ver'] = $this->session->userdata('app_version');
		$this->load->vars($data);
		$this->load->view('header');
		$this->load->view('body/body_new');
	}

	function get_siteInfo(){
		return '3.0.1';
	}

	function doupgrade(){
		ini_set('max_execution_time',60);
		include_once('path.php');
		$_GET['doUpdate'] = true;
		$updated = false;

		$updateURLFolder = getURLTmpFolder();
		$updateURLFolder = base_url('resources/');
		$getVersions = file_get_contents('current-release-versions.php') or die ('ERROR');
		if ($getVersions != ''){
			echo '<p>CURRENT VERSION: '.get_siteInfo('CMS-Version').'</p>';
			echo '<p>Reading Current Releases List</p>';
			$versionList = explode("\n", $getVersions);	
			foreach ($versionList as $aV){
				if ( $aV > get_siteInfo('CMS-Version')) {
					echo '<p>New Update Found: v'.$aV.'</p>';
					$found = true;
					
					//Download The File If We Do Not Have It
					if (!is_file($updateURLFolder.'/MMD-CMS-'.$aV.'.zip' )) {
						echo '<p>Downloading New Update</p>';
						//$newUpdate = file_get_contents('http://localhost/testerCode/autoupdate/file/MMD-CMS-'.$aV.'.zip');
						
						if ( !is_dir($updateURLFolder.'/tmp/' ) ) mkdir ($updateURLFolder.'/tmp/' );
						$dlHandler = fopen($updateURLFolder.'/tmp/MMD-CMS-'.$aV.'.zip', 'w');
						
						// Get The Zip File From Server
						$ch = curl_init();
						curl_setopt($ch, CURLOPT_URL, 'http://localhost/testerCode/autoupdate/file/MMD-CMS-'.$aV.'.zip');
						curl_setopt($ch, CURLOPT_FAILONERROR, true);
						curl_setopt($ch, CURLOPT_HEADER, 0);
						curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
						curl_setopt($ch, CURLOPT_AUTOREFERER, true);
						curl_setopt($ch, CURLOPT_BINARYTRANSFER,true);
						curl_setopt($ch, CURLOPT_TIMEOUT, 10);
						curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
						curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
						curl_setopt($ch, CURLOPT_FILE, $dlHandler);
						$page = curl_exec($ch);
						if(!$page) {
							echo "Error :- ".curl_error($ch);
							return;
						}
						curl_close($ch);
						//if ( !fwrite($dlHandler, $newUpdate) ) { echo '<p>Could not save new update. Operation aborted.</p>'; exit(); }
						fclose($dlHandler);
						echo '<p>Update Downloaded And Saved</p>';
					} else echo '<p>Update already downloaded.</p>';	
					
					if ($_GET['doUpdate'] == true) {
						//cara lain ekstrak zip file
						$extractPath='resources/tmp/';
						$this->ekstrak($updateURLFolder.'/MMD-CMS-'.$aV.'.zip', $extractPath);
						//end

						//Open The File And Do Stuff
						$zipHandle = zip_open($updateURLFolder.'/MMD-CMS-'.$aV.'.zip');
						echo '<ul>';
						while ($aF = zip_read($zipHandle) ) {
							$thisFileName = zip_entry_name($aF);
							$thisFileDir = dirname($thisFileName);
							
							//Continue if its not a file
							if ( substr($thisFileName,-1,1) == '/') continue;
							
			
							//Make the directory if we need to...
							if ( !is_dir ( $_ENV['site']['files']['server-root'].'/'.$thisFileDir ) ){
								 mkdir ( $_ENV['site']['files']['server-root'].'/'.$thisFileDir );
								 echo '<li>Created Directory '.$thisFileDir.'</li>';
							}
							
							//Overwrite the file
							if ( !is_dir($_ENV['site']['files']['server-root'].'/'.$thisFileName) ) {
								echo '<li>'.$thisFileName.'...........';
								$contents = zip_entry_read($aF, zip_entry_filesize($aF));
								$contents = str_replace("\r\n", "\n", $contents);
								$updateThis = '';
								
								//If we need to run commands, then do it.
								if ( $thisFileName == 'upgrade.php' ){
									$upgradeExec = fopen ('upgrade.php','w');
									fwrite($upgradeExec, $contents);
									fclose($upgradeExec);
									include ('upgrade.php');
									unlink('upgrade.php');
									echo' EXECUTED</li>';
								}
								else
								{
									$updateThis = fopen($_ENV['site']['files']['server-root'].'/'.$thisFileName, 'w');
									fwrite($updateThis, $contents);
									fclose($updateThis);
									unset($contents);
									echo' UPDATED</li>';
								}
							}
						}
						echo '</ul>';
						$updated = true;
					}
					else echo '<p>Update ready. <a href="?doUpdate=true">&raquo; Install Now?</a></p>';
					break;
				}
			}
			
			if ($updated == true){
				set_setting('site','CMS',$aV);
				echo '<p class="success">&raquo; CMS Updated to v'.$aV.'</p>';
			}else if ($found != true) echo '<p>&raquo; No update is available.</p>';
		}else echo '<p>Could not find latest realeases.</p>';
	}

	function ekstrak($zipFile, $extractPath=''){
		/* Open the Zip file */
		$zip = new ZipArchive;
		//$extractPath = ('resources/tmp/');
		if($zip->open($zipFile) != "true"){
		 	echo "Error :- Unable to open the Zip File ".$zipFile;
			$zip->close(); 
			return;
		} 
		/* Extract Zip File */
		$zip->extractTo($extractPath);
		$zip->close();
		echo "Success:- Proses Ekstrak Berhasil";
	}
}