function smartyTranslate($params, &$smarty)
{
    $htmlentities = !isset($params['js']);
    $pdf = isset($params['pdf']);
    $addslashes = isset($params['slashes']);
    $sprintf = isset($params['sprintf']) ? $params['sprintf'] : false;
    if ($pdf) {
        return Translate::getPdfTranslation($params['s']);
    }
    $filename = !isset($smarty->compiler_object) || !is_object($smarty->compiler_object->template) ? $smarty->template_resource : $smarty->compiler_object->template->getTemplateFilepath();
    // If the template is part of a module
    if (!empty($params['mod'])) {
        return Translate::getModuleTranslation($params['mod'], $params['s'], basename($filename, '.tpl'), $sprintf);
    }
    // If the tpl is at the root of the template folder
    if (dirname($filename) == '.') {
        $class = 'index';
    } elseif (strpos($filename, 'helpers') === 0) {
        $class = 'Helper';
    } else {
        // Split by \ and / to get the folder tree for the file
        $folder_tree = preg_split('#[/\\\\]#', $filename);
        $key = array_search('controllers', $folder_tree);
        // If there was a match, construct the class name using the child folder name
        // Eg. xxx/controllers/customers/xxx => AdminCustomers
        if ($key !== false) {
            $class = 'Admin' . Tools::toCamelCase($folder_tree[$key + 1], true);
        } else {
            $class = null;
        }
    }
    return Translate::getAdminTranslation($params['s'], $class, $addslashes, $htmlentities, $sprintf);
}
 /**
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     $action = Tools::getValue('action');
     if (!Tools::isSubmit('myajax')) {
         $this->assign();
     } elseif (!empty($action) && method_exists($this, 'ajaxProcess' . Tools::toCamelCase($action))) {
         $this->{'ajaxProcess' . Tools::toCamelCase($action)}();
     } else {
         die(Tools::jsonEncode(array('error' => 'method doesn\'t exist')));
     }
 }
Example #3
0
    /**
     * Options lists
     */
    public function displayOptionsList()
    {
        $tab = Tab::getTab($this->context->language->id, $this->id);
        // Retrocompatibility < 1.5.0
        if (!$this->optionsList && $this->_fieldsOptions) {
            $this->optionsList = array('options' => array('title' => $this->optionTitle ? $this->optionTitle : $this->l('Options'), 'fields' => $this->_fieldsOptions));
        }
        if (!$this->optionsList) {
            return;
        }
        echo '<br />';
        echo '<script type="text/javascript">
			id_language = Number(' . $this->context->language->id . ');
		</script>';
        $action = Tools::safeOutput(self::$currentIndex . '&submitOptions' . $this->table . '=1&token=' . $this->token);
        echo '<form action="' . $action . '" method="post" enctype="multipart/form-data">';
        foreach ($this->optionsList as $category => $categoryData) {
            $required = false;
            $this->displayTopOptionCategory($category, $categoryData);
            echo '<fieldset>';
            // Options category title
            $legend = '<img src="' . (!empty($tab['module']) && file_exists($_SERVER['DOCUMENT_ROOT'] . _MODULE_DIR_ . $tab['module'] . '/' . $tab['class_name'] . '.gif') ? _MODULE_DIR_ . $tab['module'] . '/' : '../img/t/') . $tab['class_name'] . '.gif" /> ';
            $legend .= isset($categoryData['title']) ? $categoryData['title'] : $this->l('Options');
            echo '<legend>' . $legend . '</legend>';
            // Category fields
            if (!isset($categoryData['fields'])) {
                continue;
            }
            // Category description
            if (isset($categoryData['description']) && $categoryData['description']) {
                echo '<p class="optionsDescription">' . $categoryData['description'] . '</p>';
            }
            foreach ($categoryData['fields'] as $key => $field) {
                // Field value
                $value = Tools::getValue($key, Configuration::get($key));
                if (!Validate::isCleanHtml($value)) {
                    $value = Configuration::get($key);
                }
                if (isset($field['defaultValue']) && !$value) {
                    $value = $field['defaultValue'];
                }
                // Check if var is invisible (can't edit it in current shop context), or disable (use default value for multishop)
                $isDisabled = $isInvisible = false;
                if (Shop::isFeatureActive()) {
                    if (isset($field['visibility']) && $field['visibility'] > Shop::getContext()) {
                        $isDisabled = true;
                        $isInvisible = true;
                    } elseif (Shop::getContext() != Shop::CONTEXT_ALL && !Configuration::isOverridenByCurrentContext($key)) {
                        $isDisabled = true;
                    }
                }
                // Display title
                echo '<div style="clear: both; padding-top:15px;" id="conf_id_' . $key . '" ' . ($isInvisible ? 'class="isInvisible"' : '') . '>';
                if ($field['title']) {
                    echo '<label class="conf_title">';
                    // Is this field required ?
                    if (isset($field['required']) && $field['required']) {
                        $required = true;
                        echo '<sup>*</sup> ';
                    }
                    echo $field['title'] . '</label>';
                }
                echo '<div class="margin-form" style="padding-top:5px;">';
                // Display option inputs
                $method = 'displayOptionType' . Tools::toCamelCase($field['type'], true);
                if (!method_exists($this, $method)) {
                    $this->displayOptionTypeText($key, $field, $value);
                } else {
                    $this->{$method}($key, $field, $value);
                }
                // Multishop default value
                if (Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_ALL && !$isInvisible) {
                    echo '<div class="preference_default_multishop">
							<label>
								<input type="checkbox" name="multishopOverrideOption[' . $key . ']" value="1" ' . ($isDisabled ? 'checked="checked"' : '') . ' onclick="checkMultishopDefaultValue(this, \'' . $key . '\')" /> ' . $this->l('Use default value') . '
							</label>
						</div>';
                }
                // Field description
                //echo (isset($field['desc']) ? '<p class="preference_description">'.((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>' : '');
                echo isset($field['desc']) ? '<p class="preference_description">' . $field['desc'] . '</p>' : '';
                // Is this field invisible in current shop context ?
                echo $isInvisible ? '<p class="multishop_warning">' . $this->l('You cannot change the value of this configuration field in this shop context') . '</p>' : '';
                echo '</div></div>';
            }
            echo '<div align="center" style="margin-top: 20px;">';
            echo '<input type="submit" value="' . $this->l('   Save   ') . '" name="submit' . ucfirst($category) . $this->table . '" class="button" />';
            echo '</div>';
            if ($required) {
                echo '<div class="small"><sup>*</sup> ' . $this->l('Required field') . '</div>';
            }
            echo '</fieldset><br />';
            $this->displayBottomOptionCategory($category, $categoryData);
        }
        echo '</form>';
    }
Example #4
0
 /**
  * Returns webservice parameters of this object.
  *
  * @param string|null $ws_params_attribute_name
  *
  * @return array
  */
 public function getWebserviceParameters($ws_params_attribute_name = null)
 {
     $this->cacheFieldsRequiredDatabase();
     $default_resource_parameters = array('objectSqlId' => $this->def['primary'], 'retrieveData' => array('className' => get_class($this), 'retrieveMethod' => 'getWebserviceObjectList', 'params' => array(), 'table' => $this->def['table']), 'fields' => array('id' => array('sqlId' => $this->def['primary'], 'i18n' => false)));
     if ($ws_params_attribute_name === null) {
         $ws_params_attribute_name = 'webserviceParameters';
     }
     if (!isset($this->{$ws_params_attribute_name}['objectNodeName'])) {
         $default_resource_parameters['objectNodeName'] = $this->def['table'];
     }
     if (!isset($this->{$ws_params_attribute_name}['objectsNodeName'])) {
         $default_resource_parameters['objectsNodeName'] = $this->def['table'] . 's';
     }
     if (isset($this->{$ws_params_attribute_name}['associations'])) {
         foreach ($this->{$ws_params_attribute_name}['associations'] as $assoc_name => &$association) {
             if (!array_key_exists('setter', $association) || isset($association['setter']) && !$association['setter']) {
                 $association['setter'] = Tools::toCamelCase('set_ws_' . $assoc_name);
             }
             if (!array_key_exists('getter', $association)) {
                 $association['getter'] = Tools::toCamelCase('get_ws_' . $assoc_name);
             }
         }
     }
     if (isset($this->{$ws_params_attribute_name}['retrieveData']) && isset($this->{$ws_params_attribute_name}['retrieveData']['retrieveMethod'])) {
         unset($default_resource_parameters['retrieveData']['retrieveMethod']);
     }
     $resource_parameters = array_merge_recursive($default_resource_parameters, $this->{$ws_params_attribute_name});
     $required_fields = isset(self::$fieldsRequiredDatabase[get_class($this)]) ? self::$fieldsRequiredDatabase[get_class($this)] : array();
     foreach ($this->def['fields'] as $field_name => $details) {
         if (!isset($resource_parameters['fields'][$field_name])) {
             $resource_parameters['fields'][$field_name] = array();
         }
         $current_field = array();
         $current_field['sqlId'] = $field_name;
         if (isset($details['size'])) {
             $current_field['maxSize'] = $details['size'];
         }
         if (isset($details['lang'])) {
             $current_field['i18n'] = $details['lang'];
         } else {
             $current_field['i18n'] = false;
         }
         if (isset($details['required']) && $details['required'] === true || in_array($field_name, $required_fields)) {
             $current_field['required'] = true;
         } else {
             $current_field['required'] = false;
         }
         if (isset($details['validate'])) {
             $current_field['validateMethod'] = array_key_exists('validateMethod', $resource_parameters['fields'][$field_name]) ? array_merge($resource_parameters['fields'][$field_name]['validateMethod'], array($details['validate'])) : array($details['validate']);
         }
         $resource_parameters['fields'][$field_name] = array_merge($resource_parameters['fields'][$field_name], $current_field);
         if (isset($details['ws_modifier'])) {
             $resource_parameters['fields'][$field_name]['modifier'] = $details['ws_modifier'];
         }
     }
     if (isset($this->date_add)) {
         $resource_parameters['fields']['date_add']['setter'] = false;
     }
     if (isset($this->date_upd)) {
         $resource_parameters['fields']['date_upd']['setter'] = false;
     }
     foreach ($resource_parameters['fields'] as $key => $resource_parameters_field) {
         if (!isset($resource_parameters_field['sqlId'])) {
             $resource_parameters['fields'][$key]['sqlId'] = $key;
         }
     }
     return $resource_parameters;
 }
function smartyTranslate($params, &$smarty)
{
    $htmlentities = !isset($params['js']);
    $pdf = isset($params['pdf']);
    $addslashes = isset($params['slashes']) || isset($params['js']);
    $sprintf = isset($params['sprintf']) ? $params['sprintf'] : array();
    if (!empty($params['d'])) {
        if (isset($params['tags'])) {
            $backTrace = debug_backtrace();
            $errorMessage = sprintf('Unable to translate "%s" in %s. tags() is not supported anymore, please use sprintf().', $params['s'], $backTrace[0]['args'][1]->template_resource);
            if (_PS_MODE_DEV_) {
                throw new Exception($errorMessage);
            } else {
                PrestaShopLogger::addLog($errorMessage);
            }
        }
        if (!is_array($sprintf)) {
            $backTrace = debug_backtrace();
            $errorMessage = sprintf('Unable to translate "%s" in %s. sprintf() parameter should be an array.', $params['s'], $backTrace[0]['args'][1]->template_resource);
            if (_PS_MODE_DEV_) {
                throw new Exception($errorMessage);
            } else {
                PrestaShopLogger::addLog($errorMessage);
                return $params['s'];
            }
        }
        return Context::getContext()->getTranslator()->trans($params['s'], $sprintf, $params['d']);
    }
    if ($pdf) {
        return Translate::smartyPostProcessTranslation(Translate::getPdfTranslation($params['s'], $sprintf), $params);
    }
    $filename = !isset($smarty->compiler_object) || !is_object($smarty->compiler_object->template) ? $smarty->template_resource : $smarty->compiler_object->template->getTemplateFilepath();
    // If the template is part of a module
    if (!empty($params['mod'])) {
        return Translate::smartyPostProcessTranslation(Translate::getModuleTranslation($params['mod'], $params['s'], basename($filename, '.tpl'), $sprintf, isset($params['js'])), $params);
    }
    // If the tpl is at the root of the template folder
    if (dirname($filename) == '.') {
        $class = 'index';
    }
    // If the tpl is used by a Helper
    if (strpos($filename, 'helpers') === 0) {
        $class = 'Helper';
    } else {
        // If the tpl is used by a Controller
        if (!empty(Context::getContext()->override_controller_name_for_translations)) {
            $class = Context::getContext()->override_controller_name_for_translations;
        } elseif (isset(Context::getContext()->controller)) {
            $class_name = get_class(Context::getContext()->controller);
            $class = substr($class_name, 0, strpos(Tools::strtolower($class_name), 'controller'));
        } else {
            // Split by \ and / to get the folder tree for the file
            $folder_tree = preg_split('#[/\\\\]#', $filename);
            $key = array_search('controllers', $folder_tree);
            // If there was a match, construct the class name using the child folder name
            // Eg. xxx/controllers/customers/xxx => AdminCustomers
            if ($key !== false) {
                $class = 'Admin' . Tools::toCamelCase($folder_tree[$key + 1], true);
            } elseif (isset($folder_tree[0])) {
                $class = 'Admin' . Tools::toCamelCase($folder_tree[0], true);
            }
        }
    }
    return Translate::smartyPostProcessTranslation(Translate::getAdminTranslation($params['s'], $class, $addslashes, $htmlentities, $sprintf), $params);
}
 public function run()
 {
     $this->init();
     $this->profiler[] = $this->stamp('init');
     if ($this->checkAccess()) {
         $this->profiler[] = $this->stamp('checkAccess');
         if (!$this->content_only && ($this->display_header || isset($this->className) && $this->className)) {
             $this->setMedia();
             $this->profiler[] = $this->stamp('setMedia');
         }
         $this->postProcess();
         $this->profiler[] = $this->stamp('postProcess');
         if (!$this->content_only && ($this->display_header || isset($this->className) && $this->className)) {
             $this->initHeader();
             $this->profiler[] = $this->stamp('initHeader');
         }
         $this->initContent();
         $this->profiler[] = $this->stamp('initContent');
         if (!$this->content_only && ($this->display_footer || isset($this->className) && $this->className)) {
             $this->initFooter();
             $this->profiler[] = $this->stamp('initFooter');
         }
         if ($this->ajax) {
             $action = Tools::toCamelCase(Tools::getValue('action'), true);
             if (!empty($action) && method_exists($this, 'displayAjax' . $action)) {
                 $this->{'displayAjax' . $action}();
             } elseif (method_exists($this, 'displayAjax')) {
                 $this->displayAjax();
             }
             return;
         }
     } else {
         $this->initCursedPage();
     }
     $this->displayProfiling();
 }
Example #7
0
 protected function updateOptions($token)
 {
     global $currentIndex;
     if ($this->tabAccess['edit'] === '1') {
         foreach ($this->_fieldsOptions as $key => $field) {
             if ($this->validateField(Tools::getValue($key), $field)) {
                 // check if a method updateOptionFieldName is available
                 $method_name = 'updateOption' . Tools::toCamelCase($key, true);
                 if (method_exists($this, $method_name)) {
                     $this->{$method_name}(Tools::getValue($key));
                 } elseif ($field['type'] == 'textLang' or $field['type'] == 'textareaLang') {
                     $languages = Language::getLanguages(false);
                     $list = array();
                     foreach ($languages as $language) {
                         $val = isset($field['cast']) ? $field['cast'](Tools::getValue($key . '_' . $language['id_lang'])) : Tools::getValue($key . '_' . $language['id_lang']);
                         if (Validate::isCleanHtml($val)) {
                             $list[$language['id_lang']] = $val;
                         } else {
                             $this->_errors[] = Tools::displayError('Can not add configuration ' . $key . ' for lang ' . Language::getIsoById((int) $language['id_lang']));
                         }
                     }
                     Configuration::updateValue($key, $list);
                 } else {
                     $val = isset($field['cast']) ? $field['cast'](Tools::getValue($key)) : Tools::getValue($key);
                     if (Validate::isCleanHtml($val)) {
                         Configuration::updateValue($key, $val);
                     } else {
                         $this->_errors[] = Tools::displayError('Can not add configuration ' . $key);
                     }
                 }
             }
         }
         if (count($this->_errors) <= 0) {
             Tools::redirectAdmin($currentIndex . '&conf=6&token=' . $token);
         }
     } else {
         $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
     }
 }
Example #8
0
 /**
  * Start Webservice request
  * 	Check webservice activation
  * 	Check autentication
  * 	Check resource
  * 	Check HTTP Method
  * 	Execute the action
  * 	Display the result
  *
  * @param string $key
  * @param string $method
  * @param string $url
  * @param string $params
  * @param string $inputXml
  *
  * @return array Returns an array of results (headers, content, type of resource...)
  */
 public function fetch($key, $method, $url, $params, $bad_class_name, $inputXml = NULL)
 {
     // Time logger
     $this->_startTime = microtime(true);
     $this->objects = array();
     // Error handler
     set_error_handler(array($this, 'webserviceErrorHandler'));
     ini_set('html_errors', 'off');
     // Two global vars, for compatibility with the PS core...
     global $webservice_call, $display_errors;
     $webservice_call = true;
     $display_errors = strtolower(ini_get('display_errors')) != 'off';
     // __PS_BASE_URI__ is from Shop::$current_base_uri
     $this->wsUrl = Tools::getHttpHost(true) . __PS_BASE_URI__ . 'api/';
     // set the output object which manage the content and header structure and informations
     $this->objOutput = new WebserviceOutputBuilder($this->wsUrl);
     $this->_key = trim($key);
     $this->outputFormat = isset($params['output_format']) ? $params['output_format'] : $this->outputFormat;
     // Set the render object to build the output on the asked format (XML, JSON, CSV, ...)
     $this->objOutput->setObjectRender($this->getOutputObject($this->outputFormat));
     $this->params = $params;
     // Check webservice activation and request authentication
     if ($this->webserviceChecks()) {
         if ($bad_class_name) {
             $this->setError(500, 'Bad override class name for this key. Please update class_name field', 126);
         }
         // parse request url
         $this->method = $method;
         $this->urlSegment = explode('/', $url);
         $this->urlFragments = $params;
         $this->_inputXml = $inputXml;
         $this->depth = isset($this->urlFragments['depth']) ? (int) $this->urlFragments['depth'] : $this->depth;
         try {
             // Method below set a particular fonction to use on the price field for products entity
             // @see WebserviceRequest::getPriceForProduct() method
             // @see WebserviceOutputBuilder::setSpecificField() method
             $this->objOutput->setSpecificField($this, 'getPriceForProduct', 'price', 'products');
             if (isset($this->urlFragments['price'])) {
                 $this->objOutput->setVirtualField($this, 'specificPriceForCombination', 'combinations', $this->urlFragments['price']);
                 $this->objOutput->setVirtualField($this, 'specificPriceForProduct', 'products', $this->urlFragments['price']);
             }
         } catch (Exception $e) {
             $this->setError(500, $e->getMessage(), $e->getCode());
         }
         if (isset($this->urlFragments['language'])) {
             $this->_available_languages = $this->filterLanguage();
         } else {
             foreach (Language::getLanguages() as $key => $language) {
                 $this->_available_languages[] = $language['id_lang'];
             }
         }
         if (empty($this->_available_languages)) {
             $this->setError(400, 'language is not available', 81);
         }
         // Need to set available languages for the render object.
         // Thus we can filter i18n field for the output
         // @see WebserviceOutputXML::renderField() method for example
         $this->objOutput->objectRender->setLanguages($this->_available_languages);
         // check method and resource
         if (empty($this->errors) && $this->checkResource() && $this->checkHTTPMethod()) {
             // The resource list is necessary for build the output
             $this->objOutput->setWsResources($this->resourceList);
             // if the resource is a core entity...
             if (!isset($this->resourceList[$this->urlSegment[0]]['specific_management']) || !$this->resourceList[$this->urlSegment[0]]['specific_management']) {
                 // load resource configuration
                 if ($this->urlSegment[0] != '') {
                     $object = new $this->resourceList[$this->urlSegment[0]]['class']();
                     if (isset($this->resourceList[$this->urlSegment[0]]['parameters_attribute'])) {
                         $this->resourceConfiguration = $object->getWebserviceParameters($this->resourceList[$this->urlSegment[0]]['parameters_attribute']);
                     } else {
                         $this->resourceConfiguration = $object->getWebserviceParameters();
                     }
                 }
                 $success = false;
                 // execute the action
                 switch ($this->method) {
                     case 'GET':
                     case 'HEAD':
                         if ($this->executeEntityGetAndHead()) {
                             $success = true;
                         }
                         break;
                     case 'POST':
                         if ($this->executeEntityPost()) {
                             $success = true;
                         }
                         break;
                     case 'PUT':
                         if ($this->executeEntityPut()) {
                             $success = true;
                         }
                         break;
                     case 'DELETE':
                         $this->executeEntityDelete();
                         break;
                 }
                 // Need to set an object for the WebserviceOutputBuilder object in any case
                 // because schema need to get webserviceParameters of this object
                 if (isset($object)) {
                     $this->objects['empty'] = $object;
                 }
             } else {
                 $specificObjectName = 'WebserviceSpecificManagement' . ucfirst(Tools::toCamelCase($this->urlSegment[0]));
                 if (!class_exists($specificObjectName)) {
                     $this->setError(501, sprintf('The specific management class is not implemented for the "%s" entity.', $this->urlSegment[0]), 124);
                 } else {
                     $this->objectSpecificManagement = new $specificObjectName();
                     $this->objectSpecificManagement->setObjectOutput($this->objOutput)->setWsObject($this);
                     try {
                         $this->objectSpecificManagement->manage();
                     } catch (WebserviceException $e) {
                         if ($e->getType() == WebserviceException::DID_YOU_MEAN) {
                             $this->setErrorDidYouMean($e->getStatus(), $e->getMessage(), $e->getWrongValue(), $e->getAvailableValues(), $e->getCode());
                         } elseif ($e->getType() == WebserviceException::SIMPLE) {
                             $this->setError($e->getStatus(), $e->getMessage(), $e->getCode());
                         }
                     }
                 }
             }
         }
     }
     $return = $this->returnOutput();
     unset($webservice_call);
     unset($display_errors);
     return $return;
 }
Example #9
0
/**
 * for retrocompatibility with old AdminTab, old index.php
 *
 * @return void
 */
function runAdminTab($tab, $ajaxMode = false)
{
    $ajaxMode = (bool) $ajaxMode;
    require_once _PS_ADMIN_DIR_ . '/init.php';
    $cookie = Context::getContext()->cookie;
    if (empty($tab) && !sizeof($_POST)) {
        $tab = 'AdminDashboard';
        $_POST['tab'] = $tab;
        $_POST['token'] = Tools::getAdminTokenLite($tab);
    }
    // $tab = $_REQUEST['tab'];
    if ($adminObj = checkingTab($tab)) {
        Context::getContext()->controller = $adminObj;
        // init is different for new tabs (AdminController) and old tabs (AdminTab)
        if ($adminObj instanceof AdminController) {
            if ($ajaxMode) {
                $adminObj->ajax = true;
            }
            $adminObj->path = dirname($_SERVER["PHP_SELF"]);
            $adminObj->run();
        } else {
            if (!$ajaxMode) {
                require_once _PS_ADMIN_DIR_ . '/header.inc.php';
            }
            $isoUser = Context::getContext()->language->id;
            $tabs = array();
            $tabs = Tab::recursiveTab($adminObj->id, $tabs);
            $tabs = array_reverse($tabs);
            $bread = '';
            foreach ($tabs as $key => $item) {
                $bread .= ' <img src="../img/admin/separator_breadcrumb.png" style="margin-right:5px" alt="&gt;" />';
                if (count($tabs) - 1 > $key) {
                    $bread .= '<a href="?tab=' . $item['class_name'] . '&token=' . Tools::getAdminToken($item['class_name'] . intval($item['id_tab']) . (int) Context::getContext()->employee->id) . '">';
                }
                $bread .= $item['name'];
                if (count($tabs) - 1 > $key) {
                    $bread .= '</a>';
                }
            }
            if (!$ajaxMode && Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_ALL && Context::getContext()->controller->multishop_context != Shop::CONTEXT_ALL) {
                echo '<div class="multishop_info">';
                if (Shop::getContext() == Shop::CONTEXT_GROUP) {
                    $shop_group = new ShopGroup((int) Shop::getContextShopGroupID());
                    printf(Translate::getAdminTranslation('You are configuring your store for group shop %s'), '<b>' . $shop_group->name . '</b>');
                } elseif (Shop::getContext() == Shop::CONTEXT_SHOP) {
                    printf(Translate::getAdminTranslation('You are configuring your store for shop %s'), '<b>' . Context::getContext()->shop->name . '</b>');
                }
                echo '</div>';
            }
            if (Validate::isLoadedObject($adminObj)) {
                if ($adminObj->checkToken()) {
                    if ($ajaxMode) {
                        // the differences with index.php is here
                        $adminObj->ajaxPreProcess();
                        $action = Tools::getValue('action');
                        // no need to use displayConf() here
                        if (!empty($action) && method_exists($adminObj, 'ajaxProcess' . Tools::toCamelCase($action))) {
                            $adminObj->{'ajaxProcess' . Tools::toCamelCase($action)}();
                        } else {
                            $adminObj->ajaxProcess();
                        }
                        // @TODO We should use a displayAjaxError
                        $adminObj->displayErrors();
                        if (!empty($action) && method_exists($adminObj, 'displayAjax' . Tools::toCamelCase($action))) {
                            $adminObj->{'displayAjax' . $action}();
                        } else {
                            $adminObj->displayAjax();
                        }
                    } else {
                        /* Filter memorization */
                        if (isset($_POST) && !empty($_POST) && isset($adminObj->table)) {
                            foreach ($_POST as $key => $value) {
                                if (is_array($adminObj->table)) {
                                    foreach ($adminObj->table as $table) {
                                        if (strncmp($key, $table . 'Filter_', 7) === 0 || strncmp($key, 'submitFilter', 12) === 0) {
                                            $cookie->{$key} = !is_array($value) ? $value : serialize($value);
                                        }
                                    }
                                } elseif (strncmp($key, $adminObj->table . 'Filter_', 7) === 0 || strncmp($key, 'submitFilter', 12) === 0) {
                                    $cookie->{$key} = !is_array($value) ? $value : serialize($value);
                                }
                            }
                        }
                        if (isset($_GET) && !empty($_GET) && isset($adminObj->table)) {
                            foreach ($_GET as $key => $value) {
                                if (is_array($adminObj->table)) {
                                    foreach ($adminObj->table as $table) {
                                        if (strncmp($key, $table . 'OrderBy', 7) === 0 || strncmp($key, $table . 'Orderway', 8) === 0) {
                                            $cookie->{$key} = $value;
                                        }
                                    }
                                } elseif (strncmp($key, $adminObj->table . 'OrderBy', 7) === 0 || strncmp($key, $adminObj->table . 'Orderway', 12) === 0) {
                                    $cookie->{$key} = $value;
                                }
                            }
                        }
                        $adminObj->displayConf();
                        $adminObj->postProcess();
                        $adminObj->displayErrors();
                        $adminObj->display();
                        include _PS_ADMIN_DIR_ . '/footer.inc.php';
                    }
                } else {
                    if ($ajaxMode) {
                        // If this is an XSS attempt, then we should only display a simple, secure page
                        if (ob_get_level() && ob_get_length() > 0) {
                            ob_clean();
                        }
                        // ${1} in the replacement string of the regexp is required, because the token may begin with a number and mix up with it (e.g. $17)
                        $url = preg_replace('/([&?]token=)[^&]*(&.*)?$/', '${1}' . $adminObj->token . '$2', $_SERVER['REQUEST_URI']);
                        if (false === strpos($url, '?token=') && false === strpos($url, '&token=')) {
                            $url .= '&token=' . $adminObj->token;
                        }
                        // we can display the correct url
                        // die(Tools::jsonEncode(array(Translate::getAdminTranslation('Invalid security token'),$url)));
                        die(Tools::jsonEncode(Translate::getAdminTranslation('Invalid security token')));
                    } else {
                        // If this is an XSS attempt, then we should only display a simple, secure page
                        if (ob_get_level() && ob_get_length() > 0) {
                            ob_clean();
                        }
                        // ${1} in the replacement string of the regexp is required, because the token may begin with a number and mix up with it (e.g. $17)
                        $url = preg_replace('/([&?]token=)[^&]*(&.*)?$/', '${1}' . $adminObj->token . '$2', $_SERVER['REQUEST_URI']);
                        if (false === strpos($url, '?token=') && false === strpos($url, '&token=')) {
                            $url .= '&token=' . $adminObj->token;
                        }
                        $message = Translate::getAdminTranslation('Invalid security token');
                        echo '<html><head><title>' . $message . '</title></head><body style="font-family:Arial,Verdana,Helvetica,sans-serif;background-color:#EC8686">
							<div style="background-color:#FAE2E3;border:1px solid #000000;color:#383838;font-weight:700;line-height:20px;margin:0 0 10px;padding:10px 15px;width:500px">
								<img src="../img/admin/error2.png" style="margin:-4px 5px 0 0;vertical-align:middle">
								' . $message . '
							</div>';
                        echo '<a href="' . htmlentities($url) . '" method="get" style="float:left;margin:10px">
								<input type="button" value="' . Tools::htmlentitiesUTF8(Translate::getAdminTranslation('I understand the risks and I really want to display this page')) . '" style="height:30px;margin-top:5px" />
							</a>
							<a href="index.php" method="get" style="float:left;margin:10px">
								<input type="button" value="' . Tools::htmlentitiesUTF8(Translate::getAdminTranslation('Take me out of here!')) . '" style="height:40px" />
							</a>
						</body></html>';
                        die;
                    }
                }
            }
        }
    }
}
Example #10
0
 public function getWebserviceParameters($wsParamsAttributeName = null)
 {
     $defaultResourceParameters = array('objectSqlId' => $this->identifier, 'retrieveData' => array('className' => get_class($this), 'retrieveMethod' => 'getWebserviceObjectList', 'params' => array(), 'table' => $this->table), 'fields' => array('id' => array('sqlId' => $this->identifier, 'i18n' => false)));
     if (is_null($wsParamsAttributeName)) {
         $wsParamsAttributeName = 'webserviceParameters';
     }
     if (!isset($this->{$wsParamsAttributeName}['objectNodeName'])) {
         $defaultResourceParameters['objectNodeName'] = $this->table;
     }
     if (!isset($this->{$wsParamsAttributeName}['objectsNodeName'])) {
         $defaultResourceParameters['objectsNodeName'] = $this->table . 's';
     }
     if (isset($this->{$wsParamsAttributeName}['associations'])) {
         foreach ($this->{$wsParamsAttributeName}['associations'] as $assocName => &$association) {
             if (!array_key_exists('setter', $association) || isset($association['setter']) && !$association['setter']) {
                 $association['setter'] = Tools::toCamelCase('set_ws_' . $assocName);
             }
             if (!array_key_exists('getter', $association)) {
                 $association['getter'] = Tools::toCamelCase('get_ws_' . $assocName);
             }
         }
     }
     if (isset($this->{$wsParamsAttributeName}['retrieveData']) && isset($this->{$wsParamsAttributeName}['retrieveData']['retrieveMethod'])) {
         unset($defaultResourceParameters['retrieveData']['retrieveMethod']);
     }
     $resourceParameters = array_merge_recursive($defaultResourceParameters, $this->{$wsParamsAttributeName});
     if (isset($this->fieldsSize)) {
         foreach ($this->fieldsSize as $fieldName => $maxSize) {
             if (!isset($resourceParameters['fields'][$fieldName])) {
                 $resourceParameters['fields'][$fieldName] = array('required' => false);
             }
             $resourceParameters['fields'][$fieldName] = array_merge($resourceParameters['fields'][$fieldName], $resourceParameters['fields'][$fieldName] = array('sqlId' => $fieldName, 'maxSize' => $maxSize, 'i18n' => false));
         }
     }
     if (isset($this->fieldsValidate)) {
         foreach ($this->fieldsValidate as $fieldName => $validateMethod) {
             if (!isset($resourceParameters['fields'][$fieldName])) {
                 $resourceParameters['fields'][$fieldName] = array('required' => false);
             }
             $resourceParameters['fields'][$fieldName] = array_merge($resourceParameters['fields'][$fieldName], $resourceParameters['fields'][$fieldName] = array('sqlId' => $fieldName, 'validateMethod' => array_key_exists('validateMethod', $resourceParameters['fields'][$fieldName]) ? array_merge($resourceParameters['fields'][$fieldName]['validateMethod'], array($validateMethod)) : array($validateMethod), 'i18n' => false));
         }
     }
     if (isset($this->fieldsRequired)) {
         $fieldsRequired = array_merge($this->fieldsRequired, isset(self::$fieldsRequiredDatabase[get_class($this)]) ? self::$fieldsRequiredDatabase[get_class($this)] : array());
         foreach ($fieldsRequired as $fieldRequired) {
             if (!isset($resourceParameters['fields'][$fieldRequired])) {
                 $resourceParameters['fields'][$fieldRequired] = array();
             }
             $resourceParameters['fields'][$fieldRequired] = array_merge($resourceParameters['fields'][$fieldRequired], $resourceParameters['fields'][$fieldRequired] = array('sqlId' => $fieldRequired, 'required' => true, 'i18n' => false));
         }
     }
     if (isset($this->fieldsSizeLang)) {
         foreach ($this->fieldsSizeLang as $fieldName => $maxSize) {
             if (!isset($resourceParameters['fields'][$fieldName])) {
                 $resourceParameters['fields'][$fieldName] = array('required' => false);
             }
             $resourceParameters['fields'][$fieldName] = array_merge($resourceParameters['fields'][$fieldName], $resourceParameters['fields'][$fieldName] = array('sqlId' => $fieldName, 'maxSize' => $maxSize, 'i18n' => true));
         }
     }
     if (isset($this->fieldsValidateLang)) {
         foreach ($this->fieldsValidateLang as $fieldName => $validateMethod) {
             if (!isset($resourceParameters['fields'][$fieldName])) {
                 $resourceParameters['fields'][$fieldName] = array('required' => false);
             }
             $resourceParameters['fields'][$fieldName] = array_merge($resourceParameters['fields'][$fieldName], $resourceParameters['fields'][$fieldName] = array('sqlId' => $fieldName, 'validateMethod' => array_key_exists('validateMethod', $resourceParameters['fields'][$fieldName]) ? array_merge($resourceParameters['fields'][$fieldName]['validateMethod'], array($validateMethod)) : array($validateMethod), 'i18n' => true));
         }
     }
     if (isset($this->fieldsRequiredLang)) {
         foreach ($this->fieldsRequiredLang as $field) {
             if (!isset($resourceParameters['fields'][$field])) {
                 $resourceParameters['fields'][$field] = array();
             }
             $resourceParameters['fields'][$field] = array_merge($resourceParameters['fields'][$field], $resourceParameters['fields'][$field] = array('sqlId' => $field, 'required' => true, 'i18n' => true));
         }
     }
     if (isset($this->date_add)) {
         $resourceParameters['fields']['date_add']['setter'] = false;
     }
     if (isset($this->date_upd)) {
         $resourceParameters['fields']['date_upd']['setter'] = false;
     }
     foreach ($resourceParameters['fields'] as $key => &$resourceParametersField) {
         if (!isset($resourceParametersField['sqlId'])) {
             $resourceParametersField['sqlId'] = $key;
         }
     }
     return $resourceParameters;
 }
 /**
  * Save form data.
  */
 protected function _postProcess()
 {
     $has_processed_something = false;
     $post_keys_switchable = array_keys(array_merge($this->getConfigFormLabelsManagerValues(), $this->getConfigFormFeaturesManagerValues()));
     $post_keys_complex = array('AEUC_legalContentManager', 'AEUC_emailAttachmentsManager', 'PS_PRODUCT_WEIGHT_PRECISION', 'discard_tpl_warn');
     $i10n_inputs_received = array();
     $received_values = Tools::getAllValues();
     foreach (array_keys($received_values) as $key_received) {
         /* Case its one of form with only switches in it */
         if (in_array($key_received, $post_keys_switchable)) {
             $is_option_active = Tools::getValue($key_received);
             $key = Tools::strtolower($key_received);
             $key = Tools::toCamelCase($key);
             if (method_exists($this, 'process' . $key)) {
                 $this->{'process' . $key}($is_option_active);
                 $has_processed_something = true;
             }
             continue;
         }
         /* Case we are on more complex forms */
         if (in_array($key_received, $post_keys_complex)) {
             // Clean key
             $key = Tools::strtolower($key_received);
             $key = Tools::toCamelCase($key, true);
             if (method_exists($this, 'process' . $key)) {
                 $this->{'process' . $key}();
                 $has_processed_something = true;
             }
         }
         /* Case Multi-lang input */
         if (strripos($key_received, 'AEUC_LABEL_DELIVERY_TIME_AVAILABLE') !== false) {
             $exploded = explode('_', $key_received);
             $count = count($exploded);
             $id_lang = (int) $exploded[$count - 1];
             $i10n_inputs_received['AEUC_LABEL_DELIVERY_TIME_AVAILABLE'][$id_lang] = $received_values[$key_received];
         }
         if (strripos($key_received, 'AEUC_LABEL_DELIVERY_TIME_OOS') !== false) {
             $exploded = explode('_', $key_received);
             $count = count($exploded);
             $id_lang = (int) $exploded[$count - 1];
             $i10n_inputs_received['AEUC_LABEL_DELIVERY_TIME_OOS'][$id_lang] = $received_values[$key_received];
         }
         if (strripos($key_received, 'AEUC_SHOPPING_CART_TEXT_BEFORE') !== false) {
             $exploded = explode('_', $key_received);
             $count = count($exploded);
             $id_lang = (int) $exploded[$count - 1];
             $i10n_inputs_received['AEUC_SHOPPING_CART_TEXT_BEFORE'][$id_lang] = $received_values[$key_received];
         }
         if (strripos($key_received, 'AEUC_SHOPPING_CART_TEXT_AFTER') !== false) {
             $exploded = explode('_', $key_received);
             $count = count($exploded);
             $id_lang = (int) $exploded[$count - 1];
             $i10n_inputs_received['AEUC_SHOPPING_CART_TEXT_AFTER'][$id_lang] = $received_values[$key_received];
         }
     }
     if (count($i10n_inputs_received) > 0) {
         $this->processAeucLabelDeliveryTime($i10n_inputs_received);
         $this->processAeucShoppingCartText($i10n_inputs_received);
         $has_processed_something = true;
     }
     if ($has_processed_something) {
         $this->emptyTemplatesCache();
         return (count($this->_errors) ? $this->displayError($this->_errors) : '') . (count($this->_warnings) ? $this->displayWarning($this->_warnings) : '') . $this->displayConfirmation($this->l('Settings saved successfully!', 'advancedeucompliance'));
     } else {
         return (count($this->_errors) ? $this->displayError($this->_errors) : '') . (count($this->_warnings) ? $this->displayWarning($this->_warnings) : '') . '';
     }
 }
Example #12
0
 function psmPPsetup($module, $name = '', $file = '')
 {
     if (is_array($module)) {
         $name = '';
         $file = $module['ppsetup'];
         $module = $module['module'];
     }
     if ($name == '' && $module->name != 'pproperties') {
         $name = $module->name;
     }
     if ($file == '') {
         $file = _PS_MODULE_DIR_ . Tools::strtolower($name != '' ? $name : $module->name) . '/ppsetup.php';
     }
     $file = str_replace('\\', '/', $file);
     $cache_id = 'psmPPsetup::' . $module->name . ':' . $name . '!' . $file;
     if (!Cache::isStored($cache_id)) {
         $classname = 'PPSetup' . ($name != '' ? Tools::toCamelCase($name, true) : '');
         if (is_file($file)) {
             require_once _PS_MODULE_DIR_ . 'pproperties/psmsetup16.php';
             if ($name != '' && $name != 'pproperties') {
                 require_once _PS_MODULE_DIR_ . 'pproperties/ppsetup.php';
             }
             require_once $file;
             $result = new $classname($module);
         } else {
             $result = false;
         }
         Cache::store($cache_id, $result);
     }
     return Cache::retrieve($cache_id);
 }
 /**
  * This method generate the form for back translations
  */
 public function initFormBack()
 {
     $name_var = $this->translations_informations[$this->type_selected]['var'];
     $GLOBALS[$name_var] = $this->fileExists();
     $missing_translations_back = array();
     // Get all types of file (PHP, TPL...) and a list of files to parse by folder
     $files_per_directory = $this->getFileToParseByTypeTranslation();
     //Parse SF2 php files
     $regexSf2Php = ['/->trans\\(([\'\\"])' . _PS_TRANS_PATTERN_ . '([\'\\"])(,\\s*?[\\[|array\\(](.*)[\\]|\\)])(,\\s*?([\'\\"])(.*)([\'\\"]))?\\)/Us', '/->transchoice\\(([\'\\"])' . _PS_TRANS_PATTERN_ . '([\'\\"])(,\\s*?(.*))(,\\s*?[\\[|array\\(](.*)[\\]|\\)])(,\\s*?([\'\\"])(.*)([\'\\"]))?\\)/Us'];
     foreach ($files_per_directory['php-sf2'] as $dir => $files) {
         foreach ($files as $file) {
             // Get content for this file
             $content = file_get_contents($dir . $file);
             if (!$content) {
                 continue;
             }
             // Parse this content
             foreach ($regexSf2Php as $reg) {
                 preg_match_all($reg, $content, $matches);
                 foreach ($matches[0] as $key => $match) {
                     $domainKey = strpos($match, 'trans(') !== false ? 8 : 10;
                     $stringToTranslate = $matches[2][$key];
                     $prefix_key = $matches[$domainKey][$key];
                     if ($prefix_key && $stringToTranslate) {
                         if (isset($GLOBALS[$name_var][$prefix_key . md5($stringToTranslate)])) {
                             $tabs_array[$prefix_key][$stringToTranslate]['trad'] = stripslashes(html_entity_decode($GLOBALS[$name_var][$prefix_key . md5($stringToTranslate)], ENT_COMPAT, 'UTF-8'));
                         } else {
                             if (!isset($tabs_array[$prefix_key][$stringToTranslate]['trad'])) {
                                 $tabs_array[$prefix_key][$stringToTranslate]['trad'] = '';
                                 if (!isset($missing_translations_back[$prefix_key])) {
                                     $missing_translations_back[$prefix_key] = 1;
                                 } else {
                                     $missing_translations_back[$prefix_key]++;
                                 }
                             }
                         }
                         $tabs_array[$prefix_key][$stringToTranslate]['use_sprintf'] = $this->checkIfKeyUseSprintf($stringToTranslate);
                     }
                 }
             }
         }
     }
     //Parse SF2/Twig files
     $regexSf2Tpl = ['/trans\\(([\'\\"])' . _PS_TRANS_PATTERN_ . '([\'\\"])(,\\s*?[\\{\\[](.*)[\\}\\]])(,\\s*?([\'\\"])(.*)([\'\\"]))?\\)/Us', '/transchoice\\(([\'\\"])' . _PS_TRANS_PATTERN_ . '([\'\\"])(,\\s*?(.*))(,\\s*?[\\{\\[](.*)[\\}\\]])(,\\s*?([\'\\"])(.*)([\'\\"]))?\\)/Us'];
     foreach ($files_per_directory['tpl-sf2'] as $file) {
         // Get content for this file
         $content = file_get_contents(_PS_ROOT_DIR_ . '/src/PrestaShopBundle/Resources/views/' . $file);
         if (!$content) {
             continue;
         }
         // Parse this content
         foreach ($regexSf2Tpl as $reg) {
             preg_match_all($reg, $content, $matches);
             foreach ($matches[0] as $key => $match) {
                 $domainKey = strpos($match, 'trans(') !== false ? 8 : 10;
                 $stringToTranslate = $matches[2][$key];
                 $prefix_key = $matches[$domainKey][$key];
                 if ($prefix_key && $stringToTranslate) {
                     if (isset($GLOBALS[$name_var][$prefix_key . md5($stringToTranslate)])) {
                         $tabs_array[$prefix_key][$stringToTranslate]['trad'] = stripslashes(html_entity_decode($GLOBALS[$name_var][$prefix_key . md5($stringToTranslate)], ENT_COMPAT, 'UTF-8'));
                     } else {
                         if (!isset($tabs_array[$prefix_key][$stringToTranslate]['trad'])) {
                             $tabs_array[$prefix_key][$stringToTranslate]['trad'] = '';
                             if (!isset($missing_translations_back[$prefix_key])) {
                                 $missing_translations_back[$prefix_key] = 1;
                             } else {
                                 $missing_translations_back[$prefix_key]++;
                             }
                         }
                     }
                     $tabs_array[$prefix_key][$stringToTranslate]['use_sprintf'] = $this->checkIfKeyUseSprintf($stringToTranslate);
                 }
             }
         }
     }
     //Parse ps PHP files
     foreach ($files_per_directory['php'] as $dir => $files) {
         foreach ($files as $file) {
             // Check if is a PHP file and if the override file exists
             if (preg_match('/^(.*)\\.php$/', $file) && Tools::file_exists_cache($file_path = $dir . $file) && !in_array($file, self::$ignore_folder)) {
                 $prefix_key = basename($file);
                 // -4 becomes -14 to remove the ending "Controller.php" from the filename
                 if (strpos($file, 'Controller.php') !== false) {
                     $prefix_key = basename(substr($file, 0, -14));
                 } elseif (strpos($file, 'Helper') !== false) {
                     $prefix_key = 'Helper';
                 }
                 if ($prefix_key == 'Admin') {
                     $prefix_key = 'AdminController';
                 }
                 if ($prefix_key == 'PaymentModule.php') {
                     $prefix_key = 'PaymentModule';
                 }
                 // Get content for this file
                 $content = file_get_contents($file_path);
                 // Parse this content
                 $matches = $this->userParseFile($content, $this->type_selected, 'php');
                 foreach ($matches as $key) {
                     // Caution ! front has underscore between prefix key and md5, back has not
                     if (isset($GLOBALS[$name_var][$prefix_key . md5($key)])) {
                         $tabs_array[$prefix_key][$key]['trad'] = stripslashes(html_entity_decode($GLOBALS[$name_var][$prefix_key . md5($key)], ENT_COMPAT, 'UTF-8'));
                     } else {
                         if (!isset($tabs_array[$prefix_key][$key]['trad'])) {
                             $tabs_array[$prefix_key][$key]['trad'] = '';
                             if (!isset($missing_translations_back[$prefix_key])) {
                                 $missing_translations_back[$prefix_key] = 1;
                             } else {
                                 $missing_translations_back[$prefix_key]++;
                             }
                         }
                     }
                     $tabs_array[$prefix_key][$key]['use_sprintf'] = $this->checkIfKeyUseSprintf($key);
                 }
             }
         }
     }
     foreach ($files_per_directory['specific'] as $dir => $files) {
         foreach ($files as $file) {
             if (Tools::file_exists_cache($file_path = $dir . $file) && !in_array($file, self::$ignore_folder)) {
                 $prefix_key = 'index';
                 // Get content for this file
                 $content = file_get_contents($file_path);
                 // Parse this content
                 $matches = $this->userParseFile($content, $this->type_selected, 'specific');
                 foreach ($matches as $key) {
                     // Caution ! front has underscore between prefix key and md5, back has not
                     if (isset($GLOBALS[$name_var][$prefix_key . md5($key)])) {
                         $tabs_array[$prefix_key][$key]['trad'] = stripslashes(html_entity_decode($GLOBALS[$name_var][$prefix_key . md5($key)], ENT_COMPAT, 'UTF-8'));
                     } else {
                         if (!isset($tabs_array[$prefix_key][$key]['trad'])) {
                             $tabs_array[$prefix_key][$key]['trad'] = '';
                             if (!isset($missing_translations_back[$prefix_key])) {
                                 $missing_translations_back[$prefix_key] = 1;
                             } else {
                                 $missing_translations_back[$prefix_key]++;
                             }
                         }
                     }
                     $tabs_array[$prefix_key][$key]['use_sprintf'] = $this->checkIfKeyUseSprintf($key);
                 }
             }
         }
     }
     foreach ($files_per_directory['tpl'] as $dir => $files) {
         foreach ($files as $file) {
             if (preg_match('/^(.*).tpl$/', $file) && Tools::file_exists_cache($file_path = $dir . $file)) {
                 // get controller name instead of file name
                 $prefix_key = Tools::toCamelCase(str_replace(_PS_ADMIN_DIR_ . DIRECTORY_SEPARATOR . 'themes', '', $file_path), true);
                 $pos = strrpos($prefix_key, DIRECTORY_SEPARATOR);
                 $tmp = substr($prefix_key, 0, $pos);
                 if (preg_match('#controllers#', $tmp)) {
                     $parent_class = explode(DIRECTORY_SEPARATOR, str_replace('/', DIRECTORY_SEPARATOR, $tmp));
                     $override = array_search('override', $parent_class);
                     if ($override !== false) {
                         // case override/controllers/admin/templates/controller_name
                         $prefix_key = 'Admin' . ucfirst($parent_class[$override + 4]);
                     } else {
                         // case admin_name/themes/theme_name/template/controllers/controller_name
                         $key = array_search('controllers', $parent_class);
                         $prefix_key = 'Admin' . ucfirst($parent_class[$key + 1]);
                     }
                 } else {
                     $prefix_key = 'Admin' . ucfirst(substr($tmp, strrpos($tmp, DIRECTORY_SEPARATOR) + 1, $pos));
                 }
                 // Adding list, form, option in Helper Translations
                 $list_prefix_key = array('AdminHelpers', 'AdminList', 'AdminView', 'AdminOptions', 'AdminForm', 'AdminCalendar', 'AdminTree', 'AdminUploader', 'AdminDataviz', 'AdminKpi', 'AdminModule_list', 'AdminModulesList');
                 if (in_array($prefix_key, $list_prefix_key)) {
                     $prefix_key = 'Helper';
                 }
                 // Adding the folder backup/download/ in AdminBackup Translations
                 if ($prefix_key == 'AdminDownload') {
                     $prefix_key = 'AdminBackup';
                 }
                 // use the prefix "AdminController" (like old php files 'header', 'footer.inc', 'index', 'login', 'password', 'functions'
                 if ($prefix_key == 'Admin' || $prefix_key == 'AdminTemplate') {
                     $prefix_key = 'AdminController';
                 }
                 $new_lang = array();
                 // Get content for this file
                 $content = file_get_contents($file_path);
                 // Parse this content
                 $matches = $this->userParseFile($content, $this->type_selected, 'tpl');
                 /* Get string translation for each tpl file */
                 foreach ($matches as $english_string) {
                     if (empty($english_string)) {
                         $this->errors[] = sprintf($this->l('There is an error in template, an empty string has been found. Please edit: "%s"'), $file_path);
                         $new_lang[$english_string] = '';
                     } else {
                         $trans_key = $prefix_key . md5($english_string);
                         if (isset($GLOBALS[$name_var][$trans_key])) {
                             $new_lang[$english_string]['trad'] = html_entity_decode($GLOBALS[$name_var][$trans_key], ENT_COMPAT, 'UTF-8');
                         } else {
                             if (!isset($new_lang[$english_string]['trad'])) {
                                 $new_lang[$english_string]['trad'] = '';
                                 if (!isset($missing_translations_back[$prefix_key])) {
                                     $missing_translations_back[$prefix_key] = 1;
                                 } else {
                                     $missing_translations_back[$prefix_key]++;
                                 }
                             }
                         }
                         $new_lang[$english_string]['use_sprintf'] = $this->checkIfKeyUseSprintf($key);
                     }
                 }
                 if (isset($tabs_array[$prefix_key])) {
                     $tabs_array[$prefix_key] = array_merge($tabs_array[$prefix_key], $new_lang);
                 } else {
                     $tabs_array[$prefix_key] = $new_lang;
                 }
             }
         }
     }
     // count will contain the number of expressions of the page
     $count = 0;
     foreach ($tabs_array as $array) {
         $count += count($array);
     }
     $this->tpl_view_vars = array_merge($this->tpl_view_vars, array('count' => $count, 'cancel_url' => $this->context->link->getAdminLink('AdminTranslations'), 'limit_warning' => $this->displayLimitPostWarning($count), 'mod_security_warning' => Tools::apacheModExists('mod_security'), 'tabsArray' => $tabs_array, 'missing_translations' => $missing_translations_back));
     $this->initToolbar();
     $this->base_tpl_view = 'translation_form.tpl';
     return parent::renderView();
 }
Example #14
0
 public function display()
 {
     $this->context->smarty->assign('display_header', $this->display_header);
     $this->context->smarty->assign('display_footer', $this->display_footer);
     // Use page title from meta_title if it has been set else from the breadcrumbs array
     if (!$this->meta_title) {
         $this->meta_title = isset($this->breadcrumbs[1]) ? $this->breadcrumbs[1] : $this->breadcrumbs[0];
     }
     $this->context->smarty->assign('meta_title', $this->meta_title);
     $tpl_action = $this->tpl_folder . $this->display . '.tpl';
     // Check if action template has been override
     foreach ($this->context->smarty->getTemplateDir() as $template_dir) {
         if (file_exists($template_dir . DIRECTORY_SEPARATOR . $tpl_action) && $this->display != 'view' && $this->display != 'options') {
             if (method_exists($this, $this->display . Tools::toCamelCase($this->className))) {
                 $this->{$this->display . Tools::toCamelCase($this->className)}();
             }
             $this->context->smarty->assign('content', $this->context->smarty->fetch($tpl_action));
             break;
         }
     }
     if (!$this->ajax) {
         $template = $this->createTemplate($this->template);
         $page = $template->fetch();
     } else {
         $page = $this->content;
     }
     if ($conf = Tools::getValue('conf')) {
         if ($this->json) {
             $this->context->smarty->assign('conf', Tools::jsonEncode($this->_conf[(int) $conf]));
         } else {
             $this->context->smarty->assign('conf', $this->_conf[(int) $conf]);
         }
     }
     if ($this->json) {
         $this->context->smarty->assign('errors', Tools::jsonEncode($this->errors));
     } else {
         $this->context->smarty->assign('errors', $this->errors);
     }
     if ($this->json) {
         $this->context->smarty->assign('warnings', Tools::jsonEncode($this->warnings));
     } else {
         $this->context->smarty->assign('warnings', $this->warnings);
     }
     if ($this->json) {
         $this->context->smarty->assign('informations', Tools::jsonEncode($this->informations));
     } else {
         $this->context->smarty->assign('informations', $this->informations);
     }
     if ($this->json) {
         $this->context->smarty->assign('confirmations', Tools::jsonEncode($this->confirmations));
     } else {
         $this->context->smarty->assign('confirmations', $this->confirmations);
     }
     if ($this->json) {
         $this->context->smarty->assign('page', Tools::jsonEncode($page));
     } else {
         $this->context->smarty->assign('page', $page);
     }
     $this->context->smarty->display($this->layout);
 }
Example #15
0
 /**
  * PROCESS : installFixtures
  * Install fixtures (E.g. demo products)
  */
 public function installFixtures($entity = null, array $data = array())
 {
     $fixtures_path = _PS_INSTALL_FIXTURES_PATH_ . 'apple/';
     $fixtures_name = 'apple';
     $zip_file = _PS_ROOT_DIR_ . '/download/fixtures.zip';
     $temp_dir = _PS_ROOT_DIR_ . '/download/fixtures/';
     // try to download fixtures if no low memory mode
     if ($entity === null) {
         if (Tools::copy('http://api.prestashop.com/fixtures/' . $data['shop_country'] . '/' . $data['shop_activity'] . '/fixtures.zip', $zip_file)) {
             Tools::deleteDirectory($temp_dir, true);
             if (Tools::ZipTest($zip_file)) {
                 if (Tools::ZipExtract($zip_file, $temp_dir)) {
                     $files = scandir($temp_dir);
                     if (count($files)) {
                         foreach ($files as $file) {
                             if (!preg_match('/^\\./', $file) && is_dir($temp_dir . $file . '/')) {
                                 $fixtures_path = $temp_dir . $file . '/';
                                 $fixtures_name = $file;
                                 break;
                             }
                         }
                     }
                 }
             }
         }
     }
     // Load class (use fixture class if one exists, or use InstallXmlLoader)
     if (file_exists($fixtures_path . '/install.php')) {
         require_once $fixtures_path . '/install.php';
         $class = 'InstallFixtures' . Tools::toCamelCase($fixtures_name);
         if (!class_exists($class, false)) {
             $this->setError($this->language->l('Fixtures class "%s" not found', $class));
             return false;
         }
         $xml_loader = new $class();
         if (!$xml_loader instanceof InstallXmlLoader) {
             $this->setError($this->language->l('"%s" must be an instane of "InstallXmlLoader"', $class));
             return false;
         }
     } else {
         $xml_loader = new InstallXmlLoader();
     }
     // Install XML data (data/xml/ folder)
     $xml_loader->setFixturesPath($fixtures_path);
     if (isset($this->xml_loader_ids) && $this->xml_loader_ids) {
         $xml_loader->setIds($this->xml_loader_ids);
     }
     $languages = array();
     foreach (Language::getLanguages(false) as $lang) {
         $languages[$lang['id_lang']] = $lang['iso_code'];
     }
     $xml_loader->setLanguages($languages);
     if ($entity) {
         $xml_loader->populateEntity($entity);
     } else {
         $xml_loader->populateFromXmlFiles();
         Tools::deleteDirectory($temp_dir, true);
         @unlink($zip_file);
     }
     if ($errors = $xml_loader->getErrors()) {
         $this->setError($errors);
         return false;
     }
     // IDS from xmlLoader are stored in order to use them for fixtures
     $this->xml_loader_ids = $xml_loader->getIds();
     unset($xml_loader);
     // Index products in search tables
     Search::indexation(true);
     return true;
 }
Example #16
0
 /**
  * Retrieve GET and POST value and translate them to actions
  */
 public function initProcess()
 {
     if (!isset($this->list_id)) {
         $this->list_id = $this->table;
     }
     // Manage list filtering
     if (Tools::isSubmit('submitFilter' . $this->list_id) || $this->context->cookie->{'submitFilter' . $this->list_id} !== false || Tools::getValue($this->list_id . 'Orderby') || Tools::getValue($this->list_id . 'Orderway')) {
         $this->filter = true;
     }
     $this->id_object = (int) Tools::getValue($this->identifier);
     /* Delete object image */
     if (isset($_GET['deleteImage'])) {
         if ($this->tabAccess['delete'] === '1') {
             $this->action = 'delete_image';
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif (isset($_GET['delete' . $this->table])) {
         if ($this->tabAccess['delete'] === '1') {
             $this->action = 'delete';
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif ((isset($_GET['status' . $this->table]) || isset($_GET['status'])) && Tools::getValue($this->identifier)) {
         if ($this->tabAccess['edit'] === '1') {
             $this->action = 'status';
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (isset($_GET['position'])) {
         if ($this->tabAccess['edit'] == '1') {
             $this->action = 'position';
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitAdd' . $this->table) || Tools::isSubmit('submitAdd' . $this->table . 'AndStay') || Tools::isSubmit('submitAdd' . $this->table . 'AndPreview') || Tools::isSubmit('submitAdd' . $this->table . 'AndBackToParent')) {
         // case 1: updating existing entry
         if ($this->id_object) {
             if ($this->tabAccess['edit'] === '1') {
                 $this->action = 'save';
                 if (Tools::isSubmit('submitAdd' . $this->table . 'AndStay')) {
                     $this->display = 'edit';
                 } else {
                     $this->display = 'list';
                 }
             } else {
                 $this->errors[] = Tools::displayError('You do not have permission to edit this.');
             }
         } else {
             if ($this->tabAccess['add'] === '1') {
                 $this->action = 'save';
                 if (Tools::isSubmit('submitAdd' . $this->table . 'AndStay')) {
                     $this->display = 'edit';
                 } else {
                     $this->display = 'list';
                 }
             } else {
                 $this->errors[] = Tools::displayError('You do not have permission to add this.');
             }
         }
     } elseif (isset($_GET['add' . $this->table])) {
         if ($this->tabAccess['add'] === '1') {
             $this->action = 'new';
             $this->display = 'add';
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to add this.');
         }
     } elseif (isset($_GET['update' . $this->table]) && isset($_GET[$this->identifier])) {
         $this->display = 'edit';
         if ($this->tabAccess['edit'] !== '1') {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (isset($_GET['view' . $this->table])) {
         if ($this->tabAccess['view'] === '1') {
             $this->display = 'view';
             $this->action = 'view';
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to view this.');
         }
     } elseif (isset($_GET['details' . $this->table])) {
         if ($this->tabAccess['view'] === '1') {
             $this->display = 'details';
             $this->action = 'details';
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to view this.');
         }
     } elseif (isset($_GET['export' . $this->table])) {
         if ($this->tabAccess['view'] === '1') {
             $this->action = 'export';
         }
     } elseif (isset($_POST['submitReset' . $this->list_id])) {
         $this->action = 'reset_filters';
     } elseif (Tools::isSubmit('submitOptions' . $this->table) || Tools::isSubmit('submitOptions')) {
         $this->display = 'options';
         if ($this->tabAccess['edit'] === '1') {
             $this->action = 'update_options';
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::getValue('action') && method_exists($this, 'process' . ucfirst(Tools::toCamelCase(Tools::getValue('action'))))) {
         $this->action = Tools::getValue('action');
     } elseif (Tools::isSubmit('submitFields') && $this->required_database && $this->tabAccess['add'] === '1' && $this->tabAccess['delete'] === '1') {
         $this->action = 'update_fields';
     } elseif (is_array($this->bulk_actions)) {
         $submit_bulk_actions = array_merge(array('enableSelection' => array('text' => $this->l('Enable selection'), 'icon' => 'icon-power-off text-success'), 'disableSelection' => array('text' => $this->l('Disable selection'), 'icon' => 'icon-power-off text-danger')), $this->bulk_actions);
         foreach ($submit_bulk_actions as $bulk_action => $params) {
             if (Tools::isSubmit('submitBulk' . $bulk_action . $this->table) || Tools::isSubmit('submitBulk' . $bulk_action)) {
                 if ($bulk_action === 'delete') {
                     if ($this->tabAccess['delete'] === '1') {
                         $this->action = 'bulk' . $bulk_action;
                         $this->boxes = Tools::getValue($this->table . 'Box');
                         if (empty($this->boxes) && $this->table == 'attribute') {
                             $this->boxes = Tools::getValue($this->table . '_valuesBox');
                         }
                     } else {
                         $this->errors[] = Tools::displayError('You do not have permission to delete this.');
                     }
                     break;
                 } elseif ($this->tabAccess['edit'] === '1') {
                     $this->action = 'bulk' . $bulk_action;
                     $this->boxes = Tools::getValue($this->table . 'Box');
                 } else {
                     $this->errors[] = Tools::displayError('You do not have permission to edit this.');
                 }
                 break;
             } elseif (Tools::isSubmit('submitBulk')) {
                 if ($bulk_action === 'delete') {
                     if ($this->tabAccess['delete'] === '1') {
                         $this->action = 'bulk' . $bulk_action;
                         $this->boxes = Tools::getValue($this->table . 'Box');
                     } else {
                         $this->errors[] = Tools::displayError('You do not have permission to delete this.');
                     }
                     break;
                 } elseif ($this->tabAccess['edit'] === '1') {
                     $this->action = 'bulk' . Tools::getValue('select_submitBulk');
                     $this->boxes = Tools::getValue($this->table . 'Box');
                 } else {
                     $this->errors[] = Tools::displayError('You do not have permission to edit this.');
                 }
                 break;
             }
         }
     } elseif (!empty($this->fields_options) && empty($this->fields_list)) {
         $this->display = 'options';
     }
 }
Example #17
0
 if (!$adminObj->ignore_sleep && Tools::apacheModExists('evasive')) {
     sleep(1);
 }
 if ($adminObj->checkToken()) {
     // the differences with index.php is here
     $adminObj->ajaxPreProcess();
     $action = Tools::getValue('action');
     // no need to use displayConf() here
     if (!empty($action) and method_exists($adminObj, 'ajaxProcess' . Tools::toCamelCase($action))) {
         $adminObj->{'ajaxProcess' . Tools::toCamelCase($action)}();
     } else {
         $adminObj->ajaxProcess();
     }
     // @TODO We should use a displayAjaxError
     $adminObj->displayErrors();
     if (!empty($action) and method_exists($adminObj, 'displayAjax' . Tools::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();
     // ${1} in the replacement string of the regexp is required, because the token may begin with a number and mix up with it (e.g. $17)
     $url = preg_replace('/([&?]token=)[^&]*(&.*)?$/', '${1}' . $adminObj->token . '$2', $_SERVER['REQUEST_URI']);
     if (false === strpos($url, '?token=') and false === strpos($url, '&token=')) {
         $url .= '&token=' . $adminObj->token;
     }
     // we can display the correct url
     // die(Tools::jsonEncode(array(translate('Invalid security token'),$url)));
     die(Tools::jsonEncode(translate('Invalid security token')));
Example #18
0
 public function run()
 {
     $this->init();
     $this->_memory['init'] = memory_get_usage();
     $this->_time['init'] = microtime(true);
     if ($this->checkAccess()) {
         $this->_memory['checkAccess'] = memory_get_usage();
         $this->_time['checkAccess'] = microtime(true);
         if (!$this->content_only && ($this->display_header || isset($this->className) && $this->className)) {
             $this->setMedia();
         }
         $this->_memory['setMedia'] = memory_get_usage();
         $this->_time['setMedia'] = microtime(true);
         // postProcess handles ajaxProcess
         $this->postProcess();
         $this->_memory['postProcess'] = memory_get_usage();
         $this->_time['postProcess'] = microtime(true);
         if (!empty($this->redirect_after)) {
             $this->redirect();
         }
         if (!$this->content_only && ($this->display_header || isset($this->className) && $this->className)) {
             $this->initHeader();
         }
         $this->_memory['initHeader'] = memory_get_usage();
         $this->_time['initHeader'] = microtime(true);
         $this->initContent();
         $this->_memory['initContent'] = memory_get_usage();
         $this->_time['initContent'] = microtime(true);
         if (!$this->content_only && ($this->display_footer || isset($this->className) && $this->className)) {
             $this->initFooter();
         }
         $this->_memory['initFooter'] = memory_get_usage();
         $this->_time['initFooter'] = microtime(true);
         // default behavior for ajax process is to use $_POST[action] or $_GET[action]
         // then using displayAjax[action]
         if ($this->ajax) {
             $action = Tools::getValue('action');
             if (!empty($action) && method_exists($this, 'displayAjax' . Tools::toCamelCase($action))) {
                 $this->{'displayAjax' . $action}();
             } elseif (method_exists($this, 'displayAjax')) {
                 $this->displayAjax();
             }
         } else {
             $this->displayDebug();
         }
     } else {
         $this->initCursedPage();
         $this->displayDebug();
     }
 }
Example #19
0
 /**
  * Get definition of an association
  *
  * @param string $association
  * @return array
  */
 protected function getDefinition($association)
 {
     if (!$association) {
         return $this->definition;
     }
     if (!isset($this->association_definition[$association])) {
         $definition = $this->definition;
         $split = explode('.', $association);
         $is_lang = false;
         for ($i = 0, $total_association = count($split); $i < $total_association; $i++) {
             $asso = $split[$i];
             // Check is current association exists in current definition
             if (!isset($definition['associations'][$asso])) {
                 throw new PrestaShopException('Association ' . $asso . ' not found for class ' . $this->definition['classname']);
             }
             $current_def = $definition['associations'][$asso];
             // Special case for lang alias
             if ($asso == self::LANG_ALIAS) {
                 $is_lang = true;
                 break;
             }
             $classname = isset($current_def['object']) ? $current_def['object'] : Tools::toCamelCase($asso, true);
             $definition = ObjectModel::getDefinition($classname);
         }
         // Get definition of associated entity and add information on current association
         $current_def['name'] = $asso;
         if (!isset($current_def['object'])) {
             $current_def['object'] = Tools::toCamelCase($asso, true);
         }
         if (!isset($current_def['field'])) {
             $current_def['field'] = 'id_' . $asso;
         }
         if (!isset($current_def['foreign_field'])) {
             $current_def['foreign_field'] = 'id_' . $asso;
         }
         if ($total_association > 1) {
             unset($split[$total_association - 1]);
             $current_def['complete_field'] = implode('.', $split) . '.' . $current_def['field'];
         } else {
             $current_def['complete_field'] = $current_def['field'];
         }
         $current_def['complete_foreign_field'] = $association . '.' . $current_def['field'];
         $definition['is_lang'] = $is_lang;
         $definition['asso'] = $current_def;
         $this->association_definition[$association] = $definition;
     } else {
         $definition = $this->association_definition[$association];
     }
     return $definition;
 }
Example #20
0
 public function generateEntityContent($entity)
 {
     $xml = $this->loadEntity($entity);
     if (method_exists($this, 'getEntityContents' . Tools::toCamelCase($entity))) {
         $content = $this->{'getEntityContents' . Tools::toCamelCase($entity)}($entity);
     } else {
         $content = $this->getEntityContents($entity);
     }
     unset($xml->entities);
     $entities = $xml->addChild('entities');
     $this->createXmlEntityNodes($entity, $content['nodes'], $entities);
     $xml->asXML($this->data_path . $entity . '.xml');
     // Generate multilang XML files
     if ($content['nodes_lang']) {
         foreach ($content['nodes_lang'] as $id_lang => $nodes) {
             if (!isset($this->languages[$id_lang])) {
                 continue;
             }
             $iso = $this->languages[$id_lang];
             if (!is_dir($this->lang_path . $this->getFallBackToDefaultLanguage($iso) . '/data')) {
                 mkdir($this->lang_path . $this->getFallBackToDefaultLanguage($iso) . '/data');
             }
             $xml_node = new InstallSimplexmlElement('<entity_' . $entity . ' />');
             $this->createXmlEntityNodes($entity, $nodes, $xml_node);
             $xml_node->asXML($this->lang_path . $this->getFallBackToDefaultLanguage($iso) . '/data/' . $entity . '.xml');
         }
     }
     if ($xml->fields['image']) {
         if (method_exists($this, 'backupImage' . Tools::toCamelCase($entity))) {
             $this->{'backupImage' . Tools::toCamelCase($entity)}((string) $xml->fields['image']);
         } else {
             $this->backupImage($entity, (string) $xml->fields['image']);
         }
     }
 }
 /**
  * This method generate the form for back translations
  */
 public function initFormBack()
 {
     $name_var = $this->translations_informations[$this->type_selected]['var'];
     $GLOBALS[$name_var] = $this->fileExists();
     $missing_translations_back = array();
     // Get all types of file (PHP, TPL...) and a list of files to parse by folder
     $files_per_directory = $this->getFileToParseByTypeTranslation();
     foreach ($files_per_directory['php'] as $dir => $files) {
         foreach ($files as $file) {
             // Check if is a PHP file and if the override file exists
             if (preg_match('/^(.*)\\.php$/', $file) && Tools::file_exists_cache($file_path = $dir . $file) && !in_array($file, self::$ignore_folder)) {
                 $prefix_key = basename($file);
                 // -4 becomes -14 to remove the ending "Controller.php" from the filename
                 if (strpos($file, 'Controller.php') !== false) {
                     $prefix_key = basename(substr($file, 0, -14));
                 } else {
                     if (strpos($file, 'Helper') !== false) {
                         $prefix_key = 'Helper';
                     }
                 }
                 if ($prefix_key == 'Admin') {
                     $prefix_key = 'AdminController';
                 }
                 if ($prefix_key == 'PaymentModule.php') {
                     $prefix_key = 'PaymentModule';
                 }
                 // Get content for this file
                 $content = file_get_contents($file_path);
                 // Parse this content
                 $matches = $this->userParseFile($content, $this->type_selected, 'php');
                 foreach ($matches as $key) {
                     // Caution ! front has underscore between prefix key and md5, back has not
                     if (isset($GLOBALS[$name_var][$prefix_key . md5($key)])) {
                         $tabs_array[$prefix_key][$key]['trad'] = stripslashes(html_entity_decode($GLOBALS[$name_var][$prefix_key . md5($key)], ENT_COMPAT, 'UTF-8'));
                     } else {
                         if (!isset($tabs_array[$prefix_key][$key]['trad'])) {
                             $tabs_array[$prefix_key][$key]['trad'] = '';
                             if (!isset($missing_translations_back[$prefix_key])) {
                                 $missing_translations_back[$prefix_key] = 1;
                             } else {
                                 $missing_translations_back[$prefix_key]++;
                             }
                         }
                     }
                     $tabs_array[$prefix_key][$key]['use_sprintf'] = $this->checkIfKeyUseSprintf($key);
                 }
             }
         }
     }
     foreach ($files_per_directory['specific'] as $dir => $files) {
         foreach ($files as $file) {
             if (Tools::file_exists_cache($file_path = $dir . $file) && !in_array($file, self::$ignore_folder)) {
                 $prefix_key = 'index';
                 // Get content for this file
                 $content = file_get_contents($file_path);
                 // Parse this content
                 $matches = $this->userParseFile($content, $this->type_selected, 'specific');
                 foreach ($matches as $key) {
                     // Caution ! front has underscore between prefix key and md5, back has not
                     if (isset($GLOBALS[$name_var][$prefix_key . md5($key)])) {
                         $tabs_array[$prefix_key][$key]['trad'] = stripslashes(html_entity_decode($GLOBALS[$name_var][$prefix_key . md5($key)], ENT_COMPAT, 'UTF-8'));
                     } else {
                         if (!isset($tabs_array[$prefix_key][$key]['trad'])) {
                             $tabs_array[$prefix_key][$key]['trad'] = '';
                             if (!isset($missing_translations_back[$prefix_key])) {
                                 $missing_translations_back[$prefix_key] = 1;
                             } else {
                                 $missing_translations_back[$prefix_key]++;
                             }
                         }
                     }
                     $tabs_array[$prefix_key][$key]['use_sprintf'] = $this->checkIfKeyUseSprintf($key);
                 }
             }
         }
     }
     foreach ($files_per_directory['tpl'] as $dir => $files) {
         foreach ($files as $file) {
             if (preg_match('/^(.*).tpl$/', $file) && Tools::file_exists_cache($file_path = $dir . $file)) {
                 // get controller name instead of file name
                 $prefix_key = Tools::toCamelCase(str_replace(_PS_ADMIN_DIR_ . '/themes', '', $file_path), true);
                 $pos = strrpos($prefix_key, DIRECTORY_SEPARATOR);
                 $tmp = substr($prefix_key, 0, $pos);
                 if (preg_match('#controllers#', $tmp)) {
                     $parent_class = explode(DIRECTORY_SEPARATOR, $tmp);
                     $key = array_search('controllers', $parent_class);
                     $prefix_key = 'Admin' . ucfirst($parent_class[$key + 1]);
                 } else {
                     $prefix_key = 'Admin' . ucfirst(substr($tmp, strrpos($tmp, DIRECTORY_SEPARATOR) + 1, $pos));
                 }
                 // Adding list, form, option in Helper Translations
                 $list_prefix_key = array('AdminHelpers', 'AdminList', 'AdminView', 'AdminOptions', 'AdminForm', 'AdminHelpAccess');
                 if (in_array($prefix_key, $list_prefix_key)) {
                     $prefix_key = 'Helper';
                 }
                 // Adding the folder backup/download/ in AdminBackup Translations
                 if ($prefix_key == 'AdminDownload') {
                     $prefix_key = 'AdminBackup';
                 }
                 // use the prefix "AdminController" (like old php files 'header', 'footer.inc', 'index', 'login', 'password', 'functions'
                 if ($prefix_key == 'Admin' || $prefix_key == 'AdminTemplate') {
                     $prefix_key = 'AdminController';
                 }
                 $new_lang = array();
                 // Get content for this file
                 $content = file_get_contents($file_path);
                 // Parse this content
                 $matches = $this->userParseFile($content, $this->type_selected, 'tpl');
                 /* Get string translation for each tpl file */
                 foreach ($matches as $english_string) {
                     if (empty($english_string)) {
                         $this->errors[] = sprintf($this->l('Error in template - Empty string found, please edit: "%s"'), $file_path);
                         $new_lang[$english_string] = '';
                     } else {
                         $trans_key = $prefix_key . md5($english_string);
                         if (isset($GLOBALS[$name_var][$trans_key])) {
                             $new_lang[$english_string]['trad'] = html_entity_decode($GLOBALS[$name_var][$trans_key], ENT_COMPAT, 'UTF-8');
                         } else {
                             if (!isset($new_lang[$english_string]['trad'])) {
                                 $new_lang[$english_string]['trad'] = '';
                                 if (!isset($missing_translations_back[$prefix_key])) {
                                     $missing_translations_back[$prefix_key] = 1;
                                 } else {
                                     $missing_translations_back[$prefix_key]++;
                                 }
                             }
                         }
                         $new_lang[$english_string]['use_sprintf'] = $this->checkIfKeyUseSprintf($key);
                     }
                 }
                 if (isset($tabs_array[$prefix_key])) {
                     $tabs_array[$prefix_key] = array_merge($tabs_array[$prefix_key], $new_lang);
                 } else {
                     $tabs_array[$prefix_key] = $new_lang;
                 }
             }
         }
     }
     // count will contain the number of expressions of the page
     $count = 0;
     foreach ($tabs_array as $array) {
         $count += count($array);
     }
     $this->tpl_view_vars = array_merge($this->tpl_view_vars, array('count' => $count, 'limit_warning' => $this->displayLimitPostWarning($count), 'tabsArray' => $tabs_array, 'missing_translations' => $missing_translations_back));
     // Add js variables needed for autotranslate
     //$this->tpl_view_vars = array_merge($this->tpl_view_vars, $this->initAutoTranslate());
     $this->initToolbar();
     $this->base_tpl_view = 'translation_form.tpl';
     return parent::renderView();
 }
 /**
  * Start controller process (this method shouldn't be overriden !)
  */
 public function run()
 {
     $this->init();
     if ($this->checkAccess()) {
         // setMedia MUST be called before postProcess
         if (!$this->content_only && ($this->display_header || isset($this->className) && $this->className)) {
             $this->setMedia();
         }
         // postProcess handles ajaxProcess
         $this->postProcess();
         if (!empty($this->redirect_after)) {
             $this->redirect();
         }
         if (!$this->content_only && ($this->display_header || isset($this->className) && $this->className)) {
             $this->initHeader();
         }
         if ($this->viewAccess()) {
             $this->initContent();
         } else {
             $this->errors[] = Tools::displayError('Access denied.');
         }
         if (!$this->content_only && ($this->display_footer || isset($this->className) && $this->className)) {
             $this->initFooter();
         }
         // default behavior for ajax process is to use $_POST[action] or $_GET[action]
         // then using displayAjax[action]
         if ($this->ajax) {
             $action = Tools::toCamelCase(Tools::getValue('action'), true);
             if (!empty($action) && method_exists($this, 'displayAjax' . $action)) {
                 $this->{'displayAjax' . $action}();
             } elseif (method_exists($this, 'displayAjax')) {
                 $this->displayAjax();
             }
         } else {
             $this->display();
         }
     } else {
         $this->initCursedPage();
         $this->smartyOutputContent($this->layout);
     }
 }
Example #23
0
 /**
  * PROCESS : installFixtures
  * Install fixtures (E.g. demo products)
  */
 public function installFixtures($entity = null)
 {
     // Load class (use fixture class if one exists, or use InstallXmlLoader)
     if (file_exists(_PS_INSTALL_FIXTURES_PATH_ . 'apple/install.php')) {
         require_once _PS_INSTALL_FIXTURES_PATH_ . 'apple/install.php';
         $class = 'InstallFixtures' . Tools::toCamelCase('apple');
         if (!class_exists($class, false)) {
             $this->setError($this->language->l('Fixtures class "%s" not found', $class));
             return false;
         }
         $xml_loader = new $class();
         if (!$xml_loader instanceof InstallXmlLoader) {
             $this->setError($this->language->l('"%s" must be an instane of "InstallXmlLoader"', $class));
             return false;
         }
     } else {
         $xml_loader = new InstallXmlLoader();
     }
     // Install XML data (data/xml/ folder)
     $xml_loader->setFixturesPath();
     if (isset($this->xml_loader_ids) && $this->xml_loader_ids) {
         $xml_loader->setIds($this->xml_loader_ids);
     }
     $languages = array();
     foreach (Language::getLanguages(false) as $lang) {
         $languages[$lang['id_lang']] = $lang['iso_code'];
     }
     $xml_loader->setLanguages($languages);
     if ($entity) {
         $xml_loader->populateEntity($entity);
     } else {
         $xml_loader->populateFromXmlFiles();
     }
     if ($errors = $xml_loader->getErrors()) {
         $this->setError($errors);
         return false;
     }
     // IDS from xmlLoader are stored in order to use them for fixtures
     $this->xml_loader_ids = $xml_loader->getIds();
     unset($xml_loader);
     // Index products in search tables
     Search::indexation(true);
     return true;
 }
Example #24
0
 public static function getPlugin($name, $base = null)
 {
     $cache_id = 'psm.plugin:' . $name . '!' . $base;
     if (!Cache::isStored($cache_id)) {
         if ($base == null && !Module::isEnabled($name)) {
             Cache::store($cache_id, false);
         } else {
             $classname = Tools::toCamelCase($name, true) . 'Plugin';
             $basedir = $base == null ? $name : $base . '/plugins/' . Tools::strtolower($name);
             $file = _PS_MODULE_DIR_ . $basedir . '/' . $classname . '.php';
             $file = self::normalizePath($file);
             if (is_file($file)) {
                 require_once $file;
                 Cache::store($cache_id, new $classname());
             } else {
                 Cache::store($cache_id, false);
             }
         }
     }
     return Cache::retrieve($cache_id);
 }
Example #25
0
 /**
  * PROCESS : installFixtures
  * Install fixtures (E.g. demo products)
  */
 public function installFixtures($entity = null, array $data = array())
 {
     $fixtures_path = _PS_INSTALL_FIXTURES_PATH_ . 'fashion/';
     $fixtures_name = 'fashion';
     $zip_file = _PS_ROOT_DIR_ . '/download/fixtures.zip';
     $temp_dir = _PS_ROOT_DIR_ . '/download/fixtures/';
     // Load class (use fixture class if one exists, or use InstallXmlLoader)
     if (file_exists($fixtures_path . '/install.php')) {
         require_once $fixtures_path . '/install.php';
         $class = 'InstallFixtures' . Tools::toCamelCase($fixtures_name);
         if (!class_exists($class, false)) {
             $this->setError($this->translator->trans('Fixtures class "%class%" not found', array('%class%' => $class), 'Install'));
             return false;
         }
         $xml_loader = new $class();
         if (!$xml_loader instanceof InstallXmlLoader) {
             $this->setError($this->translator->trans('"%class%" must be an instance of "InstallXmlLoader"', array('%class%' => $class), 'Install'));
             return false;
         }
     } else {
         $xml_loader = new InstallXmlLoader();
     }
     // Install XML data (data/xml/ folder)
     $xml_loader->setFixturesPath($fixtures_path);
     if (isset($this->xml_loader_ids) && $this->xml_loader_ids) {
         $xml_loader->setIds($this->xml_loader_ids);
     }
     $languages = array();
     foreach (Language::getLanguages(false) as $lang) {
         $languages[$lang['id_lang']] = $lang['iso_code'];
     }
     $xml_loader->setLanguages($languages);
     if ($entity) {
         $xml_loader->populateEntity($entity);
     } else {
         $xml_loader->populateFromXmlFiles();
         Tools::deleteDirectory($temp_dir, true);
         @unlink($zip_file);
     }
     if ($errors = $xml_loader->getErrors()) {
         $this->setError($errors);
         return false;
     }
     // IDS from xmlLoader are stored in order to use them for fixtures
     $this->xml_loader_ids = $xml_loader->getIds();
     unset($xml_loader);
     // Index products in search tables
     Search::indexation(true);
     return true;
 }