<?php

$iwpUpdateObject = new IWPUpdate();

$iwpUpdateObject->initUpdateManual();

class IWPUpdate {
	
	private $newVersion = '2.12.1.1';
	private $thisVersion;
	
	private $updateType; // a. oneClickUpdate b. manualUpate
	
	private $configFileContents;
	
	private $configFileModifiedSuccess;
	private $configFileModifiedError;
	private $configFileReadError;
	private $sqlUpdateError;
	private $sqlUpdateSuccess;
	
	private $messageSuffix;
	
	private $debugMode = false;
	
	function doAssignCommonUpdateMessages() {
		$this->configFileModifiedSuccess = '<br>Config file modified';
		$this->configFileModifiedError = '<br>Unable to modify config.php file';
		$this->configFileReadError = '<br>Unable to read config.php file';
		$this->sqlUpdateError = '<br>SQL Error: update failed';
		$this->sqlUpdateSuccess = '<br>Database updated';
		
		$this->messageSuffix = 'while doing common update.';		
	}
	
	function initUpdateManual() {
		
		$this->updateType = 'manualUpdate';
		
		@define('FS_METHOD', 'direct');

		include("config.php");
		include_once(APP_ROOT."/includes/registry.php");
		include_once(APP_ROOT."/includes/db.php");
		include_once(APP_ROOT."/controllers/appFunctions.php");
		include_once(APP_ROOT."/includes/commonFunctions.php");

		Reg::set('config', $config);

		DBConnectAndSetOptions();

		$settings = DB::getRow("?:settings", "*", 1);
		Reg::set('settings', unserialize($settings['general']));

		if(!defined('SUPPORT_URL')){ define('SUPPORT_URL', (getOption('SUPPORT_URL') ? getOption('SUPPORT_URL') : 'https://support.infinitewp.com/')) ; } 

		if(version_compare(APP_VERSION, '2.3.5', '<=')){
			echo 'For this manual update, at least v2.4.0 is required. For older versions, <a target="_blank" href="'.SUPPORT_URL.'/solution/articles/212269-infinitewp-admin-panel-manual-update/">see here</a>. ';
			exit;
		}

		if(version_compare(APP_VERSION, $this->newVersion, '<')) {
			
			$this->initCommon();
			
			$this->runUpdate();
			
		} else{
			echo 'You are already have the latest version.';
			exit;
		}		
	}
	
	function initUpdateFinalize() {
		global $updateAvailable;
		
		$this->updateType = 'oneClickUpdate';
		
		if(!empty($updateAvailable['updateDetails'][$this->newVersion])){
			
			$this->initCommon();
			
			$this->runUpdate();
			
		}
	}
	
	function initCommon() {
		
		echo '<br>Running update finalizer..';
		require_once(APP_ROOT.'/includes/file.php');
		
		if(!is_object($GLOBALS['FileSystemObj'])){
			if(!initFileSystem()){
				appUpdateMsg('Unable to initiate file system.', true);
				exit;
			}
		}
		
		$GLOBALS['updatePanelLocation'] = $GLOBALS['FileSystemObj']->findFolder(APP_ROOT);
		$GLOBALS['updatePanelLocation'] = removeTrailingSlash($GLOBALS['updatePanelLocation']);		
	}
	
	function runUpdate() {
		
		// This method should run initially.		
		$this->preCommonUpdate();
		
		$this->thisVersion = '2.4.4';
		$this->messageSuffix = 'while doing update for v';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_4_4();			
		}
		
		$this->thisVersion = '2.4.5';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_4_5();			
		}

		$this->thisVersion = '2.4.7';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_4_7();			
		}
		
		$this->thisVersion = '2.5.0beta1';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_5_0_beta1();			
		}
		
		$this->thisVersion = '2.5.0beta3';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_5_0_beta3();			
		}
		
		$this->thisVersion = '2.5.0beta4';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_5_0_beta4();			
		}
		
		$this->thisVersion = '2.5.0';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_5_0();			
		}
		
		$this->thisVersion = '2.5.1';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_5_1();			
		}
		
		$this->thisVersion = '2.6.0beta1';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_6_0_beta1();			
		}
		
		$this->thisVersion = '2.6.0beta2';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_6_0_beta2();			
		}
		
		$this->thisVersion = '2.6.1';
		if(
			version_compare(APP_VERSION, $this->thisVersion, '<') 
			|| (
				version_compare(APP_VERSION, '2.7.0beta2', '<') 
				&& version_compare(APP_VERSION, '2.7.0beta1', '>=')
			)
		) {
			$this->updateForV2_6_1();			
		}
		
		$this->thisVersion = '2.7.0beta1';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_7_0_beta1();			
		}
		
		$this->thisVersion = '2.7.0beta2';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_7_0_beta2();			
		}
		
		$this->thisVersion = '2.7.0';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_7_0();			
		}
		
		$this->thisVersion = '2.8.0beta1';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_8_0_beta1();			
		}

		$this->thisVersion = '2.9.0beta1';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_9_0_beta1();			
		}
		
		$this->thisVersion = '2.9.0beta2';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_9_0_beta2();			
		}

		$this->thisVersion = '2.9.1';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_9_1();			
		}
			
		$this->thisVersion = '2.10.0beta1';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_10_0_beta1();			
		}

		$this->thisVersion = '2.10.0beta2';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_10_0_beta2();			
		}

		$this->thisVersion = '2.10.0';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_10_0();			
		}

		$this->thisVersion = '2.10.1';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_10_1();			
		}
		
		$this->thisVersion = '2.10.2';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_10_2();			
		}
      
        $this->thisVersion = '2.11.0beta1';
        if(version_compare(APP_VERSION, $this->thisVersion, '<')){
            $this->updateForV2_11_0_beta1();
        }
							
		$this->thisVersion = '2.10.3';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_10_3();			
		}

		$this->thisVersion = '2.12.0beta2';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_12_0beta2();			
		}

		$this->thisVersion = '2.12.0beta3';
		if(version_compare(APP_VERSION, $this->thisVersion, '<')) {
			$this->updateForV2_12_0beta3();			
		}

		// This method should run finally.
		$this->postCommonUpdate();		
	}
	
	function doQuerySQLArray($sqlArray, $versionAppendMode = false) {
		foreach($sqlArray as $sql){
			$isDone = DB::doQuery($sql);
			$message = $this->sqlUpdateError.' '.$this->messageSuffix;
			if($versionAppendMode === true) {
				$message .= $this->thisVersion;
			}
			if(!$isDone){ die($message); }
		}
		$message = $this->sqlUpdateSuccess.' '.$this->messageSuffix;
		if($versionAppendMode === true) {
			$message .= $this->thisVersion.'.';
		}
		if($this->debugMode) {
			echo $message.'..';	
		}
		unset($message);
	}
	
	function isConfigFileEmpty($versionAppendMode = false) {
		$message = $this->configFileReadError.' '.$this->messageSuffix;
		if(empty($this->configFileContents)) {
			if($versionAppendMode === true) {
				$message .= $this->thisVersion.'.';
			}
			die($message);			
		}
		unset($message);
	}
	
	function doCheckAndPutConfigFileContents($versionAppendMode = false) {
		if ($GLOBALS['FileSystemObj']->putContents( $GLOBALS['updatePanelLocation'].'/config.php', $this->configFileContents, FS_CHMOD_FILE)) {
			$message = $this->configFileModifiedSuccess.' '.$this->messageSuffix;
			if($versionAppendMode === true) {
				$message .= $this->thisVersion.'.';
			}
			if($this->debugMode) {
				echo $message.'..';	
			}
			unset($message);
		} else {
			$message = $this->configFileModifiedError.' '.$this->messageSuffix;
			if($versionAppendMode === true) {
				$message .= $this->thisVersion.'.';
			}			
			die($message);
		}		
	}
	
	function preCommonUpdate() {
		
		$this->doAssignCommonUpdateMessages();
		
		$this->preCommonUpdateConfigFile();	
		
		//we dont have updates in database for common update.

		//we dont have updates in files for common update.		
		
	}
	
	function postCommonUpdate() {
		
		$this->doAssignCommonUpdateMessages();
		
		//we dont have updates in config file for common update.
		
		$this->postCommonUpdateDatabase();
		
		if($this->updateType === 'manualUpdate') {
			updateOption('updateAvailable', '');
		}
		
		//file delete, rename etc	
		$this->postCommonUpdateFiles();

		$this->showReloadMessage();
	}
	
	function preCommonUpdateConfigFile() {
		
		$this->configFileContents = file_get_contents(APP_ROOT . '/config.php');
		
		$this->isConfigFileEmpty();
		
		//update version number
		if (strstr($this->configFileContents, 'define(\'APP_VERSION\',')) {
			$this->configFileContents = preg_replace('/define\(\'APP_VERSION\', .*\);/mi', "define('APP_VERSION', '$this->newVersion');", $this->configFileContents);
		}
		
		$this->doCheckAndPutConfigFileContents();
	}
	
	function postCommonUpdateDatabase() {
	
		$sqlArray = array();		
		$sqlArray[] = "UPDATE `?:options` SET `optionValue` = '0' WHERE `optionName` = 'updateLastCheck'";//setting updateLastCheck to 0, makes new check Update call on next load
		
		$this->doQuerySQLArray($sqlArray);			
	}
	
	function postCommonUpdateFiles() {
		$this->clearOldAppErrorLogs();
	}

	function clearOldAppErrorLogs() {
		// appErrorLogs code clean script start here. This need to run every update so we not kept in any condition
		if (file_exists(APP_ROOT."/appErrorLogs.txt")) {
			$fp = fopen(APP_ROOT."/appErrorLogs.txt", "r");
			$pos = 0;
			$currentLine = "";
			$toKeep ="";
			while(-1 !== fseek($fp, $pos, SEEK_END)){
				$char = fgetc($fp);
				if ("\n" == $char) {
					if(!empty($currentLine)){
						if(strpos($currentLine,date("Y-m-d")) === 0){
							$toKeep = $currentLine.$toKeep;
							$currentLine = "";
						}else{
							break;
						}
					}
				} else {
					$currentLine = $char . $currentLine;
				}
				$pos--;
			}
			file_put_contents(APP_ROOT."/appErrorLogs.txt", $toKeep );
			// appErrorLogs code clean script start here
		}		

	}

	function showReloadMessage() {
		echo '<br><a href="index.php" target="_parent">Reload your App</a>.';
		
		$GLOBALS['updateFinalizeStatus'] = true;//update succesfully done
		
		if($this->updateType === 'manualUpdate') {
			$fileName = 'updateManual.php';
		} else {
			$fileName = 'updateFinalize_v'.$this->newVersion.'.php';
		}
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/'.$fileName, false, 'f');
	}
	
	function updateForV2_4_4() {
		
		$this->updateConfigFileForV2_4_4();
		
		//we dont have updates in database for v2.4.4.
		
		//we dont have updates in files for v2.4.4.		
	}
	
	function updateConfigFileForV2_4_4() {
		
		$this->configFileContents = file_get_contents(APP_ROOT . '/config.php');
		
		$this->isConfigFileEmpty(true);
		
		if (strstr($this->configFileContents, 'error_reporting(E_ALL')) {
			$this->configFileContents = preg_replace('/error_reporting\(E_ALL .*\);/mi', "error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);", $this->configFileContents);
		}
		
		$this->doCheckAndPutConfigFileContents(true);		
				
	}
	
	function updateForV2_4_5() {
		
		$this->updateConfigFileForV2_4_5();
		
		//we dont have updates in database for v2.4.5.
		
		//we dont have updates in files for v2.4.5.		
	}
	
	function updateConfigFileForV2_4_5() {
		
		$this->configFileContents = file_get_contents(APP_ROOT . '/config.php');
		
		$this->isConfigFileEmpty(true);
		
		if (strstr($this->configFileContents, 'error_reporting(E_ALL')) {
			$this->configFileContents = preg_replace('/error_reporting\(E_ALL .*\);/mi', "error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);".PHP_EOL."if(defined('E_DEPRECATED')) {".PHP_EOL."error_reporting(error_reporting() & ~E_DEPRECATED);".PHP_EOL."}".PHP_EOL, $this->configFileContents);
		}
		
		$this->doCheckAndPutConfigFileContents(true);
		
	}
	
	function updateForV2_4_7() {
		
		//we dont have updates in config file for v2.4.7.
		
		$this->updateDatabaseForV2_4_7();
		
		//we dont have updates in files for v2.4.7.		
	}
	
	function updateDatabaseForV2_4_7() {
	
		$sqlArray = array();
		
		$sqlArray[] = "DELETE FROM `?:site_stats` WHERE siteID NOT IN (SELECT siteID FROM `?:sites`)";
		$sqlArray[] = "DELETE FROM `?:groups_sites` WHERE siteID NOT IN (SELECT siteID FROM `?:sites`)";
		$sqlArray[] = "DELETE FROM `?:hide_list` WHERE siteID NOT IN (SELECT siteID FROM `?:sites`)";
		$sqlArray[] = "DELETE FROM `?:user_access` WHERE siteID NOT IN (SELECT siteID FROM `?:sites`)";
		
		$this->doQuerySQLArray($sqlArray, true);
	}
	
	function updateForV2_5_0_beta1() {
		//we dont have updates in config file for v2.5.0beta1.
		
		$this->updateDatabaseForV2_5_0_beta1();
		
		//we dont have updates in files for v2.5.0beta1.		
	}
	
	function updateDatabaseForV2_5_0_beta1() {
		
		$sqlArray = array();
		
		$sqlArray[] = "ALTER TABLE `?:addons` CHANGE `initialVersion` `initialVersion` VARCHAR( 40 ), CHANGE `updateCurrentVersion` `updateCurrentVersion` VARCHAR( 40 )";
		$sqlArray[] = "ALTER TABLE `?:sites` CHANGE `WPVersion` `WPVersion` VARCHAR( 40 ), CHANGE `pluginVersion` `pluginVersion` VARCHAR( 40 )";
		if(!(DB::getExists("SHOW COLUMNS FROM `?:sites` WHERE Field = 'siteCookie'"))){
			$sqlArray[] = "ALTER TABLE `?:sites` ADD `siteCookie` TEXT NULL";
		}
		if(!(DB::getExists("SHOW COLUMNS FROM `?:users` WHERE Field = 'authInfo'"))){
			$sqlArray[] = "ALTER TABLE `?:users` ADD `authInfo` TEXT NULL DEFAULT NULL";
		}
		if(!(DB::getExists("SHOW COLUMNS FROM `?:users` WHERE Field = 'resetMD5'"))){
			$sqlArray[] = "ALTER TABLE `?:users` ADD `resetMD5` TEXT NULL DEFAULT NULL";
		}
		if(!(DB::getExists("SHOW COLUMNS FROM `?:history` WHERE Field = 'userIDCleared'"))){
			$sqlArray[] = "ALTER TABLE `?:history` ADD `userIDCleared` INT(10) UNSIGNED NULL DEFAULT NULL";
		}
		
		$this->doQuerySQLArray($sqlArray, true);		
	}
	
	function updateForV2_5_0_beta3() {
		//we dont have updates in config file for v2.5.0beta3.
		
		$this->updateDatabaseForV2_5_0_beta3();
		
		//we dont have updates in files for v2.5.0beta3.		
	}

	function updateDatabaseForV2_5_0_beta3() {
		
		$sqlArray = array();
		
		if(!(DB::getExists("SHOW COLUMNS FROM `?:users` WHERE Field = 'resetPassword'"))){
			$sqlArray[] = "ALTER TABLE  `?:users` CHANGE  `resetMD5`  `resetPassword` TEXT NULL DEFAULT NULL";
		}
		
		$this->doQuerySQLArray($sqlArray, true);		
	}

	function updateForV2_5_0_beta4() {
		//we dont have updates in config file for v2.5.0beta4.
		
		$this->updateDatabaseForV2_5_0_beta4();
		
		//we dont have updates in files for v2.5.0beta4.		
	}

	function updateDatabaseForV2_5_0_beta4() {
		
		$sqlArray = array();
		
		$sqlArray[] = "DELETE FROM `?:history` WHERE `status`='initiated' and `microtimeInitiated` IS NULL";
		
		$this->doQuerySQLArray($sqlArray, true);		
	}

	function updateForV2_5_0() {
		//we dont have updates in config file for v2.5.0.
		
		//we dont have updates in database for v2.5.0.
		
		$this->updateFilesForV2_5_0();		
	}
	
	function updateFilesForV2_5_0() {
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/images/logo.gif', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/images/logo_big_w.gif', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/images/email/bg.gif', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/images/email/btn_open_admin.png', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/images/email/emailer_weekly_ribbon.png', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/images/email/tag_plugins.png', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/images/email/tag_themes.png', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/images/email/tag_wp.png', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/images/email/up_to_date.png', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/images/email', false);		
	}
	
	function updateForV2_5_1() {
		
		$this->updateConfigFileForV2_5_1();
		
		$this->updateDatabaseForV2_5_1();
		
		$this->updateFilesForV2_5_1();		
	}
	
	function updateConfigFileForV2_5_1() {
		
		$this->configFileContents = file_get_contents(APP_ROOT . '/config.php');
		
		$this->isConfigFileEmpty(true);
		
		if (strstr($configFileContents, 'define(\'APP_MAIL_FROM_EMAIL_NAME\',')) {
			$this->configFileContents = preg_replace('/define\(\'APP_MAIL_FROM_EMAIL_NAME.*\R/', '', $this->configFileContents);
		}
		
		$this->doCheckAndPutConfigFileContents(true);
				
	}

	function updateDatabaseForV2_5_1() {
		
		updateOption('IWPSiteURL', 'https://infinitewp.com/');
		updateOption('supportURL', 'https://support.infinitewp.com/');

		//adding passive option to panel's ftp creds
		$FTPCredentials = unserialize(getOption('FTPCredentials'));
		if(!empty($FTPCredentials['HOST']) && !isset($FTPCredentials['PASV'])){
			$FTPCredentials['PASV'] = 1;
			updateOption('FTPCredentials', serialize($FTPCredentials));
		}

		if(defined('APP_MAIL_FROM_EMAIL_NAME') && APP_MAIL_FROM_EMAIL_NAME){
			//saving APP_MAIL_FROM_EMAIL_NAME php constant details to DB
			$emailSettings = getOption("emailSettings");
			if(!empty($emailSettings)){
				$emailSettings = unserialize($emailSettings);
			}
			if(empty($emailSettings)){
				$emailSettings = array();
			}
			$existingEmailSetting = explode('|', APP_MAIL_FROM_EMAIL_NAME, 2);
			$emailSettings['fromEmail'] = $existingEmailSetting[0];
			if(!empty($existingEmailSetting[1])){
				$emailSettings['fromName'] = $existingEmailSetting[1];
			}
			updateOption('emailSettings', serialize($emailSettings));
		}

		//Removing from email if it is one of the panel user
		$emailSettings = getOption('emailSettings');
		if(!empty($emailSettings)){
			$emailSettings = unserialize($emailSettings);		
			if (!empty($emailSettings['fromEmail']) && DB::getExists("?:users", "email", "email ='".$emailSettings['fromEmail']."'")) {
				unset($emailSettings['fromEmail']);
				updateOption('emailSettings', serialize($emailSettings));
				addNotification($type='N', $title='From email changed', $message='For better delivery of emails, we have changed the From email to default From email. You can change this under Settings → Email Settings.', $state='U', $callbackOnClose='', $callbackReference='');
			}
		}
	}
	
	function updateFilesForV2_5_1() {
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/images/favicon.png', false, 'f');		
	}

	function updateForV2_6_0_beta1() {
		//we dont have updates in config file for v2.6.0beta1.
		
		//we dont have updates in database for v2.6.0beta1.
		
		$this->updateFilesForV2_6_0_beta1();		
	}
	
	function updateFilesForV2_6_0_beta1() {
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/controllers/manageEasyCron.php', false, 'f');		
	}

	function updateForV2_6_0_beta2() {
		//we dont have updates in config file for v2.6.0beta2.
		
		$this->updateDatabaseForV2_6_0_beta2();
		
		//we dont have updates in files for v2.6.0beta2.		
	}

	function updateDatabaseForV2_6_0_beta2() {
		
		$sqlArray = array();
		
		if (version_compare(APP_VERSION, '2.5.2', '!=')) {
			updateOption('supportURL', 'https://support.infinitewp.com/');

			$updateMethod = $GLOBALS['FileSystemObj']->getMethod();
			$isDirectFS = getOption('isDirectFS');
			$isDirectFSAlreadySet = ($isDirectFS != 'N' && $isDirectFS != 'Y') ? false : true;
			if(!$isDirectFSAlreadySet){
				if($updateMethod == 'FTPExt' || $updateMethod == 'sftp'){
					updateOption('isDirectFS', 'N');
				}
				else{
					updateOption('isDirectFS', 'Y');
				}
			}

			$usersNotification = DB::getArray("?:users","userID, notifications","1 ORDER BY userID ASC");
			foreach ($usersNotification as $userNotification) {
				$notificationData = @unserialize($userNotification['notifications']); 
				if(!isset($notificationData['updatesNotificationMail']['translationUpdates'])){
					if ( $notificationData['updatesNotificationMail']['coreUpdates'] == '0' && $notificationData['updatesNotificationMail']['pluginUpdates'] == '0' && $notificationData['updatesNotificationMail']['themeUpdates'] == '0' ) {
						$notificationData['updatesNotificationMail']['translationUpdates'] = '0';
					} else {
						$notificationData['updatesNotificationMail']['translationUpdates'] = '1';
					}
					DB::update("?:users", array('notifications' => serialize($notificationData)), "userID='".$userNotification['userID']."'");
				}
			}

			$sqlArray[] = "ALTER TABLE `?:hide_list` CHANGE `type` `type` ENUM('plugins','themes','core','translations')";
		}
		
		if(!(DB::getExists("SHOW COLUMNS FROM `?:sites` WHERE Field = 'lastFaviconUpdate'"))){
			$sqlArray[] = "ALTER TABLE `?:sites` ADD `lastFaviconUpdate` INT(10) NOT NULL DEFAULT '0' ";
		}
		if(!(DB::getExists("SHOW COLUMNS FROM `?:sites` WHERE Field = 'favicon'"))){
			$sqlArray[] = "ALTER TABLE `?:sites` ADD `favicon` TEXT NULL DEFAULT NULL ";
		}

		$sqlArray[] = "ALTER TABLE `?:history` CHANGE `status` `status` ENUM('writingRequest','pending','initiated','running','completed','scheduled','netError','error','processingResponse','multiCallWaiting','retry') ";
		//updateOption('showBetaWelcome', 1);//should be removed later version
		
		$this->doQuerySQLArray($sqlArray, true);		
	}

	function updateForV2_6_1() {
		//we dont have updates in config file for v2.6.1.
		
		$this->updateDatabaseForV2_6_1();
		
		//we dont have updates in files for v2.6.1.		
	}

	function updateDatabaseForV2_6_1() {
		$this->clearGarbageFaviconsForV2_6_1();		
	}
	
	function clearGarbageFaviconsForV2_6_1() {
		$sitesData = DB::getArray("?:sites", "siteID, favicon","1");
		foreach ($sitesData as $siteData) {
			if ($siteData['favicon'] == 'default' || empty($siteData['favicon'])) {
				continue;
			}
			if(file_exists(APP_ROOT."/".$siteData['favicon'])) {
				continue;
			}
			/*if(!empty($siteData['favicon']) && $siteData['favicon'] != 'default' && !file_exists(APP_ROOT."/".$siteData['favicon'])) {
				
			}*/
			DB::UPDATE("?:sites",array('favicon' => NULL , 'lastFaviconUpdate' => 0 ), "siteID =".$siteData['siteID']);
		}			
	}

	function updateForV2_7_0_beta1() {
		
		$this->updateConfigFileForV2_7_0_beta1();
		
		$this->updateDatabaseForV2_7_0_beta1();
		
		//we dont have updates in files for v270beta1.		
	}
	
	function updateConfigFileForV2_7_0_beta1() {
		
		$this->configFileContents = file_get_contents(APP_ROOT . '/config.php');
		
		$this->isConfigFileEmpty(true);
		
		//removing SQL_DRIVER constant from config.php
		if (strstr($this->configFileContents, 'SQL_DRIVER')) {
			$this->configFileContents = preg_replace('/\s*define\(\s*\'SQL_DRIVER.*\R/', '', $this->configFileContents);
		}
		
		$this->doCheckAndPutConfigFileContents(true);
				
	}
	
	function updateDatabaseForV2_7_0_beta1() {
		
		$sqlArray = array();
			
		$this->modifyDuplicateFavoritesForV2_6_1();
		
		$sqlArray[] = "CREATE TABLE IF NOT EXISTS `?:favourite_groups` (`groupID` int(10) unsigned NOT NULL AUTO_INCREMENT,`name` varchar(255) DEFAULT NULL,`type` varchar(255) DEFAULT NULL, PRIMARY KEY (`groupID`), UNIQUE KEY `name_type_unique` (`name`(141),`type`(50)))".$tableEnv.";";
		
		$sqlArray[] = "CREATE TABLE IF NOT EXISTS `?:favourites_groups_map` (`ID` int(10) unsigned NOT NULL AUTO_INCREMENT, `groupID` int(10) unsigned NOT NULL, `favouriteID` int(10) unsigned NOT NULL, PRIMARY KEY(`ID`), UNIQUE KEY `groupID_favouriteID_unique` (`groupID`,`favouriteID`))".$tableEnv.";";
		
		if(!(DB::getExists("SHOW COLUMNS FROM `?:history` WHERE Field = 'notifyFailed'"))){
			$sqlArray[] = "ALTER TABLE `?:history` ADD `notifyFailed` ENUM('pending','checked','sent') NULL DEFAULT NULL , ADD INDEX (`notifyFailed`)";
		}
		
		$sqlArray[] = "CREATE TABLE IF NOT EXISTS `?:login_logs` (`ID` int(10) unsigned NOT NULL AUTO_INCREMENT, `userID` int(10) unsigned NOT NULL, `email` varchar(45) DEFAULT NULL, `accessLevel` enum('admin', 'manager', 'others') DEFAULT 'others', `time` int(10) unsigned NOT NULL, `browserInfo` varchar(45) DEFAULT NULL,`loginAuthType`  enum('authNone', 'authBasic', 'authDuo') DEFAULT NULL,`IP` varchar(45) DEFAULT NULL,`error` varchar(255) DEFAULT NULL,`loginAttemptStatus` enum('success', 'error') DEFAULT NULL,`protocol`enum('HTTPS', 'HTTP') DEFAULT NULL,`loginRedirect` enum('authNone', 'authBasic', 'authDuo') DEFAULT NULL, `browser` varchar(255) DEFAULT NULL,PRIMARY KEY (`ID`))".$tableEnv.";";

		if (!DB::getExists("SHOW KEYS FROM `?:favourites` where Key_name = 'name_type_unique'")) {
			$sqlArray[] = "ALTER TABLE `?:favourites` ADD UNIQUE `name_type_unique` (`type`, `name`(191))";
		}
		//updateOption('showBetaWelcome', 1);//should be removed later version 		
		
		$this->doQuerySQLArray($sqlArray, true);		
	}
	
	function modifyDuplicateFavoritesForV2_6_1() {
		
		$sql = "SELECT name, COUNT(*) dulplicates FROM `?:favourites` GROUP BY name HAVING dulplicates > 1";
		$dulplicatesData = DB::getArray($sql);
		
		if (empty($dulplicatesData) || !is_array($dulplicatesData)) {
			return false;
		}
		foreach ($dulplicatesData as $dulplicateData) {
			$name = $dulplicateData['name'];
			$sqlTemp = "SELECT ID FROM `?:favourites` where name = '$name'";
			$dulplicateDataIDs = DB::getFields($sqlTemp);
			if (empty($dulplicateDataIDs) || !is_array($dulplicateDataIDs)) {
				continue;
			}
			$flag = 0;
			foreach ($dulplicateDataIDs as $dulplicateDataID) {
				$sqlArray = array();
				$flag++;
				if ($flag == 1) {
					continue;
				}
				do {
					$finalData = $this->modifyDuplicateFavoritesNewUniqueNameExistForV2_6_1($name, $flag);
					$flag++;
				}while ($finalData === false);
				$uniqueName = $finalData['uniqueName'];
				$flag = $finalData['flag'];
				$sqlArray[] = "UPDATE `?:favourites` SET name = '$uniqueName' where ID = ".$dulplicateDataID;
				
				$this->doQuerySQLArray($sqlArray, true);
			}
		}		
	}
	
	function modifyDuplicateFavoritesNewUniqueNameExistForV2_6_1($name, $flag){
		$uniqueName = $name . " (" . $flag . ")";
		if (DB::getExists("SELECT * FROM `?:favourites` where name = '$uniqueName'")) {
			return false;
		}
		$finalData['uniqueName'] = $uniqueName;
		$finalData['flag'] = $flag;
		return $finalData;
	}

	function updateForV2_7_0_beta2() {
		
		//we dont have updates in config file for v2.7.0beta2.
		
		$this->updateDatabaseForV2_7_0_beta2();
		
		//we dont have updates in files for v2.7.0beta2.		
	}

	function updateDatabaseForV2_7_0_beta2() {
		
		$sqlArray = array();
			
		if (!DB::getExists("SHOW INDEX FROM `?:login_logs` where Key_name = 'time'")) {
			$sqlArray[] = "ALTER TABLE `?:login_logs` ADD INDEX `time` (`time`)";
		} 		
		
		$this->doQuerySQLArray($sqlArray, true);		
	}

	function updateForV2_7_0() {
		
		//we dont have updates in config file for v2.7.0.
		
		$this->updateDatabaseForV2_7_0();
		
		//we dont have updates in files for v2.7.0.		
	}

	function updateDatabaseForV2_7_0() {
		
		$sqlArray = array();
			
		updateOption('isUpdatePageEmailCronReqNotified', 1);
		updateOption('isInitialSetupCompleted', 1);
		updateOption('show2_7AddonUpdatePopup',1); 		
		
		$this->doQuerySQLArray($sqlArray, true);		
	}
	
	function updateForV2_8_0_beta1() {
		
		//we dont have updates in config file for v2.8.0beta1.
		updateOption('show2_7AddonUpdatePopup',0);//No need to show v2.7.0 update popup in v2.8.0beta 
		$this->updateDatabaseForV2_8_0_beta1();
		
		$this->updateFilesForV2_8_0_beta1();
	}

	function updateDatabaseForV2_8_0_beta1() {
		
		$this->updateDatabaseForV2_8_0_beta1_db_schema_balancing();
		$sqlArray = array();
			
		if (!DB::getExists("SHOW COLUMNS FROM `?:sites` WHERE Field = 'type'")) {
			$sqlArray[] = "ALTER TABLE `?:sites` ADD `type` ENUM('normal','staging') NOT NULL DEFAULT 'normal', ADD INDEX (`type`)";
		}
		if(!(DB::getExists("SHOW COLUMNS FROM `?:sites` WHERE Field = 'stagingBaseSiteID'"))){
			$sqlArray[] = "ALTER TABLE `?:sites` ADD `stagingBaseSiteID` INT(10) UNSIGNED NULL DEFAULT NULL";
		}
		if (!DB::getExists("SHOW COLUMNS FROM `?:sites` WHERE Field = 'stagingFtpDetails'")) {
			$sqlArray[] = "ALTER TABLE `?:sites` ADD `stagingFtpDetails` TEXT NULL DEFAULT NULL";
		}
		if (!DB::getExists("SHOW COLUMNS FROM `?:sites` WHERE Field = 'ftpDetails'")) {
			$sqlArray[] = "ALTER TABLE `?:sites` ADD `ftpDetails` TEXT NULL DEFAULT NULL";
		}		

		//updateOption('showBetaWelcome', 1);//should be removed later version
		
		$this->doQuerySQLArray($sqlArray, true);		
	}

	function updateDatabaseForV2_8_0_beta1_db_schema_balancing() {
		
		$sqlArray = array();
			
		updateOption('serviceURL', 'https://service.infinitewp.com/'); //We can remove it after few versions.
		
		$sqlArray[] = "ALTER TABLE `?:addons` CHANGE `updateCurrentVersion` `updateCurrentVersion` VARCHAR( 40 ) DEFAULT NULL";
		
		if (DB::getExists("SHOW KEYS FROM `?:history` WHERE Key_name = 'type_2'")) {
			$sqlArray[] = "ALTER TABLE `?:history` DROP INDEX `type_2`";
		}

		if (DB::getExists("SHOW KEYS FROM `?:history` WHERE Key_name = 'action_2'")) {
			$sqlArray[] = "ALTER TABLE `?:history` DROP INDEX `action_2`";
		}

		if (DB::getExists("SHOW KEYS FROM `?:history_additional_data` WHERE Key_name = 'historyID_2'")) {
			$sqlArray[] = "ALTER TABLE `?:history_additional_data` DROP INDEX `historyID_2`";
		}
		
		if (DB::getExists("SHOW KEYS FROM `?:history_additional_data` WHERE Key_name = 'historyID_uniqueName'")) {
			$sqlArray[] = "ALTER TABLE `?:history_additional_data` DROP INDEX `historyID_uniqueName`";
			$sqlArray[] = "ALTER TABLE `?:history_additional_data` ADD UNIQUE KEY `historyID_uniqueName` (`historyID`,`uniqueName`(150))";
		}		
		
		if (DB::getExists("SHOW KEYS FROM `?:options` WHERE Key_name = 'optionName'")) {
			$sqlArray[] = "ALTER TABLE `?:options` DROP INDEX `optionName`";
			$sqlArray[] = "ALTER TABLE `?:options` ADD UNIQUE KEY `optionName` (`optionName`(191))";
		}

		if (DB::getExists("SHOW KEYS FROM `?:sites` WHERE Key_name = 'siteURL_UNIQUE'")) {
			$sqlArray[] = "ALTER TABLE `?:sites` DROP INDEX `siteURL_UNIQUE`";
			$sqlArray[] = "ALTER TABLE `?:sites` ADD UNIQUE KEY `siteURL_UNIQUE` (`URL`(191))";			
		}

		$sqlArray[] = "ALTER TABLE `?:sites` CHANGE `WPVersion` `WPVersion` varchar(40) DEFAULT NULL";
		
		if(DB::getExists("SHOW COLUMNS FROM `?:sites` WHERE Field = 'lastFaviconUpdate'")){
			$sqlArray[] = "ALTER TABLE `?:sites` CHANGE `lastFaviconUpdate` `lastFaviconUpdate` INT(10) unsigned NOT NULL DEFAULT 0";
		}
		
		if (!DB::getExists("SHOW KEYS FROM `?:favourite_groups` WHERE Key_name = 'name_type_unique'")) {
			$sqlArray[] = "ALTER TABLE `?:favourite_groups` ADD UNIQUE KEY `name_type_unique` (`name`(141),`type`(50))";			
		}
		
		if (!DB::getExists("SHOW COLUMNS FROM `?:favourite_groups` WHERE Field = 'name'")) {
			$sqlArray[] = "ALTER TABLE `?:favourite_groups` CHANGE `name` `name` varchar(255) DEFAULT NULL";			
		}
		
		if (!DB::getExists("SHOW COLUMNS FROM `?:favourite_groups` WHERE Field = 'type'")) {
			$sqlArray[] = "ALTER TABLE `?:favourite_groups` CHANGE `type` `type` varchar(255) DEFAULT NULL";			
		}		
		
		if (DB::getExists("SHOW KEYS FROM `?:favourites_groups_map` WHERE Key_name = 'groupID'")) {
			$sqlArray[] = "ALTER TABLE `?:favourites_groups_map` DROP INDEX `groupID`";			
		}
		
		if (!DB::getExists("SHOW KEYS FROM `?:favourites_groups_map` WHERE Key_name = 'groupID_favouriteID_unique'")) {
			$sqlArray[] = "ALTER TABLE `?:favourites_groups_map` ADD UNIQUE KEY `groupID_favouriteID_unique` (`groupID`,`favouriteID`)";			
		}			
		
		$this->doQuerySQLArray($sqlArray, true);		
	}
	
	function updateFilesForV2_8_0_beta1() {
		
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/css/custom_checkbox.css', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/css/datepicker.css', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/css/fileuploader.css', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/css/ie8nlr.css', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/css/jPaginator.css', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/css/jquery.qtip.css', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/css/layout.css', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/css/lionbars.css', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/css/nanoscroller.css', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/css/password.css', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/css/reset.css', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/css/select2.css', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/js/ZeroClipboard.js', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/js/datepicker.js', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/js/eye.js', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/js/fileuploader.js', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/js/jPaginator-min.js', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/js/jquery.mousewheel.js', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/js/jquery.paginate.js', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/js/jquery.qtip.js', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/js/jquery.unveil.js', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/js/layout.js', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/js/strength.js', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/js/utils.js', false, 'f');
		$GLOBALS['FileSystemObj']->delete($GLOBALS['updatePanelLocation'].'/js/var_dump.js', false, 'f');		
	}	

	function updateForV2_9_0_beta1(){
		updateOption('convertInnoDBToMyisam', serialize(array('0'=>1)));
	}

	function updateForV2_9_0_beta2(){
		updateOption('convertInnoDBToMyisam', serialize(array('0'=>1, '1' =>2)));
	}

	function updateForV2_9_1(){
		deleteOption('showConversionNeededTableNames');
		deleteOption('InnoDBConversionLogs');
		deleteOption('conversionNeededTables');
		updateOption('convertInnoDBToMyisam', serialize(array('0'=>1, '1' =>2)));
	}

	function updateForV2_10_0_beta1(){
		$this->updateDatabaseForV2_10_0_beta1();
	}

	function updateForV2_10_0_beta2(){
		$this->updateDatabaseForV2_10_0_beta2();
	}

	function updateForV2_10_0(){
		$this->updateDatabaseForV2_10_0();
	}

	function updateForV2_10_1(){
		$sqlArray = array();
		$sqlArray[] = "TRUNCATE TABLE  `?:site_stats`";
		$sqlArray[] = "TRUNCATE TABLE  `?:update_stats`";
		$this->doQuerySQLArray($sqlArray, true);
	}
	
	function updateDatabaseForV2_10_0_beta1(){
		$sqlArray = array();
		if(!(DB::getExists("SHOW COLUMNS FROM `?:site_stats` WHERE Field = 'updatePluginCounts'"))){
			$sqlArray[] = "ALTER TABLE `?:site_stats` ADD `updatePluginCounts` INT(10) UNSIGNED NULL DEFAULT 0";
		}
		if(!(DB::getExists("SHOW COLUMNS FROM `?:site_stats` WHERE Field = 'updateThemeCounts'"))){
			$sqlArray[] = "ALTER TABLE `?:site_stats` ADD `updateThemeCounts` INT(10) UNSIGNED NULL DEFAULT 0";
		}
		if(!(DB::getExists("SHOW COLUMNS FROM `?:site_stats` WHERE Field = 'isTranslationUpdateAvailable'"))){
			$sqlArray[] = "ALTER TABLE `?:site_stats` ADD `isTranslationUpdateAvailable` INT(10) UNSIGNED NULL DEFAULT 0";
		}
		if(!(DB::getExists("SHOW COLUMNS FROM `?:site_stats` WHERE Field = 'isCoreUpdateAvailable'"))){
			$sqlArray[] = "ALTER TABLE `?:site_stats` ADD `isCoreUpdateAvailable` enum('1', '0') NULL DEFAULT '0'";
		}
		if(!(DB::getExists("SHOW COLUMNS FROM `?:site_stats` WHERE Field = 'updateInfo'"))){
			$sqlArray[] = "ALTER TABLE `?:site_stats` ADD `updateInfo` LONGTEXT NULL DEFAULT NULL";
		}
		if (!DB::getExists("SHOW INDEX FROM `?:site_stats` where Key_name = 'siteID'")) {
			$sqlArray[] = "ALTER TABLE `?:site_stats` ADD INDEX `siteID` (`siteID`)";
		} 
		$sqlArray[] = "TRUNCATE TABLE  `?:site_stats`";
		$sqlArray[] = "CREATE TABLE IF NOT EXISTS `?:update_stats` (`ID` int(10) unsigned NOT NULL AUTO_INCREMENT, `type` enum('plugin', 'theme', 'core', 'translation') DEFAULT NULL, `URL` TEXT  DEFAULT NULL, `name` varchar(45) DEFAULT NULL, `updatePresentCount` INT(10) UNSIGNED NULL DEFAULT NULL,PRIMARY KEY (`ID`), KEY `ID` (`ID`) )".$tableEnv.";";
		$this->doQuerySQLArray($sqlArray, true);
		updateOption('showBetaWelcome', 1);
	}

	function updateDatabaseForV2_10_0_beta2(){
		$sqlArray = array();
		$sqlArray[] = "TRUNCATE TABLE  `?:site_stats`";
		$sqlArray[] = "TRUNCATE TABLE  `?:update_stats`";
		$this->doQuerySQLArray($sqlArray, true);
		updateOption('showBetaWelcome', 1);
	}

	function updateDatabaseForV2_10_0(){
		updateOption('showBetaWelcome', 0);
		updateOption('pricingPlanTypes', serialize(array('starter','developer','freelancer')));
	}
        
    function updateForV2_11_0_beta1(){
		$this->updateDatabaseForV2_11_0_beta1();
	}
        
	function updateDatabaseForV2_11_0_beta1(){
		$sqlArray = array();
		if(!(DB::getExists("SHOW COLUMNS FROM `?:history` WHERE Field = 'connection_method'"))){
		    $sqlArray[] = "ALTER TABLE `?:history` ADD `connection_method` text NULL";
		}
		if(sizeof($sqlArray)>0){
		    $this->doQuerySQLArray($sqlArray, true);
		}
	        
	}

	function updateForV2_10_2(){
		updateOption('showReSchedulePopup', 1);
	}

	function updateForV2_10_3(){
		$sqlArray = array();
		$sqlArray[] = "TRUNCATE TABLE  `?:site_stats`";
		$sqlArray[] = "TRUNCATE TABLE  `?:update_stats`";
		$this->doQuerySQLArray($sqlArray, true);
	}

	function updateForV2_12_0beta2(){
		deleteOption('activeJobs');
	}

	function updateForV2_12_0beta3(){
		$this->updateDatabaseForV2_12_0beta3();
	}

	function updateDatabaseForV2_12_0beta3(){
		$sqlArray = array();
		if(!(DB::getExists("SHOW COLUMNS FROM `?:history_additional_data` WHERE Field = 'successMsg'"))){
			$sqlArray[] = "ALTER TABLE `?:history_additional_data` ADD `successMsg` text NULL";
		}
		$this->doQuerySQLArray($sqlArray, true);
	}

}