PageRenderTime 47ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/controllers/admin/AdminTranslationsController.php

https://github.com/netplayer/PrestaShop
PHP | 2982 lines | 2161 code | 337 blank | 484 comment | 421 complexity | 2e4c7f0d4f672698bd19e63fa00d61ce MD5 | raw file
Possible License(s): CC-BY-SA-3.0, LGPL-2.1, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /*
  3. * 2007-2014 PrestaShop
  4. *
  5. * NOTICE OF LICENSE
  6. *
  7. * This source file is subject to the Open Software License (OSL 3.0)
  8. * that is bundled with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://opensource.org/licenses/osl-3.0.php
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@prestashop.com so we can send you a copy immediately.
  14. *
  15. * DISCLAIMER
  16. *
  17. * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
  18. * versions in the future. If you wish to customize PrestaShop for your
  19. * needs please refer to http://www.prestashop.com for more information.
  20. *
  21. * @author PrestaShop SA <contact@prestashop.com>
  22. * @copyright 2007-2014 PrestaShop SA
  23. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  24. * International Registered Trademark & Property of PrestaShop SA
  25. */
  26. class AdminTranslationsControllerCore extends AdminController
  27. {
  28. /** Name of theme by default */
  29. const DEFAULT_THEME_NAME = _PS_DEFAULT_THEME_NAME_;
  30. const TEXTAREA_SIZED = 70;
  31. /** @var string : Link which list all pack of language */
  32. protected $link_lang_pack = 'http://www.prestashop.com/download/lang_packs/get_each_language_pack.php';
  33. /** @var int : number of sentence which can be translated */
  34. protected $total_expression = 0;
  35. /** @var int : number of sentence which aren't translated */
  36. protected $missing_translations = 0;
  37. /** @var array : List of ISO code for all languages */
  38. protected $all_iso_lang = array();
  39. /** @var array */
  40. protected $modules_translations = array();
  41. /** @var array : List of folder which must be ignored */
  42. protected static $ignore_folder = array('.', '..', '.svn', '.git', '.htaccess', 'index.php');
  43. /** @var array : List of theme by translation type : FRONT, BACK, ERRORS... */
  44. protected $translations_informations = array();
  45. /** @var array : List of all languages */
  46. protected $languages;
  47. /** @var array : List of all themes */
  48. protected $themes;
  49. /** @var string : Directory of selected theme */
  50. protected $theme_selected;
  51. /** @var string : Name of translations type */
  52. protected $type_selected;
  53. /** @var Language object : Language for the selected language */
  54. protected $lang_selected;
  55. /** @var boolean : Is true if number of var exceed the suhosin request or post limit */
  56. protected $post_limit_exceed = false;
  57. public function __construct()
  58. {
  59. $this->bootstrap = true;
  60. $this->multishop_context = Shop::CONTEXT_ALL;
  61. $this->table = 'translations';
  62. parent::__construct();
  63. }
  64. /*
  65. * Set the type which is selected
  66. */
  67. public function setTypeSelected($type_selected)
  68. {
  69. $this->type_selected = $type_selected;
  70. }
  71. /**
  72. * AdminController::initContent() override
  73. * @see AdminController::initContent()
  74. */
  75. public function initContent()
  76. {
  77. $this->initTabModuleList();
  78. $this->initPageHeaderToolbar();
  79. if (!is_null($this->type_selected))
  80. {
  81. $method_name = 'initForm'.$this->type_selected;
  82. if (method_exists($this, $method_name))
  83. $this->content = $this->initForm($method_name);
  84. else
  85. {
  86. $this->errors[] = sprintf(Tools::displayError('"%s" does not exist.'), $this->type_selected);
  87. $this->content = $this->initMain();
  88. }
  89. }
  90. else
  91. $this->content = $this->initMain();
  92. $this->context->smarty->assign(array(
  93. 'content' => $this->content,
  94. 'show_page_header_toolbar' => $this->show_page_header_toolbar,
  95. 'page_header_toolbar_title' => $this->page_header_toolbar_title,
  96. 'page_header_toolbar_btn' => $this->page_header_toolbar_btn));
  97. }
  98. /**
  99. * This function create vars by default and call the good method for generate form
  100. *
  101. * @param $method_name
  102. * @return call the method $this->method_name()
  103. */
  104. public function initForm($method_name)
  105. {
  106. // Create a title for each translation page
  107. $title = sprintf(
  108. $this->l('%1$s (Language: %2$s, Theme: %3$s)'),
  109. $this->translations_informations[$this->type_selected]['name'],
  110. $this->lang_selected->name,
  111. $this->theme_selected ? $this->theme_selected : $this->l('none')
  112. );
  113. // Set vars for all forms
  114. $this->tpl_view_vars = array(
  115. 'lang' => $this->lang_selected->iso_code,
  116. 'title' => $title,
  117. 'type' => $this->type_selected,
  118. 'theme' => $this->theme_selected,
  119. 'post_limit_exceeded' => $this->post_limit_exceed,
  120. 'url_submit' => self::$currentIndex.'&submitTranslations'.ucfirst($this->type_selected).'=1&token='.$this->token,
  121. 'toggle_button' => $this->displayToggleButton(),
  122. 'textarea_sized' => AdminTranslationsControllerCore::TEXTAREA_SIZED
  123. );
  124. // Call method initForm for a type
  125. return $this->{$method_name}();
  126. }
  127. /**
  128. * AdminController::initToolbar() override
  129. * @see AdminController::initToolbar()
  130. */
  131. public function initToolbar()
  132. {
  133. $this->toolbar_btn['save-and-stay'] = array(
  134. 'short' => 'SaveAndStay',
  135. 'href' => '#',
  136. 'desc' => $this->l('Save and stay'),
  137. );
  138. $this->toolbar_btn['save'] = array(
  139. 'href' => '#',
  140. 'desc' => $this->l('Update translations')
  141. );
  142. $this->toolbar_btn['cancel'] = array(
  143. 'href' => self::$currentIndex.'&token='.$this->token,
  144. 'desc' => $this->l('Cancel')
  145. );
  146. }
  147. /**
  148. * Generate the Main page
  149. */
  150. public function initMain()
  151. {
  152. // Block add/update a language
  153. $packs_to_install = array();
  154. $packs_to_update = array();
  155. $token = Tools::getAdminToken('AdminLanguages'.(int)Tab::getIdFromClassName('AdminLanguages').(int)$this->context->employee->id);
  156. $file_name = $this->link_lang_pack.'?version='._PS_VERSION_;
  157. $array_stream_context = @stream_context_create(array('http' => array('method' => 'GET', 'timeout' => 8)));
  158. if ($lang_packs = Tools::file_get_contents($file_name, false, $array_stream_context))
  159. // Notice : for php < 5.2 compatibility, Tools::jsonDecode. The second parameter to true will set us
  160. if ($lang_packs != '' && $lang_packs = Tools::jsonDecode($lang_packs, true))
  161. foreach ($lang_packs as $key => $lang_pack)
  162. {
  163. if (!Language::isInstalled($lang_pack['iso_code']))
  164. $packs_to_install[$key] = $lang_pack;
  165. else
  166. $packs_to_update[$key] = $lang_pack;
  167. }
  168. $this->tpl_view_vars = array(
  169. 'theme_default' => self::DEFAULT_THEME_NAME,
  170. 'theme_lang_dir' =>_THEME_LANG_DIR_,
  171. 'token' => $this->token,
  172. 'languages' => $this->languages,
  173. 'translations_type' => $this->translations_informations,
  174. 'packs_to_install' => $packs_to_install,
  175. 'packs_to_update' => $packs_to_update,
  176. 'url_submit' => self::$currentIndex.'&token='.$this->token,
  177. 'themes' => $this->themes,
  178. 'id_theme_current' => $this->context->shop->id_theme,
  179. 'url_create_language' => 'index.php?controller=AdminLanguages&addlang&token='.$token,
  180. );
  181. $this->toolbar_scroll = false;
  182. $this->base_tpl_view = 'main.tpl';
  183. $this->content .= $this->renderKpis();
  184. $this->content .= parent::renderView();
  185. return $this->content;
  186. }
  187. /**
  188. * This method merge each arrays of modules translation in the array of modules translations
  189. */
  190. protected function getModuleTranslations()
  191. {
  192. global $_MODULE;
  193. $name_var = $this->translations_informations[$this->type_selected]['var'];
  194. if (!isset($_MODULE) && !isset($GLOBALS[$name_var]))
  195. $GLOBALS[$name_var] = array();
  196. else if (isset($_MODULE))
  197. if (is_array($GLOBALS[$name_var]) && is_array($_MODULE))
  198. $GLOBALS[$name_var] = array_merge($GLOBALS[$name_var], $_MODULE);
  199. else
  200. $GLOBALS[$name_var] = $_MODULE;
  201. }
  202. /**
  203. * This method is only used by AdminTranslations::submitCopyLang().
  204. *
  205. * It try to create folder in new theme.
  206. *
  207. * When a translation file is copied for a module, its translation key is wrong.
  208. * We have to change the translation key and rewrite the file.
  209. *
  210. * @param string $dest file name
  211. * @return bool
  212. */
  213. protected function checkDirAndCreate($dest)
  214. {
  215. $bool = true;
  216. // To get only folder path
  217. $path = dirname($dest);
  218. // If folder wasn't already added
  219. // Do not use Tools::file_exists_cache because it changes over time!
  220. if (!file_exists($path))
  221. if (!mkdir($path, 0777, true))
  222. {
  223. $bool &= false;
  224. $this->errors[] = sprintf($this->l('Cannot create the folder "%s". Please check your directory writing permissions.'), $path);
  225. }
  226. return $bool;
  227. }
  228. /**
  229. * Read the Post var and write the translation file.
  230. * This method overwrites the old translation file.
  231. *
  232. * @param bool $override_file : set true if this file is a override
  233. */
  234. protected function writeTranslationFile($override_file = false)
  235. {
  236. $type = Tools::toCamelCase($this->type_selected, true);
  237. $translation_informations = $this->translations_informations[$this->type_selected];
  238. if ($override_file)
  239. $file_path = $translation_informations['override']['dir'].$translation_informations['override']['file'];
  240. else
  241. $file_path = $translation_informations['dir'].$translation_informations['file'];
  242. if (!file_exists($file_path))
  243. {
  244. if (!file_exists(dirname($file_path)) && !mkdir(dirname($file_path), 0777, true))
  245. throw new PrestaShopException(sprintf(Tools::displayError('Directory "%s" cannot be created'), dirname($file_path)));
  246. elseif (!touch($file_path))
  247. throw new PrestaShopException(sprintf(Tools::displayError('File "%s" cannot be created'), $file_path));
  248. }
  249. $thm_name = str_replace('.', '', Tools::getValue('theme'));
  250. $kpi_key = substr(strtoupper($thm_name.'_'.Tools::getValue('lang')), 0, 16);
  251. if ($fd = fopen($file_path, 'w'))
  252. {
  253. // Get value of button save and stay
  254. $save_and_stay = Tools::isSubmit('submitTranslations'.$type.'AndStay');
  255. // Get language
  256. $lang = strtolower(Tools::getValue('lang'));
  257. // Unset all POST which are not translations
  258. unset(
  259. $_POST['submitTranslations'.$type],
  260. $_POST['submitTranslations'.$type.'AndStay'],
  261. $_POST['lang'],
  262. $_POST['token'],
  263. $_POST['theme'],
  264. $_POST['type']
  265. );
  266. // Get all POST which aren't empty
  267. $to_insert = array();
  268. foreach ($_POST as $key => $value)
  269. if (!empty($value))
  270. $to_insert[$key] = $value;
  271. ConfigurationKPI::updateValue('FRONTOFFICE_TRANSLATIONS_EXPIRE', time());
  272. ConfigurationKPI::updateValue('TRANSLATE_TOTAL_'.$kpi_key, count($_POST));
  273. ConfigurationKPI::updateValue('TRANSLATE_DONE_'.$kpi_key, count($to_insert));
  274. // translations array is ordered by key (easy merge)
  275. ksort($to_insert);
  276. $tab = $translation_informations['var'];
  277. fwrite($fd, "<?php\n\nglobal \$".$tab.";\n\$".$tab." = array();\n");
  278. foreach ($to_insert as $key => $value)
  279. fwrite($fd, '$'.$tab.'[\''.pSQL($key, true).'\'] = \''.pSQL($value, true).'\';'."\n");
  280. fwrite($fd, "\n?>");
  281. fclose($fd);
  282. // Redirect
  283. if ($save_and_stay)
  284. $this->redirect(true);
  285. else
  286. $this->redirect();
  287. }
  288. else
  289. throw new PrestaShopException(sprintf(Tools::displayError('Cannot write this file: "%s"'), $file_path));
  290. }
  291. public function submitCopyLang()
  292. {
  293. if (!($from_lang = Tools::getValue('fromLang')) || !($to_lang = Tools::getValue('toLang')))
  294. $this->errors[] = $this->l('You must select two languages in order to copy data from one to another.');
  295. else if (!($from_theme = Tools::getValue('fromTheme')) || !($to_theme = Tools::getValue('toTheme')))
  296. $this->errors[] = $this->l('You must select two themes in order to copy data from one to another.');
  297. else if (!Language::copyLanguageData(Language::getIdByIso($from_lang), Language::getIdByIso($to_lang)))
  298. $this->errors[] = $this->l('An error occurred while copying data.');
  299. else if ($from_lang == $to_lang && $from_theme == $to_theme)
  300. $this->errors[] = $this->l('There is nothing to copy (same language and theme).');
  301. else
  302. {
  303. $theme_exists = array('from_theme' => false, 'to_theme' => false);
  304. foreach ($this->themes as $theme)
  305. {
  306. if ($theme->directory == $from_theme)
  307. $theme_exists['from_theme'] = true;
  308. if ($theme->directory == $to_theme)
  309. $theme_exists['to_theme'] = true;
  310. }
  311. if ($theme_exists['from_theme'] == false || $theme_exists['to_theme'] == false)
  312. $this->errors[] = $this->l('Theme(s) not found');
  313. }
  314. if (count($this->errors))
  315. return;
  316. $bool = true;
  317. $items = Language::getFilesList($from_lang, $from_theme, $to_lang, $to_theme, false, false, true);
  318. foreach ($items as $source => $dest)
  319. {
  320. if (!$this->checkDirAndCreate($dest))
  321. $this->errors[] = sprintf($this->l('Impossible to create the directory "%s".'), $dest);
  322. elseif (!copy($source, $dest))
  323. $this->errors[] = sprintf($this->l('Impossible to copy "%s" to "%s".'), $source, $dest);
  324. elseif (strpos($dest, 'modules') && basename($source) === $from_lang.'.php' && $bool !== false)
  325. if (!$this->changeModulesKeyTranslation($dest, $from_theme, $to_theme))
  326. $this->errors[] = sprintf($this->l('Impossible to translate "$dest".'), $dest);
  327. }
  328. if (!count($this->errors))
  329. $this->redirect(false, 14);
  330. $this->errors[] = $this->l('A part of the data has been copied but some of the language files could not be found.');
  331. }
  332. /**
  333. * Change the key translation to according it to theme name.
  334. *
  335. * @param string $path
  336. * @param string $theme_from
  337. * @param string $theme_to
  338. * @return boolean
  339. */
  340. public function changeModulesKeyTranslation($path, $theme_from, $theme_to)
  341. {
  342. $content = file_get_contents($path);
  343. $arr_replace = array();
  344. $bool_flag = true;
  345. if (preg_match_all('#\$_MODULE\[\'([^\']+)\'\]#Ui', $content, $matches))
  346. {
  347. foreach ($matches[1] as $key => $value)
  348. $arr_replace[$value] = str_replace($theme_from, $theme_to, $value);
  349. $content = str_replace(array_keys($arr_replace), array_values($arr_replace), $content);
  350. $bool_flag = (file_put_contents($path, $content) === false) ? false : true;
  351. }
  352. return $bool_flag;
  353. }
  354. public function exportTabs()
  355. {
  356. // Get name tabs by iso code
  357. $tabs = Tab::getTabs($this->lang_selected->id);
  358. // Get name of the default tabs
  359. $tabs_default_lang = Tab::getTabs(1);
  360. $tabs_default = array();
  361. foreach ($tabs_default_lang as $tab)
  362. $tabs_default[$tab['class_name']] = pSQL($tab['name']);
  363. // Create content
  364. $content = "<?php\n\n\$tabs = array();";
  365. if (!empty($tabs))
  366. foreach ($tabs as $tab)
  367. if ($tabs_default[$tab['class_name']] != pSQL($tab['name']))
  368. $content .= "\n\$tabs['".$tab['class_name']."'] = '".pSQL($tab['name'])."';";
  369. $content .= "\n\nreturn \$tabs;";
  370. $dir = _PS_TRANSLATIONS_DIR_.$this->lang_selected->iso_code.DIRECTORY_SEPARATOR;
  371. $path = $dir.'tabs.php';
  372. // Check if tabs.php exists for the selected Iso Code
  373. if (!Tools::file_exists_cache($dir))
  374. if (!mkdir($dir, 0777, true))
  375. throw new PrestaShopException('The file '.$dir.' cannot be created.');
  376. if (!file_put_contents($path, $content))
  377. throw new PrestaShopException('File "'.$path.'" doesn\'t exists and cannot be created in '.$dir);
  378. if (!is_writable($path))
  379. $this->displayWarning(sprintf(Tools::displayError('This file must be writable: %s'), $path));
  380. }
  381. public function submitExportLang()
  382. {
  383. if ($this->lang_selected->iso_code && $this->theme_selected)
  384. {
  385. $this->exportTabs();
  386. $items = array_flip(Language::getFilesList($this->lang_selected->iso_code, $this->theme_selected, false, false, false, false, true));
  387. $file_name = _PS_TRANSLATIONS_DIR_.'/export/'.$this->lang_selected->iso_code.'.gzip';
  388. require_once(_PS_TOOL_DIR_.'tar/Archive_Tar.php');
  389. $gz = new Archive_Tar($file_name, true);
  390. if ($gz->createModify($items, null, _PS_ROOT_DIR_))
  391. {
  392. ob_start();
  393. header('Pragma: public');
  394. header('Expires: 0');
  395. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  396. header('Cache-Control: public');
  397. header('Content-Description: File Transfer');
  398. header('Content-type: application/octet-stream');
  399. header('Content-Disposition: attachment; filename="'.$this->lang_selected->iso_code.'.gzip'.'"');
  400. header('Content-Transfer-Encoding: binary');
  401. ob_end_flush();
  402. readfile($file_name);
  403. @unlink($file_name);
  404. exit;
  405. }
  406. $this->errors[] = Tools::displayError('An error occurred while creating archive.');
  407. }
  408. $this->errors[] = Tools::displayError('Please select a language and a theme.');
  409. }
  410. public static function checkAndAddMailsFiles($iso_code, $files_list)
  411. {
  412. if (Language::getIdByIso('en'))
  413. $default_language = 'en';
  414. else
  415. $default_language = Language::getIsoById((int)Configuration::get('PS_LANG_DEFAULT'));
  416. if (!$default_language || !Validate::isLanguageIsoCode($default_language))
  417. return false;
  418. // 1 - Scan mails files
  419. $mails = array();
  420. if (Tools::file_exists_cache(_PS_MAIL_DIR_.$default_language.'/'))
  421. $mails = scandir(_PS_MAIL_DIR_.$default_language.'/');
  422. $mails_new_lang = array();
  423. // Get all email files
  424. foreach ($files_list as $file)
  425. {
  426. if (preg_match('#^mails\/([a-z0-9]+)\/#Ui', $file['filename'], $matches))
  427. {
  428. $slash_pos = strrpos($file['filename'], '/');
  429. $mails_new_lang[] = substr($file['filename'], -(strlen($file['filename']) - $slash_pos - 1));
  430. }
  431. }
  432. // Get the difference
  433. $arr_mails_needed = array_diff($mails, $mails_new_lang);
  434. // Add mails files
  435. foreach ($arr_mails_needed as $mail_to_add)
  436. if (!in_array($mail_to_add, self::$ignore_folder))
  437. @copy(_PS_MAIL_DIR_.$default_language.'/'.$mail_to_add, _PS_MAIL_DIR_.$iso_code.'/'.$mail_to_add);
  438. // 2 - Scan modules files
  439. $modules = scandir(_PS_MODULE_DIR_);
  440. $module_mail_en = array();
  441. $module_mail_iso_code = array();
  442. foreach ($modules as $module)
  443. {
  444. if (!in_array($module, self::$ignore_folder) && Tools::file_exists_cache(_PS_MODULE_DIR_.$module.'/mails/'.$default_language.'/'))
  445. {
  446. $arr_files = scandir(_PS_MODULE_DIR_.$module.'/mails/'.$default_language.'/');
  447. foreach ($arr_files as $file)
  448. {
  449. if (!in_array($file, self::$ignore_folder))
  450. {
  451. if (Tools::file_exists_cache(_PS_MODULE_DIR_.$module.'/mails/'.$default_language.'/'.$file))
  452. $module_mail_en[] = _PS_MODULE_DIR_.$module.'/mails/ISO_CODE/'.$file;
  453. if (Tools::file_exists_cache(_PS_MODULE_DIR_.$module.'/mails/'.$iso_code.'/'.$file))
  454. $module_mail_iso_code[] = _PS_MODULE_DIR_.$module.'/mails/ISO_CODE/'.$file;
  455. }
  456. }
  457. }
  458. }
  459. // Get the difference in this modules
  460. $arr_modules_mails_needed = array_diff($module_mail_en, $module_mail_iso_code);
  461. // Add mails files for this modules
  462. foreach ($arr_modules_mails_needed as $file)
  463. {
  464. $file_en = str_replace('ISO_CODE', $default_language, $file);
  465. $file_iso_code = str_replace('ISO_CODE', $iso_code, $file);
  466. $dir_iso_code = substr($file_iso_code, 0, -(strlen($file_iso_code) - strrpos($file_iso_code, '/') - 1));
  467. if (!file_exists($dir_iso_code))
  468. {
  469. mkdir($dir_iso_code);
  470. file_put_contents($dir_iso_code.'/index.php', Tools::getDefaultIndexContent());
  471. }
  472. if (Tools::file_exists_cache($file_en))
  473. copy($file_en, $file_iso_code);
  474. }
  475. }
  476. /**
  477. * Move theme translations in selected themes
  478. *
  479. * @param array $files
  480. * @param array $themes_selected
  481. */
  482. public function checkAndAddThemesFiles($files, $themes_selected)
  483. {
  484. foreach ($files as $file)
  485. {
  486. // Check if file is a file theme
  487. if (preg_match('#^themes\/([a-z0-9]+)\/lang\/#Ui', $file['filename'], $matches))
  488. {
  489. $slash_pos = strrpos($file['filename'], '/');
  490. $name_file = substr($file['filename'], -(strlen($file['filename']) - $slash_pos - 1));
  491. $name_default_theme = $matches[1];
  492. $deleted_old_theme = false;
  493. // Get the old file theme
  494. if (file_exists(_PS_THEME_DIR_.'lang/'.$name_file))
  495. $theme_file_old = _PS_THEME_DIR_.'lang/'.$name_file;
  496. else
  497. {
  498. $deleted_old_theme = true;
  499. $theme_file_old = str_replace(self::DEFAULT_THEME_NAME, $name_default_theme, _PS_THEME_DIR_.'lang/'.$name_file);
  500. }
  501. // Move the old file theme in the new folder
  502. foreach ($themes_selected as $theme_name)
  503. if (file_exists($theme_file_old))
  504. copy($theme_file_old, str_replace($name_default_theme, $theme_name, $theme_file_old));
  505. if ($deleted_old_theme)
  506. @unlink($theme_file_old);
  507. }
  508. }
  509. }
  510. /**
  511. * Add new translations tabs by code ISO
  512. *
  513. * @param array $iso_code
  514. * @param array $files
  515. */
  516. public static function addNewTabs($iso_code, $files)
  517. {
  518. $errors = array();
  519. foreach ($files as $file)
  520. {
  521. // Check if file is a file theme
  522. if (preg_match('#^translations\/'.$iso_code.'\/tabs.php#Ui', $file['filename'], $matches) && Validate::isLanguageIsoCode($iso_code))
  523. {
  524. // Include array width new translations tabs
  525. $_TABS = array();
  526. clearstatcache();
  527. if (file_exists(_PS_ROOT_DIR_.DIRECTORY_SEPARATOR.$file['filename']))
  528. include_once(_PS_ROOT_DIR_.DIRECTORY_SEPARATOR.$file['filename']);
  529. if (count($_TABS))
  530. {
  531. foreach ($_TABS as $class_name => $translations)
  532. {
  533. // Get instance of this tab by class name
  534. $tab = Tab::getInstanceFromClassName($class_name);
  535. //Check if class name exists
  536. if (isset($tab->class_name) && !empty($tab->class_name))
  537. {
  538. $id_lang = Language::getIdByIso($iso_code);
  539. $tab->name[(int)$id_lang] = $translations;
  540. // Do not crash at intall
  541. if (!isset($tab->name[Configuration::get('PS_LANG_DEFAULT')]))
  542. $tab->name[(int)Configuration::get('PS_LANG_DEFAULT')] = $translations;
  543. if (!Validate::isGenericName($tab->name[(int)$id_lang]))
  544. $errors[] = sprintf(Tools::displayError('Tab "%s" is not valid'), $tab->name[(int)$id_lang]);
  545. else
  546. $tab->update();
  547. }
  548. }
  549. }
  550. }
  551. }
  552. return $errors;
  553. }
  554. public static function checkTranslationFile($content)
  555. {
  556. $lines = array_map('trim', explode("\n", $content));
  557. $global = false;
  558. foreach ($lines as $line)
  559. {
  560. // PHP tags
  561. if (in_array($line, array('<?php', '?>', '')))
  562. continue;
  563. // Global variable declaration
  564. if (!$global && preg_match('/^global\s+\$([a-z0-9-_]+)\s*;$/i', $line, $matches))
  565. {
  566. $global = $matches[1];
  567. continue;
  568. }
  569. // Global variable initialization
  570. if ($global != false && preg_match('/^\$'.preg_quote($global, '/').'\s*=\s*array\(\s*\)\s*;$/i', $line))
  571. continue;
  572. // Global variable initialization without declaration
  573. if (!$global && preg_match('/^\$([a-z0-9-_]+)\s*=\s*array\(\s*\)\s*;$/i', $line, $matches))
  574. {
  575. $global = $matches[1];
  576. continue;
  577. }
  578. // Assignation
  579. if (preg_match('/^\$'.preg_quote($global, '/').'\[\''._PS_TRANS_PATTERN_.'\'\]\s*=\s*\''._PS_TRANS_PATTERN_.'\'\s*;$/i', $line))
  580. continue;
  581. // Sometimes the global variable is returned...
  582. if (preg_match('/^return\s+\$'.preg_quote($global, '/').'\s*;$/i', $line, $matches))
  583. continue;
  584. return false;
  585. }
  586. return true;
  587. }
  588. public function submitImportLang()
  589. {
  590. if (!isset($_FILES['file']['tmp_name']) || !$_FILES['file']['tmp_name'])
  591. $this->errors[] = Tools::displayError('No file has been selected.');
  592. else
  593. {
  594. require_once(_PS_TOOL_DIR_.'tar/Archive_Tar.php');
  595. $gz = new Archive_Tar($_FILES['file']['tmp_name'], true);
  596. $filename = $_FILES['file']['name'];
  597. $iso_code = str_replace(array('.tar.gz', '.gzip'), '', $filename);
  598. if (Validate::isLangIsoCode($iso_code))
  599. {
  600. $themes_selected = Tools::getValue('theme', array(self::DEFAULT_THEME_NAME));
  601. $files_list = AdminTranslationsController::filterTranslationFiles($gz->listContent());
  602. $files_paths = AdminTranslationsController::filesListToPaths($files_list);
  603. $uniqid = uniqid();
  604. $sandbox = _PS_CACHE_DIR_.'sandbox'.DIRECTORY_SEPARATOR.$uniqid.DIRECTORY_SEPARATOR;
  605. if ($gz->extractList($files_paths, $sandbox))
  606. {
  607. foreach ($files_list as $file2check)
  608. {
  609. //don't validate index.php, will be overwrite when extract in translation directory
  610. if (pathinfo($file2check['filename'], PATHINFO_BASENAME) == 'index.php')
  611. continue;
  612. if (preg_match('@^[0-9a-z-_/\\\\]+\.php$@i', $file2check['filename']))
  613. {
  614. if (!AdminTranslationsController::checkTranslationFile(file_get_contents($sandbox.$file2check['filename'])))
  615. $this->errors[] = sprintf(Tools::displayError('Validation failed for: %s'), $file2check['filename']);
  616. }
  617. elseif (!preg_match('@^[0-9a-z-_/\\\\]+\.(html|tpl|txt)$@i', $file2check['filename']))
  618. $this->errors[] = sprintf(Tools::displayError('Unidentified file found: %s'), $file2check['filename']);
  619. }
  620. Tools::deleteDirectory($sandbox, true);
  621. }
  622. $i = 0;
  623. $tmp_array = array();
  624. foreach ($files_paths as $files_path)
  625. {
  626. $path = dirname($files_path);
  627. if (is_dir(_PS_TRANSLATIONS_DIR_.'../'.$path) && !is_writable(_PS_TRANSLATIONS_DIR_.'../'.$path) && !in_array($path, $tmp_array))
  628. {
  629. $this->errors[] = (!$i++? Tools::displayError('The archive cannot be extracted.').' ' : '').Tools::displayError('The server does not have permissions for writing.').' '.sprintf(Tools::displayError('Please check rights for %s'), $path);
  630. $tmp_array[] = $path;
  631. }
  632. }
  633. if (count($this->errors))
  634. return false;
  635. if ($error = $gz->extractList($files_paths, _PS_TRANSLATIONS_DIR_.'../'))
  636. {
  637. if (is_object($error) && !empty($error->message))
  638. $this->errors[] = Tools::displayError('The archive cannot be extracted.'). ' '.$error->message;
  639. else
  640. {
  641. foreach ($files_list as $file2check)
  642. if (pathinfo($file2check['filename'], PATHINFO_BASENAME) == 'index.php' && file_put_contents(_PS_TRANSLATIONS_DIR_.'../'.$file2check['filename'], Tools::getDefaultIndexContent()))
  643. continue;
  644. // Clear smarty modules cache
  645. Tools::clearCache();
  646. if (Validate::isLanguageFileName($filename))
  647. {
  648. if (!Language::checkAndAddLanguage($iso_code))
  649. $conf = 20;
  650. else
  651. {
  652. // Reset cache
  653. Language::loadLanguages();
  654. AdminTranslationsController::checkAndAddMailsFiles($iso_code, $files_list);
  655. $this->checkAndAddThemesFiles($files_list, $themes_selected);
  656. $tab_errors = AdminTranslationsController::addNewTabs($iso_code, $files_list);
  657. if (count($tab_errors))
  658. {
  659. $this->errors += $tab_errors;
  660. return false;
  661. }
  662. }
  663. }
  664. $this->redirect(false, (isset($conf) ? $conf : '15'));
  665. }
  666. }
  667. $this->errors[] = Tools::displayError('The archive cannot be extracted.');
  668. }
  669. else
  670. $this->errors[] = sprintf(Tools::displayError('ISO CODE invalid "%1$s" for the following file: "%2$s"'), $iso_code, $filename);
  671. }
  672. }
  673. /**
  674. * Filter the translation files contained in a .gzip pack
  675. * and return only the ones that we want.
  676. *
  677. * Right now the function only needs to check that
  678. * the modules for which we want to add translations
  679. * are present on the shop (installed or not).
  680. *
  681. * $list is the output of Archive_Tar::listContent()
  682. */
  683. public static function filterTranslationFiles($list)
  684. {
  685. $kept = array();
  686. foreach ($list as $file)
  687. {
  688. if ('index.php' == basename($file['filename']))
  689. continue;
  690. if (preg_match('#^modules/([^/]+)/#', $file['filename'], $m))
  691. {
  692. if (is_dir(_PS_MODULE_DIR_.$m[1]))
  693. $kept[] = $file;
  694. }
  695. else
  696. $kept[] = $file;
  697. }
  698. return $kept;
  699. }
  700. /**
  701. * Turn the list returned by
  702. * AdminTranslationsController::filterTranslationFiles()
  703. * into a list of paths that can be passed to
  704. * Archive_Tar::extractList()
  705. */
  706. public static function filesListToPaths($list)
  707. {
  708. $paths = array();
  709. foreach ($list as $item)
  710. $paths[] = $item['filename'];
  711. return $paths;
  712. }
  713. public function submitAddLang()
  714. {
  715. $arr_import_lang = explode('|', Tools::getValue('params_import_language')); /* 0 = Language ISO code, 1 = PS version */
  716. if (Validate::isLangIsoCode($arr_import_lang[0]))
  717. {
  718. $array_stream_context = @stream_context_create(array('http' => array('method' => 'GET', 'timeout' => 10)));
  719. $content = Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/gzip/'.$arr_import_lang[1].'/'.Tools::strtolower($arr_import_lang[0]).'.gzip', false, $array_stream_context);
  720. if ($content)
  721. {
  722. $file = _PS_TRANSLATIONS_DIR_.$arr_import_lang[0].'.gzip';
  723. if ((bool)@file_put_contents($file, $content))
  724. {
  725. require_once(_PS_TOOL_DIR_.'/tar/Archive_Tar.php');
  726. $gz = new Archive_Tar($file, true);
  727. $files_list = AdminTranslationsController::filterTranslationFiles($gz->listContent());
  728. if ($error = $gz->extractList(AdminTranslationsController::filesListToPaths($files_list), _PS_TRANSLATIONS_DIR_.'../'))
  729. {
  730. if (is_object($error) && !empty($error->message))
  731. $this->errors[] = Tools::displayError('The archive cannot be extracted.'). ' '.$error->message;
  732. else
  733. {
  734. if (!Language::checkAndAddLanguage($arr_import_lang[0]))
  735. $conf = 20;
  736. else
  737. {
  738. // Reset cache
  739. Language::loadLanguages();
  740. // Clear smarty modules cache
  741. Tools::clearCache();
  742. AdminTranslationsController::checkAndAddMailsFiles($arr_import_lang[0], $files_list);
  743. if ($tab_errors = AdminTranslationsController::addNewTabs($arr_import_lang[0], $files_list))
  744. $this->errors += $tab_errors;
  745. }
  746. if (!unlink($file))
  747. $this->errors[] = sprintf(Tools::displayError('Cannot delete the archive %s.'), $file);
  748. $this->redirect(false, (isset($conf) ? $conf : '15'));
  749. }
  750. }
  751. elseif (!unlink($file))
  752. $this->errors[] = sprintf(Tools::displayError('Cannot delete the archive %s.'), $file);
  753. }
  754. else
  755. $this->errors[] = Tools::displayError('The server does not have permissions for writing.').' '.sprintf(Tools::displayError('Please check rights for %s'), dirname($file));
  756. }
  757. else
  758. $this->errors[] = Tools::displayError('Language not found.');
  759. }
  760. else
  761. $this->errors[] = Tools::displayError('Invalid parameter.');
  762. }
  763. /**
  764. * This method check each file (tpl or php file), get its sentences to translate,
  765. * compare with posted values and write in iso code translation file.
  766. *
  767. * @param string $file_name
  768. * @param array $files
  769. * @param string $theme_name
  770. * @param string $module_name
  771. * @param string|boolean $dir
  772. * @return void
  773. */
  774. protected function findAndWriteTranslationsIntoFile($file_name, $files, $theme_name, $module_name, $dir = false)
  775. {
  776. // These static vars allow to use file to write just one time.
  777. static $cache_file = array();
  778. static $str_write = '';
  779. static $array_check_duplicate = array();
  780. // Set file_name in static var, this allow to open and wright the file just one time
  781. if (!isset($cache_file[$theme_name.'-'.$file_name]))
  782. {
  783. $str_write = '';
  784. $cache_file[$theme_name.'-'.$file_name] = true;
  785. if (!Tools::file_exists_cache(dirname($file_name)))
  786. mkdir(dirname($file_name), 0777, true);
  787. if (!Tools::file_exists_cache($file_name))
  788. file_put_contents($file_name, '');
  789. if (!is_writable($file_name))
  790. throw new PrestaShopException(sprintf(
  791. Tools::displayError('Cannot write to the theme\'s language file (%s). Please check write permissions.'),
  792. $file_name
  793. ));
  794. // this string is initialized one time for a file
  795. $str_write .= "<?php\n\nglobal \$_MODULE;\n\$_MODULE = array();\n";
  796. $array_check_duplicate = array();
  797. }
  798. foreach ($files as $file)
  799. {
  800. if (preg_match('/^(.*)\.(tpl|php)$/', $file) && Tools::file_exists_cache($dir.$file) && !in_array($file, self::$ignore_folder))
  801. {
  802. // Get content for this file
  803. $content = file_get_contents($dir.$file);
  804. // Get file type
  805. $type_file = substr($file, -4) == '.tpl' ? 'tpl' : 'php';
  806. // Parse this content
  807. $matches = $this->userParseFile($content, $this->type_selected, $type_file, $module_name);
  808. // Write each translation on its module file
  809. $template_name = substr(basename($file), 0, -4);
  810. foreach ($matches as $key)
  811. {
  812. if ($theme_name)
  813. {
  814. $post_key = md5(strtolower($module_name).'_'.strtolower($theme_name).'_'.strtolower($template_name).'_'.md5($key));
  815. $pattern = '\'<{'.strtolower($module_name).'}'.strtolower($theme_name).'>'.strtolower($template_name).'_'.md5($key).'\'';
  816. }
  817. else
  818. {
  819. $post_key = md5(strtolower($module_name).'_'.strtolower($template_name).'_'.md5($key));
  820. $pattern = '\'<{'.strtolower($module_name).'}prestashop>'.strtolower($template_name).'_'.md5($key).'\'';
  821. }
  822. if (array_key_exists($post_key, $_POST) && !empty($_POST[$post_key]) && !in_array($pattern, $array_check_duplicate))
  823. {
  824. $array_check_duplicate[] = $pattern;
  825. $str_write .= '$_MODULE['.$pattern.'] = \''.pSQL(str_replace(array("\r\n", "\r", "\n"), ' ', $_POST[$post_key])).'\';'."\n";
  826. $this->total_expression++;
  827. }
  828. }
  829. }
  830. }
  831. if (isset($cache_file[$theme_name.'-'.$file_name]) && $str_write != "<?php\n\nglobal \$_MODULE;\n\$_MODULE = array();\n")
  832. file_put_contents($file_name, $str_write);
  833. }
  834. /**
  835. * Clear the list of module file by type (file or directory)
  836. *
  837. * @param $files : list of files
  838. * @param string $type_clear (file|directory)
  839. * @param string $path
  840. * @return array : list of a good files
  841. */
  842. public function clearModuleFiles($files, $type_clear = 'file', $path = '')
  843. {
  844. // List of directory which not must be parsed
  845. $arr_exclude = array('img', 'js', 'mails','override');
  846. // List of good extention files
  847. $arr_good_ext = array('.tpl', '.php');
  848. foreach ($files as $key => $file)
  849. {
  850. if ($file{0} === '.' || in_array(substr($file, 0, strrpos($file, '.')), $this->all_iso_lang))
  851. unset($files[$key]);
  852. else if ($type_clear === 'file' && !in_array(substr($file, strrpos($file, '.')), $arr_good_ext))
  853. unset($files[$key]);
  854. else if ($type_clear === 'directory' && (!is_dir($path.$file) || in_array($file, $arr_exclude)))
  855. unset($files[$key]);
  856. }
  857. return $files;
  858. }
  859. /**
  860. * This method get translation for each files of a module,
  861. * compare with global $_MODULES array and fill AdminTranslations::modules_translations array
  862. * With key as English sentences and values as their iso code translations.
  863. *
  864. * @param array $files
  865. * @param string $theme_name
  866. * @param string $module_name
  867. * @param string|boolean $dir
  868. * @param string $iso_code
  869. * @return void
  870. */
  871. protected function findAndFillTranslations($files, $theme_name, $module_name, $dir = false)
  872. {
  873. $name_var = $this->translations_informations[$this->type_selected]['var'];
  874. // added for compatibility
  875. $GLOBALS[$name_var] = array_change_key_case($GLOBALS[$name_var]);
  876. // Thank to this var similar keys are not duplicate
  877. // in AndminTranslation::modules_translations array
  878. // see below
  879. $array_check_duplicate = array();
  880. foreach ($files as $file)
  881. {
  882. if ((preg_match('/^(.*).tpl$/', $file) || preg_match('/^(.*).php$/', $file)) && Tools::file_exists_cache($file_path = $dir.$file))
  883. {
  884. // Get content for this file
  885. $content = file_get_contents($file_path);
  886. // Module files can now be ignored by adding this string in a file
  887. if (strpos($content, 'IGNORE_THIS_FILE_FOR_TRANSLATION') !== false)
  888. continue;
  889. // Get file type
  890. $type_file = substr($file, -4) == '.tpl' ? 'tpl' : 'php';
  891. // Parse this content
  892. $matches = $this->userParseFile($content, $this->type_selected, $type_file, $module_name);
  893. // Write each translation on its module file
  894. $template_name = substr(basename($file), 0, -4);
  895. foreach ($matches as $key)
  896. {
  897. $md5_key = md5($key);
  898. $module_key = '<{'.Tools::strtolower($module_name).'}'.strtolower($theme_name).'>'.Tools::strtolower($template_name).'_'.$md5_key;
  899. $default_key = '<{'.Tools::strtolower($module_name).'}prestashop>'.Tools::strtolower($template_name).'_'.$md5_key;
  900. // to avoid duplicate entry
  901. if (!in_array($module_key, $array_check_duplicate))
  902. {
  903. $array_check_duplicate[] = $module_key;
  904. if (!isset($this->modules_translations[$theme_name][$module_name][$template_name][$key]['trad']))
  905. $this->total_expression++;
  906. if ($theme_name && array_key_exists($module_key, $GLOBALS[$name_var]))
  907. $this->modules_translations[$theme_name][$module_name][$template_name][$key]['trad'] = html_entity_decode($GLOBALS[$name_var][$module_key], ENT_COMPAT, 'UTF-8');
  908. elseif (array_key_exists($default_key, $GLOBALS[$name_var]))
  909. $this->modules_translations[$theme_name][$module_name][$template_name][$key]['trad'] = html_entity_decode($GLOBALS[$name_var][$default_key], ENT_COMPAT, 'UTF-8');
  910. else
  911. {
  912. $this->modules_translations[$theme_name][$module_name][$template_name][$key]['trad'] = '';
  913. $this->missing_translations++;
  914. }
  915. $this->modules_translations[$theme_name][$module_name][$template_name][$key]['use_sprintf'] = $this->checkIfKeyUseSprintf($key);
  916. }
  917. }
  918. }
  919. }
  920. }
  921. /**
  922. * Get list of files which must be parsed by directory and by type of translations
  923. *
  924. * @return array : list of files by directory
  925. */
  926. public function getFileToParseByTypeTranslation()
  927. {
  928. $directories = array();
  929. switch ($this->type_selected)
  930. {
  931. case 'front':
  932. $directories['tpl'] = array(_PS_ALL_THEMES_DIR_ => scandir(_PS_ALL_THEMES_DIR_));
  933. self::$ignore_folder[] = 'modules';
  934. $directories['tpl'] = array_merge($directories['tpl'], $this->listFiles(_PS_THEME_SELECTED_DIR_));
  935. if (isset($directories['tpl'][_PS_THEME_SELECTED_DIR_.'pdf/']))
  936. unset($directories['tpl'][_PS_THEME_SELECTED_DIR_.'pdf/']);
  937. if (Tools::file_exists_cache(_PS_THEME_OVERRIDE_DIR_))
  938. $directories['tpl'] = array_merge($directories['tpl'], $this->listFiles(_PS_THEME_OVERRIDE_DIR_));
  939. break;
  940. case 'back':
  941. $directories = array(
  942. 'php' => array(
  943. _PS_ADMIN_CONTROLLER_DIR_ => scandir(_PS_ADMIN_CONTROLLER_DIR_),
  944. _PS_OVERRIDE_DIR_.'controllers/admin/' => scandir(_PS_OVERRIDE_DIR_.'controllers/admin/'),
  945. _PS_CLASS_DIR_.'helper/' => scandir(_PS_CLASS_DIR_.'helper/'),
  946. _PS_CLASS_DIR_.'controller/' => array('AdminController.php'),
  947. _PS_CLASS_DIR_ => array('PaymentModule.php')
  948. ),
  949. 'tpl' => $this->listFiles(_PS_ADMIN_DIR_.DIRECTORY_SEPARATOR.'themes/'),
  950. 'specific' => array(
  951. _PS_ADMIN_DIR_.DIRECTORY_SEPARATOR => array(
  952. 'header.inc.php',
  953. 'footer.inc.php',
  954. 'index.php',
  955. 'functions.php'
  956. )
  957. )
  958. );
  959. // For translate the template which are overridden
  960. if (file_exists(_PS_OVERRIDE_DIR_.'controllers'.DIRECTORY_SEPARATOR.'admin'.DIRECTORY_SEPARATOR.'templates'))
  961. $directories['tpl'] = array_merge($directories['tpl'], $this->listFiles(_PS_OVERRIDE_DIR_.'controllers'.DIRECTORY_SEPARATOR.'admin'.DIRECTORY_SEPARATOR.'templates'));
  962. break;
  963. case 'errors':
  964. $directories['php'] = array(
  965. _PS_ROOT_DIR_ => scandir(_PS_ROOT_DIR_),
  966. _PS_ADMIN_DIR_.DIRECTORY_SEPARATOR => scandir(_PS_ADMIN_DIR_.DIRECTORY_SEPARATOR),
  967. _PS_FRONT_CONTROLLER_DIR_ => scandir(_PS_FRONT_CONTROLLER_DIR_),
  968. _PS_ADMIN_CONTROLLER_DIR_ => scandir(_PS_ADMIN_CONTROLLER_DIR_),
  969. _PS_OVERRIDE_DIR_.'controllers/front/' => scandir(_PS_OVERRIDE_DIR_.'controllers/front/'),
  970. _PS_OVERRIDE_DIR_.'controllers/admin/' => scandir(_PS_OVERRIDE_DIR_.'controllers/admin/')
  971. );
  972. // Get all files for folders classes/ and override/classes/ recursively
  973. $directories['php'] = array_merge($directories['php'], $this->listFiles(_PS_CLASS_DIR_, array(), 'php'));
  974. $directories['php'] = array_merge($directories['php'], $this->listFiles(_PS_OVERRIDE_DIR_.'classes/', array(), 'php'));
  975. break;
  976. case 'fields':
  977. $directories['php'] = $this->listFiles(_PS_CLASS_DIR_, array(), 'php');
  978. break;
  979. case 'pdf':
  980. $tpl_theme = Tools::file_exists_cache(_PS_THEME_SELECTED_DIR_.'pdf/') ? scandir(_PS_THEME_SELECTED_DIR_.'pdf/') : array();
  981. $directories = array(
  982. 'php' => array(
  983. _PS_CLASS_DIR_.'pdf/' => scandir(_PS_CLASS_DIR_.'pdf/'),
  984. _PS_OVERRIDE_DIR_.'classes/pdf/' => scandir(_PS_OVERRIDE_DIR_.'classes/pdf/')
  985. ),
  986. 'tpl' => array(
  987. _PS_PDF_DIR_ => scandir(_PS_PDF_DIR_),
  988. _PS_THEME_SELECTED_DIR_.'pdf/' => $tpl_theme
  989. )
  990. );
  991. break;
  992. case 'mails':
  993. $directories['php'] = array(
  994. _PS_FRONT_CONTROLLER_DIR_ => scandir(_PS_FRONT_CONTROLLER_DIR_),
  995. _PS_ADMIN_CONTROLLER_DIR_ => scandir(_PS_ADMIN_CONTROLLER_DIR_),
  996. _PS_OVERRIDE_DIR_.'controllers/front/' => scandir(_PS_OVERRIDE_DIR_.'controllers/front/'),
  997. _PS_OVERRIDE_DIR_.'controllers/admin/' => scandir(_PS_OVERRIDE_DIR_.'controllers/admin/'),
  998. _PS_ADMIN_DIR_.DIRECTORY_SEPARATOR => scandir(_PS_ADMIN_DIR_.DIRECTORY_SEPARATOR),
  999. _PS_ADMIN_DIR_.DIRECTORY_SEPARATOR.'tabs/' => scandir(_PS_ADMIN_DIR_.DIRECTORY_SEPARATOR.'/tabs')
  1000. );
  1001. // Get all files for folders classes/ and override/classes/ recursively
  1002. $directories['php'] = array_merge($directories['php'], $this->listFiles(_PS_CLASS_DIR_, array(), 'php'));
  1003. $directories['php'] = array_merge($directories['php'], $this->listFiles(_PS_OVERRIDE_DIR_.'classes/', array(), 'php'));
  1004. $directories['php'] = array_merge($directories['php'], $this->getModulesHasMails());
  1005. break;
  1006. }
  1007. return $directories;
  1008. }
  1009. /**
  1010. * This method parse a file by type of translation and type file
  1011. *
  1012. * @param $content
  1013. * @param $type_translation : front, back, errors, modules...
  1014. * @param string|bool $type_file : (tpl|php)
  1015. * @param string $module_name : name of the module
  1016. * @return return $matches
  1017. */
  1018. protected function userParseFile($content, $type_translation, $type_file = false, $module_name = '')
  1019. {
  1020. switch ($type_translation)
  1021. {
  1022. case 'front':
  1023. // Parsing file in Front office
  1024. $regex = '/\{l\s*s=([\'\"])'._PS_TRANS_PATTERN_.'\1(\s*sprintf=.*)?(\s*js=1)?\s*\}/U';
  1025. break;
  1026. case 'back':
  1027. // Parsing file in Back office
  1028. if ($type_file == 'php')
  1029. $regex = '/this->l\((\')'._PS_TRANS_PATTERN_.'\'[\)|\,]/U';
  1030. else if ($type_file == 'specific')
  1031. $regex = '/Translate::getAdminTranslation\((\')'._PS_TRANS_PATTERN_.'\'(?:,.*)*\)/U';
  1032. else
  1033. $regex = '/\{l\s*s\s*=([\'\"])'._PS_TRANS_PATTERN_.'\1(\s*sprintf=.*)?(\s*js=1)?(\s*slashes=1)?.*\}/U';
  1034. break;
  1035. case 'errors':
  1036. // Parsing file for all errors syntax
  1037. $regex = '/Tools::displayError\((\')'._PS_TRANS_PATTERN_.'\'(,\s*(.+))?\)/U';
  1038. break;
  1039. case 'modules':
  1040. // Parsing modules file
  1041. if ($type_file == 'php')
  1042. $regex = '/->l\((\')'._PS_TRANS_PATTERN_.'\'(, ?\'(.+)\')?(, ?(.+))?\)/U';
  1043. else
  1044. // In tpl file look for something that should contain mod='module_name' according to the documentation
  1045. $regex = '/\{l\s*s=([\'\"])'._PS_TRANS_PATTERN_.'\1.*\s+mod=\''.$module_name.'\'.*\}/U';
  1046. break;
  1047. case 'pdf':
  1048. // Parsing PDF file
  1049. if ($type_file == 'php')
  1050. $regex = '/HTMLTemplate.*::l\((\')'._PS_TRANS_PATTERN_.'\'[\)|\,]/U';
  1051. else
  1052. $regex = '/\{l\s*s=([\'\"])'._PS_TRANS_PATTERN_.'\1(\s*sprintf=.*)?(\s*js=1)?(\s*pdf=\'true\')?\s*\}/U';
  1053. break;
  1054. }
  1055. if (!is_array($regex))
  1056. $regex = array($regex);
  1057. $strings = array();
  1058. foreach ($regex as $regex_row)
  1059. {
  1060. $matches = array();
  1061. $n = preg_match_all($regex_row, $content, $matches);
  1062. for ($i = 0; $i < $n; $i += 1)
  1063. {
  1064. $quote = $matches[1][$i];
  1065. $string = $matches[2][$i];
  1066. if ($quote === '"')
  1067. {
  1068. // Escape single quotes because the core will do it when looking for the translation of this string
  1069. $string = str_replace('\'', '\\\'', $string);
  1070. // Unescape double quotes
  1071. $string = preg_replace('/\\\\+"/', '"', $string);
  1072. }
  1073. $strings[] = $string;
  1074. }
  1075. }
  1076. return array_unique($strings);
  1077. }
  1078. /**
  1079. * Get all translations informations for all type of translations
  1080. *
  1081. * array(
  1082. * 'type' => array(
  1083. * 'name' => string : title for the translation type,
  1084. * 'var' => string : name of var for the translation file,
  1085. * 'dir' => string : dir of translation file
  1086. * 'file' => string : file name of translation file
  1087. * )
  1088. * )
  1089. */
  1090. public function getTranslationsInformations()
  1091. {
  1092. $this->translations_informations = array(
  1093. 'front' => array(
  1094. 'name' => $this->l('Front Office translations'),
  1095. 'var' => '_LANG',
  1096. 'dir' => defined('_PS_THEME_SELECTED_DIR_') ? _PS_THEME_SELECTED_DIR_.'lang/' : '',
  1097. 'file' => $this->lang_selected->iso_code.'.php'
  1098. ),
  1099. 'back' => array(
  1100. 'name' => $this->l('Back Office translations'),
  1101. 'var' => '_LANGADM',
  1102. 'dir' => _PS_TRANSLATIONS_DIR_.$this->lang_selected->iso_code.'/',
  1103. 'file' => 'admin.php'
  1104. ),
  1105. 'errors' => array(
  1106. 'name' => $this->l('Error message translations'),
  1107. 'var' => '_ERRORS',
  1108. 'dir' => _PS_TRANSLATIONS_DIR_.$this->lang_selected->iso_code.'/',
  1109. 'file' => 'errors.php'
  1110. ),
  1111. 'fields' => array(
  1112. 'name' => $this->l('Field name translations'),
  1113. 'var' => '_FIELDS',
  1114. 'dir' => _PS_TRANSLATIONS_DIR_.$this->lang_selected->iso_code.'/',
  1115. 'file' => 'fields.php'
  1116. ),
  1117. 'modules' => array(
  1118. 'name' => $this->l('Installed modules translations'),
  1119. 'var' => '_MODULES',
  1120. 'dir' => _PS_MODULE_DIR_,
  1121. 'file' => ''
  1122. ),
  1123. 'pdf' => array(
  1124. 'name' => $this->l('PDF translations'),
  1125. 'var' => '_LANGPDF',
  1126. 'dir' => _PS_TRANSLATIONS_DIR_.$this->lang_selected->iso_code.'/',
  1127. 'file' => 'pdf.php'
  1128. ),
  1129. 'mails' => array(
  1130. 'name' => $this->l('Email templates translations'),
  1131. 'var' => '_LANGMAIL',
  1132. 'dir' => _PS_MAIL_DIR_.$this->lang_selected->iso_code.'/',
  1133. 'file' => 'lang.php'
  1134. )
  1135. );
  1136. if (defined('_PS_THEME_SELECTED_DIR_'))
  1137. {
  1138. $this->translations_informations['modules']['override'] = array('dir' => _PS_THEME_SELECTED_DIR_.'modules/', 'file' => '');
  1139. $this->translations_informations['pdf']['override'] = array('dir' => _PS_THEME_SELECTED_DIR_.'pdf/lang/', 'file' => $this->lang_selected->iso_code.'.php');
  1140. $this->translations_informations['mails']['override'] = array('dir' => _PS_THEME_SELECTED_DIR_.'mails/'.$this->lang_selected->iso_code.'/', 'file' => 'lang.php');
  1141. }
  1142. }
  1143. /**
  1144. * Get all informations on : languages, theme and the translation type.
  1145. */
  1146. public function getInformations()
  1147. {
  1148. // Get all Languages
  1149. $this->languages = Language::getLanguages(false);
  1150. // Get all iso_code of languages
  1151. foreach ($this->languages as $language)
  1152. $this->all_iso_lang[] = $language['iso_code'];
  1153. // Get all themes
  1154. $this->themes = Theme::getThemes();
  1155. // Get folder name of theme
  1156. if (($theme = Tools::getValue('theme')) && !is_array($theme))
  1157. {
  1158. $theme_exists = $this->theme_exists($theme);
  1159. if (!$theme_exists)
  1160. throw new PrestaShopException(sprintf(Tools::displayError('Invalid theme "%s"'), Tools::safeOutput($theme)));
  1161. $this->theme_selected = Tools::safeOutput($theme);
  1162. }
  1163. // Set the path of selected theme
  1164. if ($this->theme_selected)
  1165. define('_PS_THEME_SELECTED_DIR_', _PS_ROOT_DIR_.'/themes/'.$this->theme_selected.'/');
  1166. else
  1167. define('_PS_THEME_SELECTED_DIR_', '');
  1168. // Get type of translation
  1169. if (($type = Tools::getValue('type')) && !is_array($type))
  1170. $this->type_selected = strtolower(Tools::safeOutput($type));
  1171. // Get selected language
  1172. if (Tools::getValue('lang') || Tools::getValue('iso_code'))
  1173. {
  1174. $iso_code = Tools::getValue('lang') ? Tools::getValue('lang') : Tools::getValue('iso_code');
  1175. if (!Validate::isLangIsoCode($iso_code) || !in_array($iso_code, $this->all_iso_lang))
  1176. throw new PrestaShopException(sprintf(Tools::displayError('Invalid iso code "%s"'), Tools::safeOutput($iso_code)));
  1177. $this->lang_selected = new Language((int)Language::getIdByIso($iso_code));
  1178. }
  1179. else
  1180. $this->lang_selected = new Language((int)Language::getIdByIso('en'));
  1181. // Get all information for translations
  1182. $this->getTranslationsInformations();
  1183. }
  1184. public function renderKpis()
  1185. {
  1186. $time = time();
  1187. $kpis = array();
  1188. /* The data generation is located in AdminStatsControllerCore */
  1189. $helper = new HelperKpi();
  1190. $helper->id = 'box-languages';
  1191. $helper->icon = 'icon-microphone';
  1192. $helper->color = 'color1';
  1193. $helper->href = $this->context->link->getAdminLink('AdminLanguages');
  1194. $helper->title = $this->l('Enabled Languages', null, null, false);
  1195. if (ConfigurationKPI::get('ENABLED_LANGUAGES') !== false)
  1196. $helper->value = ConfigurationKPI::get('ENABLED_LANGUAGES');
  1197. if (ConfigurationKPI::get('ENABLED_LANGUAGES_EXPIRE') < $time)
  1198. $helper->source = $this->context->link->getAdminLink('AdminStats').'&ajax=1&action=getKpi&kpi=enabled_languages';
  1199. $kpis[] = $helper->generate();
  1200. $helper = new HelperKpi();
  1201. $helper->id = 'box-country';
  1202. $helper->icon = 'icon-home';
  1203. $helper->color = 'color2';
  1204. $helper->title = $this->l('Main Country', null, null, false);
  1205. $helper->subtitle = $this->l('30 Days', null, null, false);
  1206. if (ConfigurationKPI::get('MAIN_COUNTRY', $this->context->language->id) !== false)
  1207. $helper->value = ConfigurationKPI::get('MAIN_COUNTRY', $this->context->language->id);
  1208. if (ConfigurationKPI::get('MAIN_COUNTRY_EXPIRE', $this->context->language->id) < $time)
  1209. $helper->source = $this->context->link->getAdminLink('AdminStats').'&ajax=1&action=getKpi&kpi=main_country';
  1210. $kpis[] = $helper->generate();
  1211. $helper = new HelperKpi();
  1212. $helper->id = 'box-translations';
  1213. $helper->icon = 'icon-list';
  1214. $helper->color = 'color3';
  1215. $helper->title = $this->l('Front Office Translations', null, null, false);
  1216. if (ConfigurationKPI::get('FRONTOFFICE_TRANSLATIONS') !== false)
  1217. $helper->value = ConfigurationKPI::get('FRONTOFFICE_TRANSLATIONS');
  1218. if (ConfigurationKPI::get('FRONTOFFICE_TRANSLATIONS_EXPIRE') < $time)
  1219. $helper->source = $this->context->link->getAdminLink('AdminStats').'&ajax=1&action=getKpi&kpi=frontoffice_translations';
  1220. $kpis[] = $helper->generate();
  1221. $helper = new HelperKpiRow();
  1222. $helper->kpis = $kpis;
  1223. return $helper->generate();
  1224. }
  1225. /**
  1226. * AdminController::postProcess() override
  1227. * @see AdminController::postProcess()
  1228. */
  1229. public function postProcess()
  1230. {
  1231. $this->getInformations();
  1232. /* PrestaShop demo mode */
  1233. if (_PS_MODE_DEMO_)
  1234. {
  1235. $this->errors[] = Tools::displayError('This functionality has been disabled.');
  1236. return;
  1237. }
  1238. /* PrestaShop demo mode */
  1239. try {
  1240. if

Large files files are truncated, but you can click here to view the full file