Ejemplo n.º 1
0
 public function __construct()
 {
     global $cookie;
     $this->id = Tab::getCurrentTabId();
     $this->_conf = array(1 => $this->l('Deletion successful'), 2 => $this->l('Selection successfully deleted'), 3 => $this->l('Creation successful'), 4 => $this->l('Update successful'), 5 => $this->l('The new version check has been completed successfully'), 6 => $this->l('Settings update successful'), 7 => $this->l('Image successfully deleted'), 8 => $this->l('Module downloaded successfully'), 9 => $this->l('Thumbnails successfully regenerated'), 10 => $this->l('Message sent to the customer'), 11 => $this->l('Comment added'), 12 => $this->l('Module installed successfully'), 13 => $this->l('Module uninstalled successfully'), 14 => $this->l('Language successfully copied'), 15 => $this->l('Translations successfully added'), 16 => $this->l('Module transplanted successfully to hook'), 17 => $this->l('Module removed successfully from hook'), 18 => $this->l('Upload successful'), 19 => $this->l('Duplication completed successfully'), 20 => $this->l('Translation added successfully but the language has not been created'), 21 => $this->l('Module reset successfully'), 22 => $this->l('Module deleted successfully'), 23 => $this->l('Localization pack imported successfully'), 24 => $this->l('Refund Successful'), 25 => $this->l('Images successfully moved'));
     if (!$this->identifier) {
         $this->identifier = 'id_' . $this->table;
     }
     if (!$this->_defaultOrderBy) {
         $this->_defaultOrderBy = $this->identifier;
     }
     $className = get_class($this);
     if ($className == 'AdminCategories' or $className == 'AdminProducts') {
         $className = 'AdminCatalog';
     }
     $this->token = Tools14::getAdminToken($className . (int) $this->id . (int) $cookie->id_employee);
 }
Ejemplo n.º 2
0
/**
 * Return path to a product category
 *
 * @param string $urlBase Start URL
 * @param integer $id_category Start category
 * @param string $path Current path
 * @param string $highlight String to highlight (in XHTML/CSS)
 * @param string $type Category type (products/cms)
 */
function getPath($urlBase, $id_category, $path = '', $highlight = '', $categoryType = 'catalog')
{
    global $cookie;
    if ($categoryType == 'catalog') {
        $category = Db::getInstance()->getRow('
		SELECT id_category, level_depth, nleft, nright
		FROM ' . _DB_PREFIX_ . 'category
		WHERE id_category = ' . (int) $id_category);
        if (isset($category['id_category'])) {
            $categories = Db::getInstance()->ExecuteS('
			SELECT c.id_category, cl.name, cl.link_rewrite
			FROM ' . _DB_PREFIX_ . 'category c
			LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON (cl.id_category = c.id_category)
			WHERE c.nleft <= ' . (int) $category['nleft'] . ' AND c.nright >= ' . (int) $category['nright'] . ' AND cl.id_lang = ' . (int) $cookie->id_lang . '
			ORDER BY c.level_depth ASC
			LIMIT ' . (int) ($category['level_depth'] + 1));
            $fullPath = '';
            $n = 1;
            $nCategories = (int) sizeof($categories);
            foreach ($categories as $category) {
                $edit = '<a href="' . $urlBase . '&id_category=' . (int) $category['id_category'] . '&' . ($category['id_category'] == 1 ? 'viewcategory' : 'addcategory') . '&token=' . Tools14::getAdminToken('AdminCatalog' . (int) Tab::getIdFromClassName('AdminCatalog') . (int) $cookie->id_employee) . '" title="' . ($category['id_category'] == 1 ? 'Home' : 'Modify') . '"><img src="../img/admin/' . ($category['id_category'] == 1 ? 'home' : 'edit') . '.gif" alt="" /></a> ';
                $fullPath .= $edit . ($n < $nCategories ? '<a href="' . $urlBase . '&id_category=' . (int) $category['id_category'] . '&viewcategory&token=' . Tools14::getAdminToken('AdminCatalog' . (int) Tab::getIdFromClassName('AdminCatalog') . (int) $cookie->id_employee) . '" title="' . htmlentities($category['name'], ENT_NOQUOTES, 'UTF-8') . '">' : '') . (!empty($highlight) ? str_ireplace($highlight, '<span class="highlight">' . htmlentities($highlight, ENT_NOQUOTES, 'UTF-8') . '</span>', $category['name']) : $category['name']) . ($n < $nCategories ? '</a>' : '') . (($n++ != $nCategories or !empty($path)) ? ' > ' : '');
            }
            return $fullPath . $path;
        }
    } elseif ($categoryType == 'cms') {
        $category = new CMSCategory($id_category, (int) $cookie->id_lang);
        if (!$category->id) {
            return $path;
        }
        $name = $highlight != NULL ? str_ireplace($highlight, '<span class="highlight">' . $highlight . '</span>', CMSCategory::hideCMSCategoryPosition($category->name)) : CMSCategory::hideCMSCategoryPosition($category->name);
        $edit = '<a href="' . $urlBase . '&id_cms_category=' . $category->id . '&addcategory&token=' . Tools14::getAdminToken('AdminCMSContent' . (int) Tab::getIdFromClassName('AdminCMSContent') . (int) $cookie->id_employee) . '">
				<img src="../img/admin/edit.gif" alt="Modify" /></a> ';
        if ($category->id == 1) {
            $edit = '<a href="' . $urlBase . '&id_cms_category=' . $category->id . '&viewcategory&token=' . Tools14::getAdminToken('AdminCMSContent' . (int) Tab::getIdFromClassName('AdminCMSContent') . (int) $cookie->id_employee) . '">
					<img src="../img/admin/home.gif" alt="Home" /></a> ';
        }
        $path = $edit . '<a href="' . $urlBase . '&id_cms_category=' . $category->id . '&viewcategory&token=' . Tools14::getAdminToken('AdminCMSContent' . (int) Tab::getIdFromClassName('AdminCMSContent') . (int) $cookie->id_employee) . '">
		' . $name . '</a> > ' . $path;
        if ($category->id == 1) {
            return substr($path, 0, strlen($path) - 3);
        }
        return getPath($urlBase, $category->id_parent, $path, '', 'cms');
    }
}
Ejemplo n.º 3
0
    private function _getJsInit()
    {
        global $currentIndex, $cookie;
        $js = '';
        if (method_exists('Tools', 'getAdminTokenLite')) {
            $token_preferences = Tools14::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").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);
	}
}';
        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(){

	$("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 20 minutes (before aborting an ajax request)
	$.ajaxSetup({timeout:1200000});

	// 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=' . Tools14::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");
	});

});

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());
	}
	showConfigResult(res.next_desc);
	$("#upgradeNow").unbind();
	$("#upgradeNow").replaceWith("<a class=\\"button-autoupgrade\\" href=\\"' . $currentIndex . '&token=' . $this->token . '\\" >' . $this->l('Click to refresh the page and use the new configuration', 'AdminSelfUpgrade', true) . '</a>");
}
function startProcess(type){
	if (type == "upgrade")
		msg = "' . $this->l('an upgrade is currently in progress ... Click "OK" to abort.', 'AdminTab', true, false) . '";
	else
		msg = "' . $this->l('a restoration is currently in progress ... Click "OK" to abort.', true, false) . '";


	// hide useless divs, show activity log
	$("#informationBlock,#comparisonBlock,#currentConfigurationBlock,#backupOptionsBlock,#upgradeOptionsBlock,#upgradeButtonBlock").slideUp("fast");
	$("#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");
			$("#rollback").click();
			return false;
		}
		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")
			.addClass("conf")
			.removeClass("fail")
			.html("<p>' . $this->l('Upgrade complete') . '</p>")
			.show();
		$("#infoStep").html("<h3>' . $this->l('Upgrade Complete !', 'AdminSelfUpgrade', true) . '</h3>");
	}
	else
	{
		params = res.nextParams
		$("#pleaseWait").hide();
		$("#upgradeResultCheck")
			.addClass("fail")
			.removeClass("ok")
			.html("<p>' . $this->l('Upgrade complete, but warnings has been found. Please restore your shop.') . '</p>")
			.show("slow");
		$("#infoStep").html("<h3>' . $this->l('Upgrade Complete, but warnings has been found.', 'AdminSelfUpgrade', true) . '</h3>");
	}

	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 functionnal (try to create an account, place an order...)', 'AdminSelfUpgrade', true) . '",
		"' . $this->l('Product images does 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")
		.addClass("hint clear")
		.html("<h3>' . $this->l('ToDo list:') . '</h3>")
	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")
		.addClass("ok")
		.removeClass("fail")
		.html("<p>' . $this->l('Restoration complete.') . '</p>")
		.show("slow");
	updateInfoStep("<h3>' . $this->l('Restoration complete.') . '</h3>");
	$(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;
	var PS_AUTOUP_BACKUP;
	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){
	var _PS_MODE_DEV_;
	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)
		{
			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(["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 cancelled. 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 cancelled. An error happens.') . '");
		$(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 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");
				}
			}
		})
	$.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(){
			$("#advanced").hide();
			$("#normal").show();
		});
	';
        $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 to 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 == "")
				{
					showConfigResult("' . $this->l('You need to enter the version number associated to 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 skip 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 preserve files 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;
    }