<?php
/**
 * Include to auto upgrade page 
 *
 * @package admin-panel
 * 
 */
require_once('admin.php');
require_once(dirname(__FILE__) . '/class-wtg-upgrader.php');

require_once(dirname(__FILE__) . '/other_functions.php');
define('WTG_PLUGIN_DIR_NAME', plugin_basename(dirname(__FILE__)));

function copy_files($src_dir, $dst_dir) {
   $d = dir($src_dir);
   $msg_error='';
   while($file = $d->read()) { 
	 if ($file != "." && $file != "..") { // to prevent an infinite loop
           if (is_dir($src_dir."/".$file)) { // do the following if it is a directory
               if (!@scandir($dst_dir."/".$file)) {
                  mkdir($dst_dir."/".$file); // create directories that do not yet exist
               }
               copy_files($src_dir."/".$file, $dst_dir."/".$file); // recursive part
           } else {
               $copy = copy($src_dir."/".$file, $dst_dir."/".$file); // put the files
               if (!$copy) {
               		$msg_error .='File copy fails: '. $file.'<br>';
               }
           }
       }
   }
   return $msg_error;
}

function extract_unit($string, $start, $end)
{
	$pos = stripos($string, $start);
	$str = substr($string, $pos);
	$str_two = substr($str, strlen($start));
	$second_pos = stripos($str_two, $end);
	if($second_pos) {
		$str_three = substr($str_two, 0, $second_pos);
	} else {
		$str_three=$str_two;
	}
	$unit = trim($str_three); // remove whitespaces
	return $unit;
}


function SureRemoveDir($dir, $DeleteMe) {
    if(!$dh = @opendir($dir)) return;
    while (false !== ($obj = readdir($dh))) {
        if($obj=='.' || $obj=='..') continue;
        if (!@unlink($dir.'/'.$obj)) SureRemoveDir($dir.'/'.$obj, true);
    }

    closedir($dh);
    if ($DeleteMe){
        @rmdir($dir);
    }
}

function is_empty_dir($dir)
{
    if (($files = @scandir($dir)) && count($files) <= 2) {
        return true;
    }
    return false;
}

function wtg_restore() {
	$message= array('type'=>'error');
	$plugins=get_plugins("/".WTG_PLUGIN_DIR_NAME);
	foreach ($plugins as $key => $value) {
		$plugin_file=$key;
	}
	$plugin=WTG_PLUGIN_DIR_NAME.'/'.$plugin_file;
	#for Window only
	$_POST['plugin_path'] = str_replace("\\\\", "\\", $_POST['plugin_path']);
	$_POST['backup_folder'] = str_replace("\\\\", "\\", $_POST['backup_folder']);
		
	$backup_folder=$_POST['backup_folder'];
	$p_plugin_path = $_POST['plugin_path'];
	$source_folder_name = $p_plugin_path."/".WTG_PLUGIN_DIR_NAME;
	
	if(file_exists($backup_folder."/".$plugin_file) && $plugin_file) {
	
		if ($p_plugin_path && $backup_folder && is_dir($backup_folder) && is_dir($source_folder_name) && (strcmp(WP_PLUGIN_DIR,$p_plugin_path) == 0)) { // do the following if it is a directory
			
			if (is_empty_dir($backup_folder)) {
				$error_message="The backup folder is empty. We can not restore the plugin.";
			} else { 
				SureRemoveDir($source_folder_name, false);
				# restore plugin from backup
				$msg_error=copy_files($backup_folder, $source_folder_name);
				if($msg_error) {
					$error_message="There are some problem while restoring the backup of current version of plugin.";
				} else {
					$error_message="Plugin restored successfully.";
					$message['type']="upgrade";
				}
			}
		} else {
			$error_message="Please insert the correct backup and plugin directory path.";
		}
	} else {
		$error_message="Sorry! Please enter the correct backup folder of this plugin.";
	}
	
	$message['message']= $error_message;
	return $message;
}

function wtg_empty_folder(){
	$path = $_POST['backup_folder'];
	
	// INITIALIZE THE DEBUG STRING
	$debugStr = '';
	$debugStr .= "Deleting Contents Of: $path<br /><br />";
 
	// PARSE THE FOLDER
	if ($handle = opendir($path)) {
 
		while (false !== ($file = readdir($handle))) {
 
			if ($file != "." && $file != "..") {
 
				// IF IT"S A FILE THEN DELETE IT
				if(is_file($path."/".$file)) {
 
					if(unlink($path."/".$file)) {
					$debugStr .= "Deleted File: ".$file."<br />";	
					}
 
				} else {
 
					// IT IS A DIRECTORY
					// CRAWL THROUGH THE DIRECTORY AND DELETE IT'S CONTENTS
 
					if($handle2 = opendir($path."/".$file)) {
 
						while (false !== ($file2 = readdir($handle2))) {
 
							if ($file2 != "." && $file2 != "..") {
								if(unlink($path."/".$file."/".$file2)) {
								$debugStr .= "Deleted File: $file/$file2<br />";	
								}
							}
 
						}
 
					}
 
					if(rmdir($path."/".$file)) {
					$debugStr .= "Directory: ".$file."<br />";	
					}
 
				}
 
			}
 
		}
 
	}
	//return $debugStr;
	/*foreach(glob($backup_folder.'*.*') as $v){
		unlink($v);
	}
	
	if (!(is_empty_dir($backup_folder))) {
		$error_message = "There was a problem deleting files. Please delete the files manually.";
	} else {
		$error_message = "Files deleted successfully. Please continue upgrade.";
	}*/
	$message['message']= $debugStr;
	return $message;

}

function wtg_upgrade() {
	$message= array('type'=>'error');
	// Check if is needed the upgrade
	$result=wtg_get_version(WTG_UPGRADE_VERSION_URL);
	$wtg_option = get_option('wtg_option');
	$messages = wtg_post_data(WTG_CHECK_URL, array("receipt_num" => convert_uudecode($wtg_option['receipt_number']), "domain" => $_SERVER['SERVER_NAME'], "ipaddress" => $_SERVER['REMOTE_ADDR'], "type" => 'wtg'));
	$error_message = '';
	$pos = strpos($messages, 'uncomplete');
	$pos2 = strpos($messages, 'webtrafficgenius');
	if(($pos === false) && ($pos2 !== false)) {
		$upgradeURL = $messages;
		if(version_compare($result, WTG_CURRENT_VERSION, '>')) {
			$plugins=get_plugins("/".WTG_PLUGIN_DIR_NAME);
			foreach ($plugins as $key => $value) {
				$plugin_file=$key;
			}
			$plugin=WTG_PLUGIN_DIR_NAME.'/'.$plugin_file;
			#for Window only
			$_POST['plugin_path'] = str_replace("\\\\", "\\", $_POST['plugin_path']);
			$_POST['backup_folder'] = str_replace("\\\\", "\\", $_POST['backup_folder']);
			
			$backup_folder = $_POST['backup_folder'];
			$p_plugin_path = $_POST['plugin_path'];
			$source_folder_name = $p_plugin_path."/".WTG_PLUGIN_DIR_NAME;
			//echo "p_plugin_path: ".$p_plugin_path." backup_folder: ".$backup_folder. " is_dir($backup_folder): ".is_dir($backup_folder)." is_dir($source_folder_name): ".is_dir($source_folder_name);
			
			/*if (strcmp(WP_PLUGIN_DIR,$p_plugin_path) == 0)
				echo "matching directory";*/
				
			if ($p_plugin_path && $backup_folder &&
				is_dir($backup_folder) && is_dir($source_folder_name)) 
			{

				$inplugindirectory = strpos($backup_folder, WP_PLUGIN_DIR);
				if($inplugindirectory === false) 
				{
					if (!(is_empty_dir($backup_folder))) {
						$error_message="The backup folder is not empty. Please empty the folder first.";
					} else {
						//if config file is not writeable
						if (!is_writeable($source_folder_name.'/config.php')) {
							$error_message = "Please chmod " . $source_folder_name. '/config.php' . " to 766<br/>";
						}
						else
						{
							# take a backup of existing plugin files and directory
							$msg_error = copy_files($source_folder_name, $backup_folder);
							if($msg_error) {
								$error_message="There are some problem while taking the backup of current version of plugin.";
							} else {
								// WordPress Administration File API 
								$nonce = 'upgrade-plugin_' . $plugin;
								$url = 'update.php?action=upgrade-plugin&plugin=' . $plugin;
								$upgrader = new Plugin_Upgrader( new Plugin_Upgrader_Skin( compact('title', 'nonce', 'url', 'plugin') ) );
								$upgrader->upgrade($plugin, $upgradeURL);
							
								$txt1 = file_get_contents($backup_folder."/config.php");
								if(file_exists($backup_folder."/config.php")) {
									$string1=extract_unit($txt1, '<?php', '?>');
								}
								
								/*if(file_exists($source_folder_name.'/config.php')) {
									$txt2 = file_get_contents($source_folder_name.'/config_sample.php');
									$string2=extract_unit($txt2, '<?php', '?>');
								}*/
								$string.="<?php";
								$string.="\n";
								$string.=$string1;
								$string.="\n\n";
								$new_ver = "define('WTG_CURRENT_VERSION', '".$result."');";
								$string = preg_replace ("/define\(\\'WTG_CURRENT_VERSION\\'\, \\'(\d+)\.(\d+)\.(\d+)\\'\);/",$new_ver, $string);
								/*if($string2) {
									$string.=$string2;
									$string.="\n\n";
								}*/
								$string.="?>";
								$fp = fopen($source_folder_name.'/config.php', 'w');
								if(fwrite($fp, $string) === false)
									$error_message='Could not merge the config file. Please merge it manually with the help of backup directory.';  
								
							}
							if (!$error_message) {
								// If successfully, notify user
								$error_message = "The upgrade was successfully.";
								$message['type']="upgrade";
							}
						
						}
					}
				}
				else
					$error_message = "You're not allowed to put your backup in the Plugins folder. Please choose another location for you backup.";
			} else {
				$error_message = "The directory may not be existing. Please insert the correct backup and plugin directory path.";
			}
		} else {
			$error_message = "You don't need to upgrade. You already have the latest version.";
		}
	}
	else {
		$error_message = "Your copy of Web Traffic Genius is unregistered.  Please <a href='http://www.webtrafficgenius.com/traffic.html'>click here</a> to purchase your own licensed copy.";
	}

	$message['message']= $error_message;
	return $message;
}


 function wtg_auto_upgrade() {
	$wtg_option = get_option('wtg_option');
 	if (isset($_POST['upgrade'])) {
		// decode the encoded receipt number
		$wtg_option['receipt_number']=convert_uudecode($wtg_option['receipt_number']);
		//echo $wtg_option['receipt_number'];
		if($wtg_option['registration'] && $wtg_option['receipt_number']) {
			$upgrade_status=wtg_post_data(WTG_CHECK_URL, array("action" => "upgrade_status", "receipt_num" => $wtg_option['receipt_number'], "type" => 'wtg'));
			if($upgrade_status != 'uncomplete') {
				$message=wtg_upgrade();
				if($message['type']== 'upgrade') {
					//echo 'upgrade';
					$update_status=wtg_post_data($url, array("action" => "update_activations", "receipt_num" => $wtg_option['receipt_number'], "domain" => $_SERVER['SERVER_NAME'], "ipaddress" => $_SERVER['REMOTE_ADDR'], "type" => 'wtg'));
					exit;
				}
			}
		} else {
			$message['message']="Please register first to upgrade the plugin.";
		}
	}
	
	if (isset($_POST['empty_folder'])){
		$message=wtg_empty_folder();
	}
			
	if (isset($_POST['restore'])) {
		$message=wtg_restore();
		//if(!$message) exit;
	}
?>
	<div class="wrap">
		<div class="icon32" id="icon-plugins"><br></div>
		<h2>Auto plugin upgrade</h2>
<?php
	wtg_messages();
	wtg_check_registration_status();
	
	if(isset($message['message'])) {
		if($message['type'] == 'upgrade') {
			$class="updated fade";
		} else {
			$class="error fade below-h2";
		}
		print '<div class="'.$class.'" id="message"><p>'.$message['message'].'</p></div>';
	}

?>
		<form action="" method="post">
			<div class="wrap">
				<table class="form-table">
					<tr valign="top">
						<th scope="row"><label for="tmp_folder">Backup Folder</label></th>
						<td><input type="text" size="40" value="<?php echo (isset($_POST['backup_folder']))?$_POST['backup_folder']: $_SERVER['DOCUMENT_ROOT']."/wtg-backup"; ?>" id="backup_folder" name="backup_folder">
							<br><span class="description">&nbsp;This folder is used as a backup to store the current version. Needs write permission for the Web Server user.</span>
						</td>
					</tr>
					<tr valign="top">
						<th scope="row"><label for="plugin_path">Plugins Path</label></th>
						<td><input type="text" size="40" value="<?php echo (isset($_POST['plugin_path']))?$_POST['plugin_path']: WP_PLUGIN_DIR ?>" id="plugin_path" name="plugin_path">
							<br><span class="description">&nbsp;This is the path to the plugins folder.</span>
						</td>
					</tr>
				</table>
				<p class="submit">
					<input type="submit" value="Proceed" class="button" name="upgrade" id="upgrade">
					<input type="submit" value="Restore" class="button" name="restore" id="restore">
					<input type='submit' value='Empty Backup Folder' class='button' name='empty_folder' id='empty_folder'>
				</p>
				<p>Having problems auto upgrading?  Refer to this post in the forum about it: <a target="_new" href="http://webtrafficandmarketing.com/forums/web-traffic-genius-software/1798-why-wordpress-asks-connection-info.html">Why WordPress Asks for Connection Info</a>. </p>
			</div>
		</form>
	</div>
<?php
 exit;
 }
?>