Esempio n. 1
0
 /**
  * @see DbCore::connect()
  */
 public function connect()
 {
     $socket = false;
     $port = false;
     if (strpos($this->server, ':') !== false) {
         list($server, $port) = explode(':', $this->server);
         if (is_numeric($port) === false) {
             $socket = $port;
             $port = false;
         }
     } elseif (strpos($this->server, '/') !== false) {
         $socket = $this->server;
     }
     if ($socket) {
         $this->link = @new mysqli(null, $this->user, $this->password, $this->database, null, $socket);
     } elseif ($port) {
         $this->link = @new mysqli($server, $this->user, $this->password, $this->database, $port);
     } else {
         $this->link = @new mysqli($this->server, $this->user, $this->password, $this->database);
     }
     // Do not use object way for error because this work bad before PHP 5.2.9
     if (mysqli_connect_error()) {
         Tools14::displayError(sprintf(Tools14::displayError('Link to database cannot be established: %s'), mysqli_connect_error()));
         exit;
     }
     // UTF-8 support
     if (!$this->link->query('SET NAMES \'utf8\'')) {
         Tools14::displayError(Tools14::displayError('PrestaShop Fatal error: no utf-8 support. Please check your server configuration.'));
         exit;
     }
     return $this->link;
 }
Esempio n. 2
0
 /**
  * @see DbCore::connect()
  */
 public function connect()
 {
     try {
         $this->link = $this->_getPDO($this->server, $this->user, $this->password, $this->database, 5);
     } catch (PDOException $e) {
         die(sprintf(Tools14::displayError('Link to database cannot be established: %s'), $e->getMessage()));
         exit;
     }
     // UTF-8 support
     if (!is_object($this->link) || $this->link->exec('SET NAMES \'utf8\'') === false) {
         Tools14::displayError('PrestaShop Fatal error: no utf-8 support. Please check your server configuration.');
         exit;
     }
     return $this->link;
 }
Esempio n. 3
0
 /**
  * @see DbCore::connect()
  */
 public function connect()
 {
     if (!defined('_PS_MYSQL_REAL_ESCAPE_STRING_')) {
         define('_PS_MYSQL_REAL_ESCAPE_STRING_', function_exists('mysql_real_escape_string'));
     }
     if (!($this->link = @mysql_connect($this->server, $this->user, $this->password))) {
         Tools14::displayError('Link to database cannot be established.');
         exit;
     }
     if (!$this->set_db($this->database)) {
         Tools14::displayError('The database selection cannot be made.');
         exit;
     }
     // UTF-8 support
     if (!mysql_query('SET NAMES \'utf8\'', $this->link)) {
         Tools14::displayError('PrestaShop Fatal error: no utf-8 support. Please check your server configuration.');
     }
     return $this->link;
 }
Esempio n. 4
0
}
*/
ob_start();
$timerStart = microtime(true);
$currentFileName = array_reverse(explode("/", $_SERVER['SCRIPT_NAME']));
// $cookieLifetime = (time() + (((int)Configuration::get('PS_COOKIE_LIFETIME_BO') > 0 ? (int)Configuration::get('PS_COOKIE_LIFETIME_BO') : 1)* 3600));
$cookieLifetime = time() + 84600;
$adminFilename = trim($_POST['dir'], '/') . '/';
// die(info($adminFilename));
require_once AUTOUPGRADE_MODULE_DIR . 'Tools14.php';
require_once AUTOUPGRADE_MODULE_DIR . 'AdminSelfTab.php';
require_once AUTOUPGRADE_MODULE_DIR . 'AdminSelfUpgrade.php';
// $needClass = array('Cookie'); //, 'ObjectModel', 'Db', 'MySQL', 'SubDomain', 'Tools');
$needClass = array();
foreach ($needClass as $class) {
    if (!class_exists($class, false)) {
        if (file_exists(_PS_ADMIN_DIR_ . '/autoupgrade/' . $class . '.php')) {
            require_once _PS_ADMIN_DIR_ . '/autoupgrade/' . $class . '.php';
            info($class, 'from autoupgrade');
        } else {
            require_once _PS_ROOT_DIR_ . '/classes/' . $class . '.php';
        }
        if (version_compare(_PS_VERSION_, '1.4', '<')) {
            if (!class_exists($class, false) and class_exists($class . 'Core', false)) {
                eval('class ' . $class . ' extends ' . $class . 'Core{}');
            }
        }
    }
}
$currentIndex = $_SERVER['SCRIPT_NAME'] . (($tab = Tools14::getValue('tab')) ? '?tab=' . $tab : '');
Esempio n. 5
0
/**
 * @deprecated
 */
function nl2br2($string)
{
    return Tools14::nl2br($string);
}
Esempio n. 6
0
 /**
  * Sanitize data which will be injected into SQL query
  *
  * @param string $string SQL data which will be injected into SQL query
  * @param boolean $html_ok Does data contain HTML code ? (optional)
  * @return string Sanitized data
  */
 public function escape($string, $html_ok = false)
 {
     if (_PS_MAGIC_QUOTES_GPC_) {
         $string = stripslashes($string);
     }
     if (!is_numeric($string)) {
         $string = $this->_escape($string);
         if (!$html_ok) {
             $string = strip_tags(Tools14::nl2br($string));
         }
     }
     return $string;
 }
    define('_PS_ROOT_DIR_', realpath(_PS_ADMIN_DIR_ . '/../'));
}
// ajax-upgrade-tab is located in admin/autoupgrade directory
require_once _PS_ROOT_DIR_ . '/config/settings.inc.php';
//require(_PS_ADMIN_DIR_.'/functions.php');
include AUTOUPGRADE_MODULE_DIR . 'init.php';
// this is used to set this->ajax = true in the constructor
global $ajax;
$ajax = true;
$adminObj = new AdminSelfUpgrade();
if (is_object($adminObj)) {
    $adminObj->ajax = 1;
    if ($adminObj->checkToken()) {
        // the differences with index.php is here
        $adminObj->ajaxPreProcess();
        $action = Tools14::getValue('action');
        // no need to use displayConf() here
        if (!empty($action) and method_exists($adminObj, 'ajaxProcess' . $action)) {
            $adminObj->{'ajaxProcess' . $action}();
        } else {
            $adminObj->ajaxProcess();
        }
        // @TODO We should use a displayAjaxError
        $adminObj->displayErrors();
        if (!empty($action) and method_exists($adminObj, 'displayAjax' . $action)) {
            $adminObj->{'displayAjax' . $action}();
        } else {
            $adminObj->displayAjax();
        }
    } else {
        // If this is an XSS attempt, then we should only display a simple, secure page
Esempio n. 8
0
 protected function _postConfig($fields)
 {
     global $currentIndex, $smarty;
     $languages = Language::getLanguages(false);
     if (method_exists('Tools', 'clearCache')) {
         Tools14::clearCache($smarty);
     }
     /* Check required fields */
     foreach ($fields as $field => $values) {
         if (isset($values['required']) and $values['required']) {
             if (isset($values['type']) and $values['type'] == 'textLang') {
                 foreach ($languages as $language) {
                     if (($value = Tools14::getValue($field . '_' . $language['id_lang'])) == false and (string) $value != '0') {
                         $this->_errors[] = Tools14::displayError('field') . ' <b>' . $values['title'] . '</b> ' . Tools14::displayError('is required.');
                     }
                 }
             } elseif (($value = Tools14::getValue($field)) == false and (string) $value != '0') {
                 $this->_errors[] = Tools14::displayError('field') . ' <b>' . $values['title'] . '</b> ' . Tools14::displayError('is required.');
             }
         }
     }
     /* Check fields validity */
     foreach ($fields as $field => $values) {
         if (isset($values['type']) and $values['type'] == 'textLang') {
             foreach ($languages as $language) {
                 if (Tools14::getValue($field . '_' . $language['id_lang']) and isset($values['validation'])) {
                     if (!Validate::$values['validation'](Tools14::getValue($field . '_' . $language['id_lang']))) {
                         $this->_errors[] = Tools14::displayError('field') . ' <b>' . $values['title'] . '</b> ' . Tools14::displayError('is invalid.');
                     }
                 }
             }
         } elseif (Tools14::getValue($field) and isset($values['validation'])) {
             if (!Validate::$values['validation'](Tools14::getValue($field))) {
                 $this->_errors[] = Tools14::displayError('field') . ' <b>' . $values['title'] . '</b> ' . Tools14::displayError('is invalid.');
             }
         }
     }
     /* Default value if null */
     foreach ($fields as $field => $values) {
         if (!Tools14::getValue($field) and isset($values['default'])) {
             $_POST[$field] = $values['default'];
         }
     }
     /* Save process */
     if (!sizeof($this->_errors)) {
         if (Tools14::isSubmit('submitAppearanceconfiguration')) {
             if (isset($_FILES['PS_LOGO']['tmp_name']) and $_FILES['PS_LOGO']['tmp_name']) {
                 if ($error = checkImage($_FILES['PS_LOGO'], 300000)) {
                     $this->_errors[] = $error;
                 }
                 if (!($tmpName = tempnam(_PS_TMP_IMG_DIR_, 'PS')) or !move_uploaded_file($_FILES['PS_LOGO']['tmp_name'], $tmpName)) {
                     return false;
                 } elseif (!@imageResize($tmpName, _PS_IMG_DIR_ . 'logo.jpg')) {
                     $this->_errors[] = 'an error occurred during logo copy';
                 }
                 unlink($tmpName);
             }
             if (isset($_FILES['PS_LOGO_MAIL']['tmp_name']) and $_FILES['PS_LOGO_MAIL']['tmp_name']) {
                 if ($error = checkImage($_FILES['PS_LOGO_MAIL'], 300000)) {
                     $this->_errors[] = $error;
                 }
                 if (!($tmpName = tempnam(_PS_TMP_IMG_DIR_, 'PS_MAIL')) or !move_uploaded_file($_FILES['PS_LOGO_MAIL']['tmp_name'], $tmpName)) {
                     return false;
                 } elseif (!@imageResize($tmpName, _PS_IMG_DIR_ . 'logo_mail.jpg')) {
                     $this->_errors[] = 'an error occurred during logo copy';
                 }
                 unlink($tmpName);
             }
             if (isset($_FILES['PS_LOGO_INVOICE']['tmp_name']) and $_FILES['PS_LOGO_INVOICE']['tmp_name']) {
                 if ($error = checkImage($_FILES['PS_LOGO_INVOICE'], 300000)) {
                     $this->_errors[] = $error;
                 }
                 if (!($tmpName = tempnam(_PS_TMP_IMG_DIR_, 'PS_INVOICE')) or !move_uploaded_file($_FILES['PS_LOGO_INVOICE']['tmp_name'], $tmpName)) {
                     return false;
                 } elseif (!@imageResize($tmpName, _PS_IMG_DIR_ . 'logo_invoice.jpg')) {
                     $this->_errors[] = 'an error occurred during logo copy';
                 }
                 unlink($tmpName);
             }
             if (isset($_FILES['PS_STORES_ICON']['tmp_name']) and $_FILES['PS_STORES_ICON']['tmp_name']) {
                 if ($error = checkImage($_FILES['PS_STORES_ICON'], 300000)) {
                     $this->_errors[] = $error;
                 }
                 if (!($tmpName = tempnam(_PS_TMP_IMG_DIR_, 'PS_STORES_ICON')) or !move_uploaded_file($_FILES['PS_STORES_ICON']['tmp_name'], $tmpName)) {
                     return false;
                 } elseif (!@imageResize($tmpName, _PS_IMG_DIR_ . 'logo_stores.gif')) {
                     $this->_errors[] = 'an error occurred during logo copy';
                 }
                 unlink($tmpName);
             }
             $this->uploadIco('PS_FAVICON', _PS_IMG_DIR_ . 'favicon.ico');
         }
         /* Update settings in database */
         if (!sizeof($this->_errors)) {
             foreach ($fields as $field => $values) {
                 unset($val);
                 if (isset($values['type']) and $values['type'] == 'textLang') {
                     foreach ($languages as $language) {
                         $val[$language['id_lang']] = isset($values['cast']) ? $values['cast'](Tools14::getValue($field . '_' . $language['id_lang'])) : Tools14::getValue($field . '_' . $language['id_lang']);
                     }
                 } else {
                     $val = isset($values['cast']) ? $values['cast'](Tools14::getValue($field)) : Tools14::getValue($field);
                 }
                 Configuration::updateValue($field, $val);
             }
             Tools14::redirectAdmin($currentIndex . '&conf=6' . '&token=' . $this->token);
         }
     }
 }
    private function _getJsInit()
    {
        global $currentIndex;
        if (method_exists('Tools', 'getAdminTokenLite')) {
            $token_preferences = Tools::getAdminTokenLite('AdminPreferences');
        } else {
            $token_preferences = Tools14::getAdminTokenLite('AdminPreferences');
        }
        $js = '';
        $js .= '
function ucFirst(str) {
	if (str.length > 0) {
		return str[0].toUpperCase() + str.substring(1);
	}
	else {
		return str;
	}
}

function cleanInfo(){
	$("#infoStep").html("reset<br/>");
}

function updateInfoStep(msg){
	if (msg)
	{
		$("#infoStep").html(msg);
		$("#infoStep").attr({ scrollTop: $("#infoStep").attr("scrollHeight") });
	}
}

function addError(msg){
	if (msg)
		$("#errorWindow").html(msg);
}

function addQuickInfo(arrQuickInfo){
	if (arrQuickInfo)
	{
		$("#quickInfo").show();
		for(i=0;i<arrQuickInfo.length;i++)
			$("#quickInfo").append(arrQuickInfo[i]+"<br/>");
		// Note : jquery 1.6 make uses of prop() instead of attr()
		$("#quickInfo").prop({ scrollTop: $("#quickInfo").prop("scrollHeight") },1);
	}
}';
        if ($this->manualMode) {
            $js .= 'var manualMode = true;';
        } else {
            $js .= 'var manualMode = false;';
        }
        $js .= '
var firstTimeParams = ' . $this->buildAjaxResult() . ';
firstTimeParams = firstTimeParams.nextParams;
firstTimeParams.firstTime = "1";

$(document).ready(function(){
	$(".upgradestep").click(function(e)
	{
		e.preventDefault();
		// $.scrollTo("#options")
	});

	// more convenient to have that param for handling success and error
	var requestParams;
		
		// set timeout to 5 minutes (download can be long)?
		$.ajaxSetup({timeout:300000});

	
	// prepare available button here, without params ?
	prepareNextButton("#upgradeNow",firstTimeParams);
	prepareNextButton("#rollback",firstTimeParams);
	prepareNextButton("#restoreDb",firstTimeParams);
	prepareNextButton("#restoreFiles",firstTimeParams);

});

/**
 * parseXMLResult is used to handle the return value of the doUpgrade method
 * @xmlRet xml return value
 * @var previousParams contains the precedent post values (to conserve post datas during upgrade db process)
 */

function checkConfig(res)
{
	testRequiredList = $(res.testList[0].test);
	configIsOk = true;

	testRequiredList.each(function()
	{
		result = $(this).attr("result");
		if (result == "fail") configIsOk = false;
	});

	if (!configIsOk)
	{
		alert("Configuration install problem");
		return "fail";
	}
	else
		return "ok";
}

function handleXMLResult(xmlRet, previousParams)
{
	// use xml2json and put the result in the global var
	// this will be used in after** javascript functions
	resGlobal = $.xml2json(xmlRet);
	result = "ok";
	switch(previousParams.upgradeDbStep) 
	{
		case 0: // getVersionFromDb
		resGlobal.result = "ok";
		break;
		case 1: // getVersionFromDb
		result = resGlobal.result;
		break;
		case 2: // checkConfig
		result = checkConfig(resGlobal);
		break;
		case 3: // doUpgrade:
		result = resGlobal.result;
		break;
		case 4: // upgradeComplete
		result = resGlobal.result;
		break;
	}

	if (result == "ok")
	{
		nextParams = previousParams;
		nextParams.upgradeDbStep = parseInt(previousParams.upgradeDbStep)+1;
		if(nextParams.upgradeDbStep >= 4)
		{
			resGlobal.next = "upgradeComplete";
			nextParams.typeResult = "json";
		}
		else 
			resGlobal.next = "upgradeDb";
		resGlobal = {next:resGlobal.next,nextParams:nextParams,status:"ok"};

	}
	else
	{
		$("#dbResultCheck")
			.addClass("fail")
			.removeClass("ok")
			.show("slow");
		$("#dbCreateResultCheck")
			.hide("slow");
		
		// propose rollback if there is an error
		if (confirm("An error happen\\r\\n' . $this->l('You may need to rollback.') . '"))
			resGlobal = {next:"rollback",nextParams:{typeResult:"json"},status:"error"};
	}

	return resGlobal;
};

var resGlobal = {};
function afterUpgradeNow()
{
	$("#upgradeNow").unbind();
	$("#upgradeNow").replaceWith("<span class=\\"button-autoupgrade\\">' . $this->l('Upgrading PrestaShop') . '</span>");
}

function afterUpgradeComplete()
{
	$("#pleaseWait").hide();
	$("#dbResultCheck")
		.addClass("ok")
		.removeClass("fail")
		.html("<p>' . $this->l('upgrade complete. Please check your front-office theme is functionnal (try to make an order, check theme)') . '</p>")
		.show("slow")
		.append("<a href=\\"index.php?tab=AdminPreferences&token=' . $token_preferences . '\\" class=\\"button\\">' . $this->l('activate your shop here') . '</a>");
	$("#dbCreateResultCheck")
		.hide("slow");
	$("#infoStep").html("<h3>' . $this->l('Upgrade Complete ! ') . '</h3>");
}

/**
 * afterBackupDb display the button 
 * 
 */
function afterBackupDb()
{
	$("#restoreDbContainer").html("<a href=\\"\\" class=\\"upgradestep button\\" id=\\"restoreDb\\">restoreDb</a> ' . $this->l('click to restore database') . '");
	prepareNextButton("#restoreDb",{});
}

function afterRestoreDb()
{
	$("#restoreDbContainer").html("");
}

function afterRestoreFiles()
{
	$("#restoreFilesContainer").html("");
}

function afterBackupFiles()
{
	$("#restoreFilesContainer").html("<div id=\\"restoreFilesContainer\\"><a href=\\"\\" class=\\"upgradestep button\\" id=\\"restoreFiles\\">restoreFiles</a> ' . $this->l('click to restore files') . '");
	prepareNextButton("#restoreFiles",{});

}

function doAjaxRequest(action, nextParams){
		$("#pleaseWait").show();
		// myNext, used when json is not available but response is correct
		myNext = nextParams;
		req = $.ajax({
			type:"POST",
			url : "' . ($this->standalone ? __PS_BASE_URI__ . trim($this->adminDir, DIRECTORY_SEPARATOR) . '/autoupgrade/ajax-upgradetab.php' : str_replace('index', 'ajax-tab', $currentIndex)) . '",
			async: true,
			data : {
				dir:"' . trim($this->adminDir, DIRECTORY_SEPARATOR) . '",
				ajaxMode : "1",
				token : "' . $this->token . '",
				tab : "' . get_class($this) . '",
				action : action,
				params : nextParams
			},
			success : function(res,textStatus,jqXHR)
			{
				$("#pleaseWait").hide();
				if(eval("typeof nextParams") == "undefined")
				{
					nextParams = {typeResult : "json"};
				}

				if (nextParams.typeResult == "xml")
				{
					res = handleXMLResult(res,nextParams);
				}
				else
				{
					try{
						res = $.parseJSON(res);
						nextParams = res.nextParams;
					}
					catch(e){
						res = {status : "error"};
						alert("error during "+action);
						/*
						nextParams = {
							error:"0",
							next:"cancelUpgrade",
							nextDesc:"Error detected during ["+action+"] step, reverting...",
							nextQuickInfo:[],
							status:"ok",
							"stepDone":true
						}
						*/
					}
				}

				if (res.status == "ok")
				{
					$("#"+action).addClass("done");
					if (res.stepDone)
						$("#"+action).addClass("stepok");
					
					// if a function "after[action name]" exists, it should be called.
					// This is used for enabling restore buttons for example
					funcName = "after"+ucFirst(action);
					if (typeof funcName == "string" &&
						eval("typeof " + funcName) == "function") {
						eval(funcName+"()");
					}

					handleSuccess(res,nextParams.typeResult);
				}
				else
				{
					// display progression
					$("#"+action).addClass("done");
					$("#"+action).addClass("steperror");
					handleError(res);
				}
			},
			error: function(res,textStatus,jqXHR)
			{
				$("#pleaseWait").hide();
				if (textStatus == "timeout" && action == "download")
				{
					updateInfoStep("' . $this->l('Your server can\'t download the file. Please upload it first by ftp in your admin/autoupgrade directory') . '");
				}
				else
				{
					updateInfoStep("[Server Error] Status message : " + textStatus);
				}
			}
		});
	};

/**
 * prepareNextButton make the button button_selector available, and update the nextParams values
 *
 * @param button_selector $button_selector
 * @param nextParams $nextParams
 * @return void
 */
function prepareNextButton(button_selector, nextParams)
{
	$(button_selector).unbind();
	$(button_selector).click(function(e){
		e.preventDefault();
		$("#currentlyProcessing").show();
';
        if (defined('_PS_MODE_DEV_') and _PS_MODE_DEV_) {
            $js .= 'addQuickInfo(["[DEV] request : "+$(this).attr("id")]);';
        }
        $js .= '
	action = button_selector.substr(1);
	res = doAjaxRequest(action, nextParams);
	});
}

/**
 * handleSuccess
 * res = {error:, next:, nextDesc:, nextParams:, nextQuickInfo:,status:"ok"}
 * @param res $res
 * @return void
 */
function handleSuccess(res)
{
	updateInfoStep(res.nextDesc);
	if (res.next != "")
	{
		addQuickInfo(res.nextQuickInfo);

		$("#"+res.next).addClass("nextStep");
		if (manualMode)
		{
			prepareNextButton("#"+res.next,res.nextParams);
			alert("manually go to "+res.next+" button ");
		}
		else
		{
			// @TODO :
			// 1) instead of click(), call a function.
			doAjaxRequest(res.next,res.nextParams);
			// 2) remove all step link (or show them only in dev mode)
			// 3) when steps link displayed, they should change color when passed
		}
	}
	else
	{
		// Way To Go, end of upgrade process
		addQuickInfo(["End of upgrade process"]);
	}
}

// res = {nextParams, NextDesc}
function handleError(res)
{
	// display error message in the main process thing
	updateInfoStep(res.nextDesc);
	addQuickInfo(res.nextQuickInfo);
	// In case the rollback button has been desactivated, just re-enable it
	prepareNextButton("#rollback",res.nextParams);
	// ask if you want to rollback
	// @TODO !!!
	if (confirm(res.NextDesc+"\\r\\r' . $this->l('Do you want to rollback ?') . '"))
	{
		if (manualMode)
			alert("' . $this->l('Please go manually go to rollback button') . '");
		else
		{
			$("#rollback").click();
		}
			
	}
}
';
        // ajax to check md5 files
        $js .= 'function addModifiedFileList(title, fileList, css_class)
{
	subList = $("<ul class=\\"changedFileList "+css_class+"\\"></ul>");

	$(fileList).each(function(k,v){
		$(subList).append("<li>"+v+"</li>");
	});
	$("#changedList").append("<h3><a class=\\"toggleSublist\\">"+title+"</a> (" + fileList.length + ")</h3>");
	$("#changedList").append(subList);
	$("#cchangedList").append("<br/>");

}';
        $js .= '$(document).ready(function(){
	$.ajax({
			type:"POST",
			url : "' . __PS_BASE_URI__ . trim($this->adminDir, DIRECTORY_SEPARATOR) . '/autoupgrade/ajax-upgradetab.php",
			async: true,
			data : {
				dir:"' . trim($this->adminDir, DIRECTORY_SEPARATOR) . '",
				token : "' . $this->token . '",
				tab : "' . get_class($this) . '",
				action : "checkFilesVersion",
				params : {}
			},
			success : function(res,textStatus,jqXHR)
			{
				res = $.parseJSON(res);
				answer = res.nextParams;
				$("#checkPrestaShopFilesVersion").html("<span> "+answer.msg+" </span> ");
				if (answer.status == "error")
					$("#checkPrestaShopFilesVersion").prepend("<img src=\\"../img/admin/warning.gif\\" /> ");
				else
				{
					$("#checkPrestaShopFilesVersion").prepend("<img src=\\"../img/admin/warning.gif\\" /> ");
					$("#checkPrestaShopFilesVersion").append("<a id=\\"toggleChangedList\\" class=\\"button\\" href=\\"\\">' . $this->l('See or hide the list') . '</a><br/>");
					$("#checkPrestaShopFilesVersion").append("<div id=\\"changedList\\" style=\\"display:none \\"><br/>");
					if(answer.result.core.length)
						addModifiedFileList("' . $this->l('Core file(s)') . '", answer.result.core, "changedImportant");
					if(answer.result.mail.length)
						addModifiedFileList("' . $this->l('Mail file(s)') . '", answer.result.mail, "changedNotice");
					if(answer.result.translation.length)
						addModifiedFileList("' . $this->l('Translation file(s)') . '", answer.result.translation, "changedNotice");

					$("#toggleChangedList").bind("click",function(e){e.preventDefault();$("#changedList").toggle();});
					$(".toggleSublist").live("click",function(e){e.preventDefault();$(this).parent().next().toggle();});
				}
			}
			,
			error: function(res,textStatus,jqXHR)
			{
				if (textStatus == "timeout" && action == "download")
				{
					updateInfoStep("' . $this->l('Your server can\'t download the file. Please upload it first by ftp in your admin/autoupgrade directory') . '");
				}
				else
				{
					updateInfoStep("[Server Error] Status message : " + textStatus);
				}
			}
		})
});';
        return $js;
    }
Esempio n. 10
0
    protected function warnDomainName()
    {
        if ($_SERVER['HTTP_HOST'] != Configuration::get('PS_SHOP_DOMAIN') and $_SERVER['HTTP_HOST'] != Configuration::get('PS_SHOP_DOMAIN_SSL')) {
            $this->displayWarning($this->l('Your are currently connected with the following domain name:') . ' <span style="color: #CC0000;">' . $_SERVER['HTTP_HOST'] . '</span><br />' . $this->l('This one is different from the main shop domain name set in "Preferences > SEO & URLs":') . ' <span style="color: #CC0000;">' . Configuration::get('PS_SHOP_DOMAIN') . '</span><br />
			<a href="index.php?tab=AdminMeta&token=' . Tools14::getAdminTokenLite('AdminMeta') . '#SEO%20%26%20URLs">' . $this->l('Click here if you want to modify the main shop domain name') . '</a>');
        }
    }
Esempio n. 11
0
 public function getXmlFile($xml_localfile, $xml_remotefile, $refresh = false)
 {
     // @TODO : this has to be moved in autoupgrade.php > install method
     if (!is_dir(_PS_ROOT_DIR_ . '/config/xml')) {
         if (is_file(_PS_ROOT_DIR_ . '/config/xml')) {
             unlink(_PS_ROOT_DIR_ . '/config/xml');
         }
         mkdir(_PS_ROOT_DIR_ . '/config/xml', 0777);
     }
     if ($refresh || !file_exists($xml_localfile) || filemtime($xml_localfile) < time() - 3600 * Upgrader::DEFAULT_CHECK_VERSION_DELAY_HOURS) {
         $xml_string = Tools14::file_get_contents($xml_remotefile, false, stream_context_create(array('http' => array('timeout' => 10))));
         $xml = @simplexml_load_string($xml_string);
         if ($xml !== false) {
             file_put_contents($xml_localfile, $xml_string);
         }
     } else {
         $xml = @simplexml_load_file($xml_localfile);
     }
     return $xml;
 }
Esempio n. 12
0
    /**
     * Display configuration form
     *
     * @params string $name Form name
     * @params array $fields Fields settings
     *
     * @global string $currentIndex Current URL in order to keep current Tab
     */
    protected function _displayForm($name, $fields, $tabname, $size, $icon)
    {
        global $currentIndex;
        $defaultLanguage = (int) Configuration::get('PS_LANG_DEFAULT');
        $languages = Language::getLanguages(false);
        $confValues = $this->getConf($fields, $languages);
        $divLangName = $this->getDivLang($fields);
        $required = false;
        echo '
		<script type="text/javascript">
			id_language = Number(' . $defaultLanguage . ');
			
			function addRemoteAddr(){
				var length = $(\'input[name=PS_MAINTENANCE_IP]\').attr(\'value\').length;	
				if (length > 0)
					$(\'input[name=PS_MAINTENANCE_IP]\').attr(\'value\',$(\'input[name=PS_MAINTENANCE_IP]\').attr(\'value\') +\',' . Tools14::getRemoteAddr() . '\');
				else
					$(\'input[name=PS_MAINTENANCE_IP]\').attr(\'value\',\'' . Tools14::getRemoteAddr() . '\');
			}
		</script>
		<form action="' . $currentIndex . '&submit' . $name . $this->table . '=1&token=' . $this->token . '" method="post" enctype="multipart/form-data">
			<fieldset><legend><img src="../img/admin/' . strval($icon) . '.gif" />' . $tabname . '</legend>';
        foreach ($fields as $key => $field) {
            /* Specific line for e-mails settings */
            if (get_class($this) == 'Adminemails' and $key == 'PS_MAIL_SERVER') {
                echo '<div id="smtp" style="display: ' . ((isset($confValues['PS_MAIL_METHOD']) and $confValues['PS_MAIL_METHOD'] == 2) ? 'block' : 'none') . ';">';
            }
            if (isset($field['required']) and $field['required']) {
                $required = true;
            }
            $val = $this->getVal($confValues, $key);
            if (!in_array($field['type'], array('image', 'radio', 'container', 'container_end')) or isset($field['show'])) {
                echo '<div style="clear: both; padding-top:15px;">' . ($field['title'] ? '<label >' . $field['title'] . '</label>' : '') . '<div class="margin-form" style="padding-top:5px;">';
            }
            /* Display the appropriate input type for each field */
            switch ($field['type']) {
                case 'disabled':
                    echo $field['disabled'];
                    break;
                case 'select':
                    echo '
					<select name="' . $key . '"' . (isset($field['js']) === true ? ' onchange="' . $field['js'] . '"' : '') . ' id="' . $key . '">';
                    foreach ($field['list'] as $k => $value) {
                        echo '<option value="' . (isset($value['cast']) ? $value['cast']($value[$field['identifier']]) : $value[$field['identifier']]) . '"' . ($val == $value[$field['identifier']] ? ' selected="selected"' : '') . '>' . $value['name'] . '</option>';
                    }
                    echo '
					</select>';
                    break;
                case 'selectLang':
                    foreach ($languages as $language) {
                        echo '
						<div id="' . $key . '_' . $language['id_lang'] . '" style="margin-bottom:8px; display: ' . ($language['id_lang'] == $defaultLanguage ? 'block' : 'none') . '; float: left; vertical-align: top;">
							<select name="' . $key . '_' . strtoupper($language['iso_code']) . '">';
                        foreach ($field['list'] as $k => $value) {
                            echo '<option value="' . (isset($value['cast']) ? $value['cast']($value[$field['identifier']]) : $value[$field['identifier']]) . '"' . (htmlentities(Tools14::getValue($key . '_' . strtoupper($language['iso_code']), Configuration::get($key . '_' . strtoupper($language['iso_code'])) ? Configuration::get($key . '_' . strtoupper($language['iso_code'])) : ''), ENT_COMPAT, 'UTF-8') == $value[$field['identifier']] ? ' selected="selected"' : '') . '>' . $value['name'] . '</option>';
                        }
                        echo '
							</select>
						</div>';
                    }
                    $this->displayFlags($languages, $defaultLanguage, $divLangName, $key);
                    break;
                case 'bool':
                    echo '<label class="t" for="' . $key . '_on"><img src="../img/admin/enabled.gif" alt="' . $this->l('Yes') . '" title="' . $this->l('Yes') . '" /></label>
					<input type="radio" name="' . $key . '" id="' . $key . '_on" value="1"' . ($val ? ' checked="checked"' : '') . (isset($field['js']['on']) ? $field['js']['on'] : '') . ' />
					<label class="t" for="' . $key . '_on"> ' . $this->l('Yes') . '</label>
					<label class="t" for="' . $key . '_off"><img src="../img/admin/disabled.gif" alt="' . $this->l('No') . '" title="' . $this->l('No') . '" style="margin-left: 10px;" /></label>
					<input type="radio" name="' . $key . '" id="' . $key . '_off" value="0" ' . (!$val ? 'checked="checked"' : '') . (isset($field['js']['off']) ? $field['js']['off'] : '') . '/>
					<label class="t" for="' . $key . '_off"> ' . $this->l('No') . '</label>';
                    break;
                case 'radio':
                    foreach ($field['choices'] as $cValue => $cKey) {
                        echo '<input type="radio" name="' . $key . '" id="' . $key . $cValue . '_on" value="' . (int) $cValue . '"' . ($cValue == $val ? ' checked="checked"' : '') . (isset($field['js'][$cValue]) ? ' ' . $field['js'][$cValue] : '') . ' /><label class="t" for="' . $key . $cValue . '_on"> ' . $cKey . '</label><br />';
                    }
                    echo '<br />';
                    break;
                case 'image':
                    echo '
					<table cellspacing="0" cellpadding="0">
						<tr>';
                    if ($name == 'themes') {
                        echo '
						<td colspan="' . sizeof($field['list']) . '">
							<b>' . $this->l('In order to use a new theme, please follow these steps:', get_class()) . '</b>
							<ul>
								<li>' . $this->l('Import your theme using this module:', get_class()) . ' <a href="index.php?tab=AdminModules&token=' . Tools14::getAdminTokenLite('AdminModules') . '&filtername=themeinstallator" style="text-decoration: underline;">' . $this->l('Theme installer', get_class()) . '</a></li>
								<li>' . $this->l('When your theme is imported, please select the theme in this page', get_class()) . '</li>
							</ul>
						</td>
						</tr>
						<tr>
						';
                    }
                    $i = 0;
                    foreach ($field['list'] as $theme) {
                        echo '<td class="center" style="width: 180px; padding:0px 20px 20px 0px;">
						<input type="radio" name="' . $key . '" id="' . $key . '_' . $theme['name'] . '_on" style="vertical-align: text-bottom;" value="' . $theme['name'] . '"' . (_THEME_NAME_ == $theme['name'] ? 'checked="checked"' : '') . ' />
						<label class="t" for="' . $key . '_' . $theme['name'] . '_on"> ' . Tools14::strtolower($theme['name']) . '</label>
						<br />
						<label class="t" for="' . $key . '_' . $theme['name'] . '_on">
							<img src="../themes/' . $theme['name'] . '/preview.jpg" alt="' . Tools14::strtolower($theme['name']) . '">
						</label>
						</td>';
                        if (isset($field['max']) and ($i + 1) % $field['max'] == 0) {
                            echo '</tr><tr>';
                        }
                        $i++;
                    }
                    echo '</tr>
					</table>';
                    break;
                case 'price':
                    $default_currency = new Currency((int) Configuration::get("PS_CURRENCY_DEFAULT"));
                    echo $default_currency->getSign('left') . '<input type="' . $field['type'] . '" size="' . (isset($field['size']) ? (int) $field['size'] : 5) . '" name="' . $key . '" value="' . ($field['type'] == 'password' ? '' : htmlentities($val, ENT_COMPAT, 'UTF-8')) . '" />' . $default_currency->getSign('right') . ' ' . $this->l('(tax excl.)');
                    break;
                case 'textLang':
                    foreach ($languages as $language) {
                        echo '
						<div id="' . $key . '_' . $language['id_lang'] . '" style="margin-bottom:8px; display: ' . ($language['id_lang'] == $defaultLanguage ? 'block' : 'none') . '; float: left; vertical-align: top;">
							<input type="text" size="' . (isset($field['size']) ? (int) $field['size'] : 5) . '" name="' . $key . '_' . $language['id_lang'] . '" value="' . htmlentities($this->getVal($confValues, $key . '_' . $language['id_lang']), ENT_COMPAT, 'UTF-8') . '" />
						</div>';
                    }
                    $this->displayFlags($languages, $defaultLanguage, $divLangName, $key);
                    break;
                case 'file':
                    if (isset($field['thumb']) and $field['thumb'] and $field['thumb']['pos'] == 'before') {
                        echo '<img src="' . $field['thumb']['file'] . '" alt="' . $field['title'] . '" title="' . $field['title'] . '" /><br />';
                    }
                    echo '<input type="file" name="' . $key . '" />';
                    break;
                case 'textarea':
                    echo '<textarea name=' . $key . ' cols="' . $field['cols'] . '" rows="' . $field['rows'] . '">' . htmlentities($val, ENT_COMPAT, 'UTF-8') . '</textarea>';
                    break;
                case 'container':
                    echo '<div id="' . $key . '">';
                    break;
                case 'container_end':
                    echo (isset($field['content']) === true ? $field['content'] : '') . '</div>';
                    break;
                case 'maintenance_ip':
                    echo '<input type="' . $field['type'] . '"' . (isset($field['id']) === true ? ' id="' . $field['id'] . '"' : '') . ' size="' . (isset($field['size']) ? (int) $field['size'] : 5) . '" name="' . $key . '" value="' . ($field['type'] == 'password' ? '' : htmlentities($val, ENT_COMPAT, 'UTF-8')) . '" />' . (isset($field['next']) ? '&nbsp;' . strval($field['next']) : '') . ' &nbsp;<a href="#" class="button" onclick="addRemoteAddr(); return false;">' . $this->l('Add my IP') . '</a>';
                    break;
                case 'text':
                default:
                    echo '<input type="' . $field['type'] . '"' . (isset($field['id']) === true ? ' id="' . $field['id'] . '"' : '') . ' size="' . (isset($field['size']) ? (int) $field['size'] : 5) . '" name="' . $key . '" value="' . ($field['type'] == 'password' ? '' : htmlentities($val, ENT_COMPAT, 'UTF-8')) . '" />' . (isset($field['next']) ? '&nbsp;' . strval($field['next']) : '');
            }
            echo (isset($field['required']) and $field['required'] and !in_array($field['type'], array('image', 'radio'))) ? ' <sup>*</sup>' : '';
            echo isset($field['desc']) ? '<p style="clear:both">' . ((isset($field['thumb']) and $field['thumb'] and $field['thumb']['pos'] == 'after') ? '<img src="' . $field['thumb']['file'] . '" alt="' . $field['title'] . '" title="' . $field['title'] . '" style="float:left;" />' : '') . $field['desc'] . '</p>' : '';
            if (!in_array($field['type'], array('image', 'radio', 'container', 'container_end')) or isset($field['show'])) {
                echo '</div></div>';
            }
        }
        /* End of specific div for e-mails settings */
        if (get_class($this) == 'Adminemails') {
            echo '<script type="text/javascript">if (getE(\'PS_MAIL_METHOD2_on\').checked) getE(\'smtp\').style.display = \'block\'; else getE(\'smtp\').style.display = \'none\';</script></div>';
        }
        if (!is_writable(PS_ADMIN_DIR . '/../config/settings.inc.php') and $name == 'themes') {
            echo '<p><img src="../img/admin/warning.gif" alt="" /> ' . $this->l('if you change the theme, the settings.inc.php file must be writable (CHMOD 755 / 777)') . '</p>';
        }
        echo '	<div align="center" style="margin-top: 20px;">
					<input type="submit" value="' . $this->l('   Save   ', 'AdminPreferences') . '" name="submit' . ucfirst($name) . $this->table . '" class="button" />
				</div>
				' . ($required ? '<div class="small"><sup>*</sup> ' . $this->l('Required field', 'AdminPreferences') . '</div>' : '') . '
			</fieldset>
		</form>';
        if (get_class($this) == 'AdminPreferences') {
            echo '<script type="text/javascript">changeCMSActivationAuthorization();</script>';
        }
    }
Esempio n. 13
0
define('_PS_ADMIN_DIR_', _PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . $_POST['dir']);
define('PS_ADMIN_DIR', _PS_ADMIN_DIR_);
// Retro-compatibility
//require(_PS_ADMIN_DIR_.'/functions.php');
include AUTOUPGRADE_MODULE_DIR . 'init.php';
$adminObj = new $tab();
$adminObj->ajax = true;
if (is_object($adminObj)) {
    if ($adminObj->checkToken()) {
        // the differences with index.php is here
        $adminObj->ajaxPreProcess();
        $action = Tools14::getValue('action');
        // no need to use displayConf() here
        if (!empty($action) and method_exists($adminObj, 'ajaxProcess' . Tools14::toCamelCase($action))) {
            $adminObj->{'ajaxProcess' . Tools14::toCamelCase($action)}();
        } else {
            $adminObj->ajaxProcess();
        }
        // @TODO We should use a displayAjaxError
        $adminObj->displayErrors();
        if (!empty($action) and method_exists($adminObj, 'displayAjax' . Tools14::toCamelCase($action))) {
            $adminObj->{'displayAjax' . $action}();
        } else {
            $adminObj->displayAjax();
        }
    } else {
        // If this is an XSS attempt, then we should only display a simple, secure page
        ob_clean();
        $adminObj->displayInvalidToken();
    }
}
Esempio n. 14
0
    private function _getJsInit()
    {
        global $cookie;
        $token_preferences = Tools14::getAdminTokenLite('AdminPreferences');
        $js = '
function ucFirst(str) {
	if (str.length > 0) {
		return str[0].toUpperCase() + str.substring(1);
	}
	else {
		return str;
	}
}

function cleanInfo(){
	$("#infoStep").html("reset<br/>");
}

function updateInfoStep(msg){
	if (msg)
	{
		$("#infoStep").append(msg+"<div class=\\"clear\\"></div>");
		$("#infoStep").prop({ scrollTop: $("#infoStep").prop("scrollHeight")},1);
	}
}

function addError(arrError){
	if (typeof(arrError) != "undefined" && arrError.length)
	{
		$("#errorDuringUpgrade").show();
		for(i=0;i<arrError.length;i++)
			$("#infoError").append(arrError[i]+"<div class=\\"clear\\"></div>");
		// Note : jquery 1.6 make uses of prop() instead of attr()
		$("#infoError").prop({ scrollTop: $("#infoError").prop("scrollHeight")},1);
	}
}

function addQuickInfo(arrQuickInfo){
	if (arrQuickInfo)
	{
		$("#quickInfo").show();
		for(i=0;i<arrQuickInfo.length;i++)
			$("#quickInfo").append(arrQuickInfo[i]+"<div class=\\"clear\\"></div>");
		// Note : jquery 1.6 make uses of prop() instead of attr()
		$("#quickInfo").prop({ scrollTop: $("#quickInfo").prop("scrollHeight")},1);
	}
}' . "\n";
        if ($this->manualMode) {
            $js .= 'var manualMode = true;' . "\n";
        } else {
            $js .= 'var manualMode = false;' . "\n";
        }
        // relative admin dir
        $admin_dir = trim(str_replace($this->prodRootDir, '', $this->adminDir), DIRECTORY_SEPARATOR);
        // _PS_MODE_DEV_ will be available in js
        if (defined('_PS_MODE_DEV_') and _PS_MODE_DEV_) {
            $js .= 'var _PS_MODE_DEV_ = true;' . "\n";
        }
        if ($this->getConfig('PS_AUTOUP_BACKUP')) {
            $js .= 'var PS_AUTOUP_BACKUP = true;' . "\n";
        }
        $js .= $this->_getJsErrorMsgs();
        $js .= '
var firstTimeParams = ' . $this->buildAjaxResult() . ';
firstTimeParams = firstTimeParams.nextParams;
firstTimeParams.firstTime = "1";

// js initialization : prepare upgrade and rollback buttons
$(document).ready(function(){

    $(".nobootstrap.no-header-toolbar").removeClass("nobootstrap").addClass("bootstrap");

    $(document).on("click", "a.confirmBeforeDelete", function(e){
        if (!confirm("' . $this->l('Are you sure you want to delete this backup?', 'AdminSelfUpgrade', true, false) . '"))
            e.preventDefault();
    });

	$("select[name=channel]").change(function(e){
		$("select[name=channel]").find("option").each(function()
		{
			if ($(this).is(":selected"))
				$("#for-"+$(this).attr("id")).show();
			else
				$("#for-"+$(this).attr("id")).hide();
	});

		refreshChannelInfos();
	});

	function refreshChannelInfos()
	{
		val = $("select[name=channel]").find("option:selected").val();
		$.ajax({
			type:"POST",
			url : "' . __PS_BASE_URI__ . $admin_dir . '/autoupgrade/ajax-upgradetab.php",
			async: true,
			data : {
				dir:"' . $admin_dir . '",
				token : "' . $this->token . '",
				tab : "AdminSelfUpgrade",
				action : "getChannelInfo",
				ajaxMode : "1",
				params : { channel : val}
			},
			success : function(res,textStatus,jqXHR)
			{
				if (isJsonString(res))
					res = $.parseJSON(res);
				else
					res = {nextParams:{status:"error"}};

				answer = res.nextParams.result;
				if (typeof(answer) != "undefined")
				$("#channel-infos").replaceWith(answer.div);
				if (typeof(answer) != "undefined" && answer.available)
				{
					$("#channel-infos .all-infos").show();
				}
				else if (typeof(answer) != "undefined")
				{
					$("#channel-infos").html(answer.div);
					$("#channel-infos .all-infos").hide();
				}
			},
			error: function(res, textStatus, jqXHR)
			{
				if (textStatus == "timeout" && action == "download")
				{
					updateInfoStep("' . $this->l('Your server cannot download the file. Please upload it first by ftp in your admin/autoupgrade directory', 'AdminSelfUpgrade', true) . '");
				}
				else
				{
					// technical error : no translation needed
					$("#checkPrestaShopFilesVersion").html("<img src=\\"../img/admin/warning.gif\\" /> Error Unable to check md5 files");
				}
			}
		})
	}

	$(document).ready(function(){
		$("div[id|=for]").hide();
		$("select[name=channel]").change();
	});

	// the following prevents to leave the page at the innappropriate time
	$.xhrPool = [];
	$.xhrPool.abortAll = function()
	{
		$.each(this, function(jqXHR)
		{
			if (jqXHR && (jqXHR.readystate != 4))
			{
				jqXHR.abort();
			}
		});
	}
	$(".upgradestep").click(function(e)
	{
		e.preventDefault();
		// $.scrollTo("#options")
	});

	// set timeout to 120 minutes (before aborting an ajax request)
	$.ajaxSetup({timeout:7200000});

	// prepare available button here, without params ?
	prepareNextButton("#upgradeNow",firstTimeParams);

	/**
	 * reset rollbackParams js array (used to init rollback button)
	 */
	$("select[name=restoreName]").change(function(){
		// show delete button if the value is not 0
		if($(this).val() != 0)
		{
			$("span#buttonDeleteBackup").html("<br><a class=\\"button confirmBeforeDelete\\" href=\\"index.php?tab=AdminSelfUpgrade&token=' . $this->token . '&amp;deletebackup&amp;name="+$(this).val()+"\\">' . '<img src=\\"../img/admin/disabled.gif\\" />' . $this->l('Delete') . '</a>");
		}

		if ($("select[name=restoreName]").val() != 0)
		{
			$("#rollback").removeAttr("disabled");
			rollbackParams = jQuery.extend(true, {}, firstTimeParams);

			delete rollbackParams.backupName;
			delete rollbackParams.backupFilesFilename;
			delete rollbackParams.backupDbFilename;
			delete rollbackParams.restoreFilesFilename;
			delete rollbackParams.restoreDbFilenames;

			// init new name to backup
			rollbackParams.restoreName = $("select[name=restoreName]").val();
			prepareNextButton("#rollback", rollbackParams);
			// Note : theses buttons have been removed.
			// they will be available in a future release (when DEV_MODE and MANUAL_MODE enabled)
			// prepareNextButton("#restoreDb", rollbackParams);
			// prepareNextButton("#restoreFiles", rollbackParams);
		}
		else
			$("#rollback").attr("disabled", "disabled");
	});

});

function showConfigResult(msg, type){
	if (type == null)
		type = "conf";
	$("#configResult").html("<div class=\\""+type+"\\">"+msg+"</div>").show();
	if (type == "conf")
	{
		$("#configResult").delay(3000).fadeOut("slow", function() {
			location.reload();
		});
	}
}

// reuse previousParams, and handle xml returns to calculate next step
// (and the correct next param array)
// a case has to be defined for each requests that returns xml


function afterUpdateConfig(res)
{
	params = res.nextParams
	config = params.config
	oldChannel = $("select[name=channel] option.current");
	if (config.channel != oldChannel.val())
	{
		newChannel = $("select[name=channel] option[value="+config.channel+"]");
		oldChannel.removeClass("current");
		oldChannel.html(oldChannel.html().substr(2));
		newChannel.addClass("current");
		newChannel.html("* "+newChannel.html());
	}
	if (res.error == 1)
		showConfigResult(res.next_desc, "error");
	else
		showConfigResult(res.next_desc);
	$("#upgradeNow").unbind();
	$("#upgradeNow").replaceWith("<a class=\\"button-autoupgrade\\" href=\\"' . $this->currentIndex . '&token=' . $this->token . '\\" >' . $this->l('Click to refresh the page and use the new configuration', 'AdminSelfUpgrade', true) . '</a>");
}
function startProcess(type){

	// hide useless divs, show activity log
	$("#informationBlock,#comparisonBlock,#currentConfigurationBlock,#backupOptionsBlock,#upgradeOptionsBlock,#upgradeButtonBlock").slideUp("fast");
	$(".autoupgradeSteps a").addClass("button");
	$("#activityLogBlock").fadeIn("slow");

	$(window).bind("beforeunload", function(e)
	{
		if (confirm("' . $this->l('An update is currently in progress... Click "OK" to abort.', 'AdminTab', true, false) . '"))
		{
			$.xhrPool.abortAll();
			$(window).unbind("beforeunload");
			return true;
		}
		else
		{
			if (type == "upgrade")
			{
				e.returnValue = false;
				e.cancelBubble = true;
				if (e.stopPropagation)
				{
					e.stopPropagation();
				}
				if (e.preventDefault)
				{
					e.preventDefault();
				}
			}
		}
	});
}

function afterUpgradeNow(res)
{
	startProcess("upgrade");
	$("#upgradeNow").unbind();
	$("#upgradeNow").replaceWith("<span id=\\"upgradeNow\\" class=\\"button-autoupgrade\\">' . $this->l('Upgrading PrestaShop', 'AdminSelfUpgrade', true) . ' ...</span>");
}

function afterUpgradeComplete(res)
{
	params = res.nextParams
	$("#pleaseWait").hide();
	if (params.warning_exists == "false")
	{
		$("#upgradeResultCheck")
			.html("<p>' . $this->l('Upgrade complete') . '</p>")
			.show();
		$("#infoStep").html("<p class=\\"alert alert-success\\">' . $this->l('Upgrade Complete!') . '</p>");
	}
	else
	{
		params = res.nextParams
		$("#pleaseWait").hide();
		$("#upgradeResultCheck")
			.html("<p>' . $this->l('Upgrade complete, but warning notifications has been found.') . '</p>")
			.show("slow");
		$("#infoStep").html("<p class=\\"alert alert-warning\\">' . $this->l('Upgrade complete, but warning notifications has been found.', 'AdminSelfUpgrade', true) . '</p>");
	}

	todo_list = [
		"' . $this->l('Cookies have changed, you will need to log in again once you refreshed the page', 'AdminSelfUpgrade', true) . '",
		"' . $this->l('Javascript and CSS files have changed, please clear your browser cache with CTRL-F5', 'AdminSelfUpgrade', true) . '",
		"' . $this->l('Please check that your front-office theme is functional (try to create an account, place an order...)', 'AdminSelfUpgrade', true) . '",
		"' . $this->l('Product images do not appear in the front-office? Try regenerating the thumbnails in Preferences > Images', 'AdminSelfUpgrade', true) . '",
		"' . $this->l('Do not forget to reactivate your shop once you have checked everything!', 'AdminSelfUpgrade', true) . '",
	];

	todo_ul = "<ul>";
	$("#upgradeResultToDoList")
		.html("<strong>' . $this->l('ToDo list:') . '</strong>")
	for(var i in todo_list)
	{
		todo_ul += "<li>"+todo_list[i]+"</li>";
	}
	todo_ul += "</ul>";
	$("#upgradeResultToDoList").append(todo_ul)
	$("#upgradeResultToDoList").show();

	$(window).unbind("beforeunload");
}

function afterError(res)
{
	params = res.nextParams;
	if (params.next == "")
		$(window).unbind("beforeunload");
	$("#pleaseWait").hide();

	addQuickInfo(["unbind :) "]);
}

function afterRollback(res)
{
	startProcess("rollback");
}

function afterRollbackComplete(res)
{
	params = res.nextParams
	$("#pleaseWait").hide();
	$("#upgradeResultCheck")
		.html("<p>' . $this->l('Restoration complete.') . '</p>")
		.show("slow");
	updateInfoStep("<p class=\\"alert alert-success\\">' . $this->l('Restoration complete.') . '</p>");
	$(window).unbind();
}


function afterRestoreDb(params)
{
	// $("#restoreBackupContainer").hide();
}

function afterRestoreFiles(params)
{
	// $("#restoreFilesContainer").hide();
}

function afterBackupFiles(res)
{
	params = res.nextParams;
	// if (params.stepDone)
}

/**
 * afterBackupDb display the button
 *
 */
function afterBackupDb(res)
{
	params = res.nextParams;
	if (res.stepDone && typeof(PS_AUTOUP_BACKUP) != "undefined" && PS_AUTOUP_BACKUP == true)
	{
		$("#restoreBackupContainer").show();
		$("select[name=restoreName]").children("options").removeAttr("selected");
		$("select[name=restoreName]")
			.append("<option selected=\\"selected\\" value=\\""+params.backupName+"\\">"+params.backupName+"</option>")
		$("select[name=restoreName]").change();
	}
}


function call_function(func){
	this[func].apply(this, Array.prototype.slice.call(arguments, 1));
}

function doAjaxRequest(action, nextParams){
	if (typeof(_PS_MODE_DEV_) != "undefined" && _PS_MODE_DEV_ == true)
		addQuickInfo(["[DEV] ajax request : " + action]);
	$("#pleaseWait").show();
	req = $.ajax({
		type:"POST",
		url : "' . __PS_BASE_URI__ . $admin_dir . '/autoupgrade/ajax-upgradetab.php' . '",
		async: true,
		data : {
			dir:"' . $admin_dir . '",
			ajaxMode : "1",
			token : "' . $this->token . '",
			tab : "AdminSelfUpgrade",
			action : action,
			params : nextParams
		},
		beforeSend: function(jqXHR)
		{
			$.xhrPool.push(jqXHR);
		},
		complete: function(jqXHR)
		{
			// just remove the item to the "abort list"
			$.xhrPool.pop();
			// $(window).unbind("beforeunload");
		},
		success : function(res, textStatus, jqXHR)
		{
			$("#pleaseWait").hide();
			try{
				res = $.parseJSON(res);
			}
			catch(e){
				res = {status : "error", nextParams:nextParams};
				alert("' . $this->l('Javascript error (parseJSON) detected for action ', __CLASS__, true, false) . '\\""+action+"\\".' . $this->l('Starting restoration...', __CLASS__, true, false) . '");
			}

			addQuickInfo(res.nextQuickInfo);
			addError(res.nextErrors);
			updateInfoStep(res.next_desc);
			currentParams = res.nextParams;
			if (res.status == "ok")
			{
				$("#"+action).addClass("done");
				if (res.stepDone)
					$("#"+action).addClass("stepok");
				// if a function "after[action name]" exists, it should be called now.
				// This is used for enabling restore buttons for example
				funcName = "after" + ucFirst(action);
				if (typeof funcName == "string" && eval("typeof " + funcName) == "function")
					call_function(funcName, res);

				handleSuccess(res, action);
			}
			else
			{
				// display progression
				$("#"+action).addClass("done");
				$("#"+action).addClass("steperror");
				if (action != "rollback"
					&& action != "rollbackComplete"
					&& action != "restoreFiles"
					&& action != "restoreDb"
					&& action != "rollback"
					&& action != "noRollbackFound"
				)
					handleError(res, action);
				else
					alert("' . $this->l('Error detected during', __CLASS__, true, false) . ' [" + action + "].");
			}
		},
		error: function(jqXHR, textStatus, errorThrown)
		{
			$("#pleaseWait").hide();
			if (textStatus == "timeout")
			{
				if (action == "download")
					updateInfoStep("' . addslashes($this->l('Your server cannot download the file. Please upload it first by ftp in your admin/autoupgrade directory')) . '");
				else
					updateInfoStep("[Server Error] Timeout:' . addslashes($this->l('The request exceeded the max_time_limit. Please change your server configuration.')) . '");
			}
			else
				updateInfoStep("[Ajax / Server Error for action " + action + "] textStatus: \\"" + textStatus + " \\" errorThrown:\\"" + errorThrown + " \\" jqXHR: \\" " + jqXHR.responseText + "\\"");
		}
	});
	return req;
};

/**
 * prepareNextButton make the button button_selector available, and update the nextParams values
 *
 * @param button_selector $button_selector
 * @param nextParams $nextParams
 * @return void
 */
function prepareNextButton(button_selector, nextParams)
{
	$(button_selector).unbind();
	$(button_selector).click(function(e){
		e.preventDefault();
		$("#currentlyProcessing").show();';
        $js .= '
	action = button_selector.substr(1);
	res = doAjaxRequest(action, nextParams);
	});
}

/**
 * handleSuccess
 * res = {error:, next:, next_desc:, nextParams:, nextQuickInfo:,status:"ok"}
 * @param res $res
 * @return void
 */
function handleSuccess(res, action)
{
	if (res.next != "")
	{

		$("#"+res.next).addClass("nextStep");
		if (manualMode && (action != "rollback"
						&& action != "rollbackComplete"
						&& action != "restoreFiles"
						&& action != "restoreDb"
						&& action != "rollback"
						&& action != "noRollbackFound"))
		{
			prepareNextButton("#"+res.next,res.nextParams);
			alert("' . sprintf($this->l('Manually go to %s button', __CLASS__, true, false), '"+res.next+"') . '");
		}
		else
		{
			// if next is rollback, prepare nextParams with rollbackDbFilename and rollbackFilesFilename
			if ( res.next == "rollback")
			{
				res.nextParams.restoreName = ""
			}
			doAjaxRequest(res.next, res.nextParams);
			// 2) remove all step link (or show them only in dev mode)
			// 3) when steps link displayed, they should change color when passed if they are visible
		}
	}
	else
	{
		// Way To Go, end of upgrade process
		addQuickInfo(["' . $this->l('End of process') . '"]);
	}
}

// res = {nextParams, next_desc}
function handleError(res, action)
{
	// display error message in the main process thing
	// In case the rollback button has been deactivated, just re-enable it
	$("#rollback").removeAttr("disabled");
	// auto rollback only if current action is upgradeFiles or upgradeDb
	if (action == "upgradeFiles" || action == "upgradeDb" || action == "upgradeModules" )
	{
		$(".button-autoupgrade").html("' . $this->l('Operation canceled. Checking for restoration...') . '");
		res.nextParams.restoreName = res.nextParams.backupName;
		if (confirm("' . $this->l('Do you want to restore') . ' " + "' . $this->backupName . '" + " ?"))
			doAjaxRequest("rollback",res.nextParams);
	}
	else
	{
		$(".button-autoupgrade").html("' . $this->l('Operation canceled. An error happened.') . '");
		$(window).unbind();
	}
}';
        // ajax to check md5 files
        $js .= 'function addModifiedFileList(title, fileList, css_class, container)
{
	subList = $("<ul class=\\"changedFileList "+css_class+"\\"></ul>");

	$(fileList).each(function(k,v){
		$(subList).append("<li>"+v+"</li>");
	});
	$(container).append("<h3><a class=\\"toggleSublist\\" href=\\"#\\" >"+title+"</a> (" + fileList.length + ")</h3>");
	$(container).append(subList);
	$(container).append("<br/>");

}';
        if (!file_exists($this->autoupgradePath . DIRECTORY_SEPARATOR . 'ajax-upgradetab.php')) {
            $js .= '$(document).ready(function(){
			$("#checkPrestaShopFilesVersion").html("<img src=\\"../img/admin/warning.gif\\" /> [TECHNICAL ERROR] ajax-upgradetab.php ' . $this->l('is missing. please reinstall the module') . '");
			})';
        } else {
            $js .= '
			function isJsonString(str) {
				try {
						typeof(str) != "undefined" && JSON.parse(str);
				} catch (e) {
						return false;
				}
				return true;
		}

$(document).ready(function(){
	$.ajax({
			type:"POST",
			url : "' . __PS_BASE_URI__ . $admin_dir . '/autoupgrade/ajax-upgradetab.php",
			async: true,
			data : {
				dir:"' . $admin_dir . '",
				token : "' . $this->token . '",
				tab : "' . get_class($this) . '",
				action : "checkFilesVersion",
				ajaxMode : "1",
				params : {}
			},
			success : function(res,textStatus,jqXHR)
			{
				if (isJsonString(res))
					res = $.parseJSON(res);
				else
				{
					res = {nextParams:{status:"error"}};
				}
					answer = res.nextParams;
					$("#checkPrestaShopFilesVersion").html("<span> "+answer.msg+" </span> ");
					if ((answer.status == "error") || (typeof(answer.result) == "undefined"))
						$("#checkPrestaShopFilesVersion").prepend("<img src=\\"../img/admin/warning.gif\\" /> ");
					else
					{
						$("#checkPrestaShopFilesVersion").prepend("<img src=\\"../img/admin/warning.gif\\" /> ");
						$("#checkPrestaShopFilesVersion").append("<a id=\\"toggleChangedList\\" class=\\"button\\" href=\\"\\">' . $this->l('See or hide the list') . '</a><br/>");
						$("#checkPrestaShopFilesVersion").append("<div id=\\"changedList\\" style=\\"display:none \\"><br/>");
						if(answer.result.core.length)
							addModifiedFileList("' . $this->l('Core file(s)') . '", answer.result.core, "changedImportant", "#changedList");
						if(answer.result.mail.length)
							addModifiedFileList("' . $this->l('Mail file(s)') . '", answer.result.mail, "changedNotice", "#changedList");
						if(answer.result.translation.length)
							addModifiedFileList("' . $this->l('Translation file(s)') . '", answer.result.translation, "changedNotice", "#changedList");

						$("#toggleChangedList").bind("click",function(e){e.preventDefault();$("#changedList").toggle();});
						$(".toggleSublist").die().live("click",function(e){e.preventDefault();$(this).parent().next().toggle();});
					}
			}
			,
			error: function(res, textStatus, jqXHR)
			{
				if (textStatus == "timeout" && action == "download")
				{
					updateInfoStep("' . $this->l('Your server cannot download the file. Please upload it to your FTP server, and put it in your /[admin]/autoupgrade directory.') . '");
				}
				else
				{
					// technical error : no translation needed
					$("#checkPrestaShopFilesVersion").html("<img src=\\"../img/admin/warning.gif\\" /> Error: Unable to check md5 files");
				}
			}
		})
	$.ajax({
			type:"POST",
			url : "' . __PS_BASE_URI__ . $admin_dir . '/autoupgrade/ajax-upgradetab.php",
			async: true,
			data : {
				dir:"' . $admin_dir . '",
				token : "' . $this->token . '",
				tab : "' . get_class($this) . '",
				action : "compareReleases",
				ajaxMode : "1",
				params : {}
			},
			success : function(res,textStatus,jqXHR)
			{
				if (isJsonString(res))
					res = $.parseJSON(res);
				else
				{
					res = {nextParams:{status:"error"}};
				}
				answer = res.nextParams;
				$("#checkPrestaShopModifiedFiles").html("<span> "+answer.msg+" </span> ");
				if ((answer.status == "error") || (typeof(answer.result) == "undefined"))
					$("#checkPrestaShopModifiedFiles").prepend("<img src=\\"../img/admin/warning.gif\\" /> ");
				else
				{
					$("#checkPrestaShopModifiedFiles").prepend("<img src=\\"../img/admin/warning.gif\\" /> ");
					$("#checkPrestaShopModifiedFiles").append("<a id=\\"toggleDiffList\\" class=\\"button\\" href=\\"\\">' . $this->l('See or hide the list') . '</a><br/>");
					$("#checkPrestaShopModifiedFiles").append("<div id=\\"diffList\\" style=\\"display:none \\"><br/>");
						if(answer.result.deleted.length)
							addModifiedFileList("' . $this->l('Theses files will be deleted') . '", answer.result.deleted, "diffImportant", "#diffList");
						if(answer.result.modified.length)
							addModifiedFileList("' . $this->l('Theses files will be modified') . '", answer.result.modified, "diffImportant", "#diffList");

					$("#toggleDiffList").bind("click",function(e){e.preventDefault();$("#diffList").toggle();});
					$(".toggleSublist").die().live("click",function(e){
						e.preventDefault();
						// this=a, parent=h3, next=ul
						$(this).parent().next().toggle();
					});
				}
			},
			error: function(res, textStatus, jqXHR)
			{
				if (textStatus == "timeout" && action == "download")
				{
					updateInfoStep("' . $this->l('Your server cannot download the file. Please upload it first by ftp in your admin/autoupgrade directory') . '");
				}
				else
				{
					// technical error : no translation needed
					$("#checkPrestaShopFilesVersion").html("<img src=\\"../img/admin/warning.gif\\" /> Error: Unable to check md5 files");
				}
			}
		})
	});';
        }
        // advanced/normal mode
        $js .= '
	$("input[name=btn_adv]").click(function(e)
		{
			if ($("#advanced:visible").length)
				switch_to_normal();
			else
				switch_to_advanced();
		});

		function switch_to_advanced(){
			$("input[name=btn_adv]").val("' . $this->l('Less options', 'AdminTab', true, false) . '");
			$("#advanced").show();
		}

		function switch_to_normal(){
			$("input[name=btn_adv]").val("' . $this->l('More options (Expert mode)', 'AdminTab', true, false) . '");
			$("#advanced").hide();
		}

		$(document).ready(function(){
			' . ($this->getConfig('channel') == 'major' ? 'switch_to_normal();' : 'switch_to_advanced();') . '
		});
	';
        $js .= '
$(document).ready(function()
{
	$("input[name|=submitConf]").bind("click", function(e){
		params = {};
		newChannel = $("select[name=channel] option:selected").val();
		oldChannel = $("select[name=channel] option.current").val();
		oldChannel = "";
		if (oldChannel != newChannel)
		{
			if( newChannel == "major"
				|| newChannel == "minor"
				|| newChannel == "rc"
				|| newChannel == "beta"
				|| newChannel == "alpha" )
				params.channel = newChannel;

			if(newChannel == "private")
			{
				if (($("input[name=private_release_link]").val() == "") || ($("input[name=private_release_md5]").val() == ""))
				{
					showConfigResult("' . $this->l('Link and MD5 hash cannot be empty') . '", "error");
					return false;
				}
				params.channel = "private";
				params.private_release_link = $("input[name=private_release_link]").val();
				params.private_release_md5 = $("input[name=private_release_md5]").val();
				if ($("input[name=private_allow_major]").is(":checked"))
					params.private_allow_major = 1;
				else
					params.private_allow_major = 0;
			}
			if(newChannel == "archive")
			{
				archive_prestashop = $("select[name=archive_prestashop] option:selected").val();
				archive_num = $("input[name=archive_num]").val();
				if (archive_num == "")
				{
					showConfigResult("' . $this->l('You need to enter the version number associated with the archive.') . '", "error");
					return false;
				}
				if (archive_prestashop == "")
				{
					showConfigResult("' . $this->l('No archive has been selected.') . '", "error");
					return false;
				}
				params.channel = "archive";
				params.archive_prestashop = archive_prestashop;
				params.archive_num = archive_num;
			}
			if(newChannel == "directory")
			{
				params.channel = "directory";
				params.directory_prestashop = $("select[name=directory_prestashop] option:selected").val();
				directory_num = $("input[name=directory_num]").val();
				if (directory_num == "" || directory_num.indexOf(".") == -1)
				{
					showConfigResult("' . $this->l('You need to enter the version number associated with the directory.') . '", "error");
					return false;
				}
				params.directory_num = $("input[name=directory_num]").val();
			}
		}
		// note: skipBackup is currently not used
		if ($(this).attr("name") == "submitConf-skipBackup")
		{
			skipBackup = $("input[name=submitConf-skipBackup]:checked").length;
			if (skipBackup == 0 || confirm("' . $this->l('Please confirm that you want to skip the backup.') . '"))
				params.skip_backup = $("input[name=submitConf-skipBackup]:checked").length;
			else
			{
				$("input[name=submitConf-skipBackup]:checked").removeAttr("checked");
				return false;
			}
		}

		// note: preserveFiles is currently not used
		if ($(this).attr("name") == "submitConf-preserveFiles")
		{
			preserveFiles = $("input[name=submitConf-preserveFiles]:checked").length;
			if (confirm("' . $this->l('Please confirm that you want to preserve file options.') . '"))
				params.preserve_files = $("input[name=submitConf-preserveFiles]:checked").length;
			else
			{
				$("input[name=submitConf-skipBackup]:checked").removeAttr("checked");
				return false;
			}
		}
		res = doAjaxRequest("updateConfig", params);
	});
});
';
        return $js;
    }
Esempio n. 15
0
function checkingTab($tab)
{
    global $adminObj, $cookie;
    $tab = trim($tab);
    if (!Validate::isTabName($tab)) {
        return false;
    }
    $row = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql = 'SELECT id_tab, module FROM `' . _DB_PREFIX_ . 'tab` WHERE class_name = \'' . pSQL($tab) . '\'');
    if (!$row['id_tab']) {
        if (isset(AdminTab::$tabParenting[$tab])) {
            Tools14::redirectAdmin('?tab=' . AdminTab::$tabParenting[$tab] . '&token=' . Tools14::getAdminTokenLite(AdminTab::$tabParenting[$tab]));
        }
        echo Tools14::displayError('Tab cannot be found.');
        return false;
    }
    if ($row['module'] and file_exists(_PS_MODULE_DIR_ . '/' . $row['module'] . '/' . $tab . '.php')) {
        include_once _PS_MODULE_DIR_ . '/' . $row['module'] . '/' . $tab . '.php';
    } elseif (file_exists(PS_ADMIN_DIR . '/tabs/' . $tab . '.php')) {
        include_once PS_ADMIN_DIR . '/tabs/' . $tab . '.php';
    }
    if (!class_exists($tab, false) or !$row['id_tab']) {
        echo Tools14::displayError('Tab file cannot be found.');
        return false;
    }
    $adminObj = new $tab();
    if (!$adminObj->viewAccess()) {
        $adminObj->_errors = array(Tools14::displayError('Access denied'));
        echo $adminObj->displayErrors();
        return false;
    }
    return $row['id_tab'];
}
Esempio n. 16
0
 public static function enableCache($level = 1)
 {
     global $smarty;
     if (!Configuration::get('PS_SMARTY_CACHE')) {
         return;
     }
     if ($smarty->force_compile == 0 and $smarty->caching == $level) {
         return;
     }
     self::$_forceCompile = (int) $smarty->force_compile;
     self::$_caching = (int) $smarty->caching;
     $smarty->force_compile = 0;
     $smarty->caching = (int) $level;
 }
    private function _getJsInit()
    {
        global $currentIndex, $cookie;
        $js = '';
        if (method_exists('Tools', 'getAdminTokenLite')) {
            $token_preferences = Tools::getAdminTokenLite('AdminPreferences');
        } else {
            $token_preferences = Tools14::getAdminTokenLite('AdminPreferences');
        }
        $js .= '
function ucFirst(str) {
	if (str.length > 0) {
		return str[0].toUpperCase() + str.substring(1);
	}
	else {
		return str;
	}
}

function cleanInfo(){
	$("#infoStep").html("reset<br/>");
}

function updateInfoStep(msg){
	if (msg)
	{
		$("#infoStep").html(msg);
		$("#infoStep").attr({ scrollTop: $("#infoStep").attr("scrollHeight") });
	}
}


function addQuickInfo(arrQuickInfo){
	if (arrQuickInfo)
	{
		$("#quickInfo").show();
		for(i=0;i<arrQuickInfo.length;i++)
			$("#quickInfo").append(arrQuickInfo[i]+"<div class=\\"clear\\"></div>");
		// Note : jquery 1.6 make uses of prop() instead of attr()
		$("#quickInfo").prop({ scrollTop: $("#quickInfo").prop("scrollHeight") },1);
	}
}';
        if ($this->manualMode) {
            $js .= 'var manualMode = true;';
        } else {
            $js .= 'var manualMode = false;';
        }
        // relative admin dir
        $adminDir = trim(str_replace($this->prodRootDir, '', $this->adminDir), DIRECTORY_SEPARATOR);
        $js .= '
var firstTimeParams = ' . $this->buildAjaxResult() . ';
firstTimeParams = firstTimeParams.nextParams;
firstTimeParams.firstTime = "1";

// js initialization : prepare upgrade and rollback buttons
$(document).ready(function(){
	$(".upgradestep").click(function(e)
	{
		e.preventDefault();
		// $.scrollTo("#options")
	});

		// set timeout to 5 minutes (download can be long)
		$.ajaxSetup({timeout:300000});

	// prepare available button here, without params ?
	prepareNextButton("#upgradeNow",firstTimeParams);
	
	/**
	 * reset rollbackParams js array (used to init rollback button)
	 */
	$("select[name=restoreName]").change(function(){
		$(this).next().remove();
		// show delete button if the value is not 0
		if($(this).val() != 0)
		{
			$(this).after("<a class=\\"button confirmBeforeDelete\\" href=\\"index.php?tab=AdminSelfUpgrade&token=' . Tools::getAdminToken('AdminSelfUpgrade' . (int) Tab::getIdFromClassName('AdminSelfUpgrade') . (int) $cookie->id_employee) . '&amp;deletebackup&amp;name="+$(this).val()+"\\">' . '<img src=\\"../img/admin/disabled.gif\\" />' . $this->l('Delete') . '</a>");
			$(this).next().click(function(e){
				if (!confirm("' . $this->l('Are you sure you want to delete this backup ?') . '"))
					e.preventDefault();
			});
		}

		if ($("select[name=restoreName]").val() != 0)
		{
			$("#rollback").removeAttr("disabled");
			rollbackParams = jQuery.extend(true, {}, firstTimeParams);

			delete rollbackParams.backupName;
			delete rollbackParams.backupFilesFilename;
			delete rollbackParams.backupDbFilename;
			delete rollbackParams.restoreFilesFilename;
			delete rollbackParams.restoreDbFilenames;
			
			// init new name to backup
			rollbackParams.restoreName = $("select[name=restoreName]").val();
			prepareNextButton("#rollback", rollbackParams);
			// Note : theses buttons have been removed.
			// they will be available in a future release (when DEV_MODE and MANUAL_MODE enabled) 
			// prepareNextButton("#restoreDb", rollbackParams);
			// prepareNextButton("#restoreFiles", rollbackParams);
		}
		else
			$("#rollback").attr("disabled", "disabled");
	});
	$("select[name=restoreName]").change();

});


// reuse previousParams, and handle xml returns to calculate next step
// (and the correct next param array)
// a case has to be defined for each requests that returns xml


function afterUpgradeNow(params)
{
	$("#upgradeNow").unbind();
	$("#upgradeNow").replaceWith("<span class=\\"button-autoupgrade\\">' . $this->l('Upgrading PrestaShop') . ' ...</span>");
}

function afterUpgradeComplete(params)
{
	$("#pleaseWait").hide();
	$("#dbResultCheck")
		.addClass("ok")
		.removeClass("fail")
		.html("<p>' . $this->l('upgrade complete. Please check your front-office theme is functionnal (try to make an order, check theme)') . '</p>")
		.show("slow")
		.append("<a href=\\"index.php?tab=AdminPreferences&token=' . $token_preferences . '\\" class=\\"button\\">' . $this->l('activate your shop here') . '</a>");
	$("#dbCreateResultCheck")
		.hide("slow");
	$("#infoStep").html("<h3>' . $this->l('Upgrade Complete !') . '</h3>");
}

function afterRollbackComplete(params)
{
	$("#rollback").attr("disabled", "disabled");
	$($("select[name=restoreName]").children()[0])
		.attr("selected", "selected");
	$(".button-autoupgrade").html("' . $this->l('Restoration complete.') . '");
}
function afterRollbackComplete(params)
{
	$("#pleaseWait").hide();
	$("#dbResultCheck")
		.addClass("ok")
		.removeClass("fail")
		.html("<p>' . $this->l('restoration complete.') . '</p>")
		.show("slow")
		.append("<a href=\\"index.php?tab=AdminPreferences&token=' . $token_preferences . '\\" class=\\"button\\">' . $this->l('activate your shop here') . '</a>");
	$("#dbCreateResultCheck")
		.hide("slow");
	$("#infoStep").html("<h3>' . $this->l('Restoration Complete.') . '</h3>");
}


function afterRestoreDb(params)
{
	// $("#restoreBackupContainer").hide();
}

function afterRestoreFiles(params)
{
	// $("#restoreFilesContainer").hide();
}

function afterBackupFiles(params)
{
	if (params.stepDone)
	{
	}
}

/**
 * afterBackupDb display the button
 *
 */
function afterBackupDb(params)
{
	if (params.stepDone)
	{
		$("#restoreBackupContainer").show();
		$("select[name=restoreName]").children().removeAttr("selected");
		$("select[name=restoreName]")
			.append("<option selected=\\"selected\\" value=\\""+params.backupName+"\\">"+params.backupName+"</option>")
	}
}


function call_function(func){
	this[func].apply(this, Array.prototype.slice.call(arguments, 1));
}

function doAjaxRequest(action, nextParams){
	var _PS_MODE_DEV_;
	if (_PS_MODE_DEV_)
		addQuickInfo(["[DEV] ajax request : "+action]);
	$("#pleaseWait").show();
	req = $.ajax({
		type:"POST",
		url : "' . __PS_BASE_URI__ . $adminDir . '/autoupgrade/ajax-upgradetab.php' . '",
		async: true,
		data : {
			dir:"' . $adminDir . '",
			ajaxMode : "1",
			token : "' . $this->token . '",
			tab : "AdminSelfUpgrade",
			action : action,
			params : nextParams
		},
		success : function(res,textStatus,jqXHR)
		{
			$("#pleaseWait").hide();

			try{
				res = $.parseJSON(res);
				addQuickInfo(res.nextQuickInfo);
				currentParams = res.nextParams;
				if (res.status == "ok")
				{
					$("#"+action).addClass("done");
					if (res.stepDone)
						$("#"+action).addClass("stepok");
					// if a function "after[action name]" exists, it should be called now.
					// This is used for enabling restore buttons for example
					funcName = "after"+ucFirst(action);
					if (typeof funcName == "string" && eval("typeof " + funcName) == "function") 
						call_function(funcName, currentParams);

					handleSuccess(res);
				}
				else
				{
					// display progression
					$("#"+action).addClass("done");
					$("#"+action).addClass("steperror");
					if (action != "rollback" 
						&& action != "rollbackComplete" 
						&& action != "restoreFiles"
						&& action != "restoreDb"
						&& action != "rollback"
						&& action != "noRollbackFound"
					)
						handleError(res);
					else
						alert("[TECHNICAL ERROR] Error detected during ["+action+"].");
				}
			}
			catch(e){
				res = {status : "error"};
				alert("[TECHNICAL ERROR] Error detected during ["+action+"].");
			}
		},
		error: function(res, textStatus, jqXHR)
		{
			$("#pleaseWait").hide();
			if (textStatus == "timeout" && action == "download")
			{
				updateInfoStep("' . $this->l('Your server cannot download the file. Please upload it first by ftp in your admin/autoupgrade directory') . '");
			}
			else
				if (textStatus == "timeout")
					updateInfoStep("[Server Error] Timeout:' . $this->l('The request excessed the max_time_limit. Please change your server configuration.') . '");
			{
				updateInfoStep("[Server Error] Status message : " + textStatus);
			}
		}
	});
};

/**
 * prepareNextButton make the button button_selector available, and update the nextParams values
 *
 * @param button_selector $button_selector
 * @param nextParams $nextParams
 * @return void
 */
function prepareNextButton(button_selector, nextParams)
{
	$(button_selector).unbind();
	$(button_selector).click(function(e){
		e.preventDefault();
		$("#currentlyProcessing").show();
';
        $js .= '
	action = button_selector.substr(1);
	res = doAjaxRequest(action, nextParams);
	});
}

/**
 * handleSuccess
 * res = {error:, next:, nextDesc:, nextParams:, nextQuickInfo:,status:"ok"}
 * @param res $res
 * @return void
 */
function handleSuccess(res)
{
	updateInfoStep(res.nextDesc);
	if (res.next != "")
	{

		$("#"+res.next).addClass("nextStep");
		if (manualMode)
		{
			prepareNextButton("#"+res.next,res.nextParams);
			alert("manually go to "+res.next+" button ");
		}
		else
		{
			// 1) instead of click(), call a function.
			doAjaxRequest(res.next,res.nextParams);
			// 2) remove all step link (or show them only in dev mode)
			// 3) when steps link displayed, they should change color when passed if they are visible
		}
	}
	else
	{
		// Way To Go, end of upgrade process
		addQuickInfo(["End of process"]);
	}
}

// res = {nextParams, NextDesc}
function handleError(res)
{
	// display error message in the main process thing
	updateInfoStep(res.nextDesc);
	// In case the rollback button has been deactivated, just re-enable it
	$("#rollback").removeAttr("disabled");
	$(".button-autoupgrade").html("' . $this->l('Operation cancelled. Restoration in progress ...') . '");
	doAjaxRequest("rollback",res.nextParams);


}
';
        // ajax to check md5 files
        $js .= 'function addModifiedFileList(title, fileList, css_class, container)
{
	subList = $("<ul class=\\"changedFileList "+css_class+"\\"></ul>");

	$(fileList).each(function(k,v){
		$(subList).append("<li>"+v+"</li>");
	});
	$(container).append("<h3><a class=\\"toggleSublist\\">"+title+"</a> (" + fileList.length + ")</h3>");
	$(container).append(subList);
	$(container).append("<br/>");

}';
        if (!file_exists($this->autoupgradePath . DIRECTORY_SEPARATOR . 'ajax-upgradetab.php')) {
            $js .= '$(document).ready(function(){
			$("#checkPrestaShopFilesVersion").html("<img src=\\"../img/admin/warning.gif\\" /> [TECHNICAL ERROR] ajax-upgradetab.php ' . $this->l('is missing. please reinstall the module') . '");
			})';
        } else {
            $js .= '
			function isJsonString(str) {
				try {
						JSON.parse(str);
				} catch (e) {
						return false;
				}
				return true;
		}
	
$(document).ready(function(){
	$.ajax({
			type:"POST",
			url : "' . __PS_BASE_URI__ . $adminDir . '/autoupgrade/ajax-upgradetab.php",
			async: true,
			data : {
				dir:"' . $adminDir . '",
				token : "' . $this->token . '",
				tab : "' . get_class($this) . '",
				action : "checkFilesVersion",
				ajaxMode : "1",
				params : {}
			},
			success : function(res,textStatus,jqXHR)
			{
				if (isJsonString(res))
					res = $.parseJSON(res);
				else
				{
					res = {nextParams:{status:"error"}};
				}
					answer = res.nextParams;
					$("#checkPrestaShopFilesVersion").html("<span> "+answer.msg+" </span> ");
					if ((answer.status == "error") || (typeof(answer.result) == "undefined"))
						$("#checkPrestaShopFilesVersion").prepend("<img src=\\"../img/admin/warning.gif\\" /> ");
					else
					{
						$("#checkPrestaShopFilesVersion").prepend("<img src=\\"../img/admin/warning.gif\\" /> ");
						$("#checkPrestaShopFilesVersion").append("<a id=\\"toggleChangedList\\" class=\\"button\\" href=\\"\\">' . $this->l('See or hide the list') . '</a><br/>");
						$("#checkPrestaShopFilesVersion").append("<div id=\\"changedList\\" style=\\"display:none \\"><br/>");
						if(answer.result.core.length)
							addModifiedFileList("' . $this->l('Core file(s)') . '", answer.result.core, "changedImportant", "#changedList");
						if(answer.result.mail.length)
							addModifiedFileList("' . $this->l('Mail file(s)') . '", answer.result.mail, "changedNotice", "#changedList");
						if(answer.result.translation.length)
							addModifiedFileList("' . $this->l('Translation file(s)') . '", answer.result.translation, "changedNotice", "#changedList");

						$("#toggleChangedList").bind("click",function(e){e.preventDefault();$("#changedList").toggle();});
						$(".toggleSublist").live("click",function(e){e.preventDefault();$(this).parent().next().toggle();});
				}
			}
			,
			error: function(res, textStatus, jqXHR)
			{
				if (textStatus == "timeout" && action == "download")
				{
					updateInfoStep("' . $this->l('Your server cannot download the file. Please upload it first by ftp in your admin/autoupgrade directory') . '");
				}
				else
				{
					// technical error : no translation needed
					$("#checkPrestaShopFilesVersion").html("<img src=\\"../img/admin/warning.gif\\" /> [TECHNICAL ERROR] Unable to check md5 files");
				}
			}
		})
	$.ajax({
			type:"POST",
			url : "' . __PS_BASE_URI__ . $adminDir . '/autoupgrade/ajax-upgradetab.php",
			async: true,
			data : {
				dir:"' . $adminDir . '",
				token : "' . $this->token . '",
				tab : "' . get_class($this) . '",
				action : "compareReleases",
				ajaxMode : "1",
				params : {}
			},
			success : function(res,textStatus,jqXHR)
			{
				if (isJsonString(res))
					res = $.parseJSON(res);
				else
				{
					res = {nextParams:{status:"error"}};
				}
				answer = res.nextParams;
				$("#checkPrestaShopModifiedFiles").html("<span> "+answer.msg+" </span> ");
				if ((answer.status == "error") || (typeof(answer.result) == "undefined"))
					$("#checkPrestaShopModifiedFiles").prepend("<img src=\\"../img/admin/warning.gif\\" /> ");
				else
				{
					$("#checkPrestaShopModifiedFiles").prepend("<img src=\\"../img/admin/warning.gif\\" /> ");
					$("#checkPrestaShopModifiedFiles").append("<a id=\\"toggleDiffList\\" class=\\"button\\" href=\\"\\">' . $this->l('See or hide the list') . '</a><br/>");
					$("#checkPrestaShopModifiedFiles").append("<div id=\\"diffList\\" style=\\"display:none \\"><br/>");
						if(answer.result.deleted.length)
							addModifiedFileList("' . $this->l('Theses files will be deleted') . '", answer.result.deleted, "diffImportant", "#diffList");
						if(answer.result.modified.length)
							addModifiedFileList("' . $this->l('Theses files will be modified') . '", answer.result.modified, "diffImportant", "#diffList");

					$("#toggleDiffList").bind("click",function(e){e.preventDefault();$("#diffList").toggle();});
					$(".toggleSublist").die().live("click",function(e){
						e.preventDefault();
						// this=a, parent=h3, next=ul
						$(this).parent().next().toggle();
					});
				}
			},
			error: function(res, textStatus, jqXHR)
			{
				if (textStatus == "timeout" && action == "download")
				{
					updateInfoStep("' . $this->l('Your server cannot download the file. Please upload it first by ftp in your admin/autoupgrade directory') . '");
				}
				else
				{
					// technical error : no translation needed
					$("#checkPrestaShopFilesVersion").html("<img src=\\"../img/admin/warning.gif\\" /> [TECHNICAL ERROR] Unable to check md5 files");
				}
			}
		})
});';
        }
        return $js;
    }