website2.lib.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. <?php
  2. /* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. */
  17. /**
  18. * \file htdocs/core/lib/website2.lib.php
  19. * \ingroup website
  20. * \brief Library for website module (rare functions not required for execution of website)
  21. */
  22. /**
  23. * Save content of a page on disk
  24. *
  25. * @param string $filemaster Full path of filename master.inc.php for website to generate
  26. * @return boolean True if OK
  27. */
  28. function dolSaveMasterFile($filemaster)
  29. {
  30. global $conf;
  31. // Now generate the master.inc.php page
  32. dol_syslog("We regenerate the master file");
  33. dol_delete_file($filemaster);
  34. $mastercontent = '<?php'."\n";
  35. $mastercontent .= '// File generated to link to the master file - DO NOT MODIFY - It is just an include'."\n";
  36. $mastercontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) {\n";
  37. $mastercontent .= " if (! defined('USEEXTERNALSERVER')) define('USEEXTERNALSERVER', 1);\n";
  38. $mastercontent .= " require_once '".DOL_DOCUMENT_ROOT."/master.inc.php';\n";
  39. $mastercontent .= "}\n";
  40. $mastercontent .= '?>'."\n";
  41. $result = file_put_contents($filemaster, $mastercontent);
  42. dolChmod($filemaster);
  43. return $result;
  44. }
  45. /**
  46. * Save an alias page on disk (A page that include the reference page).
  47. * It saves file into the root directory but also into language subdirectory.
  48. *
  49. * @param string $filealias Full path of filename to generate
  50. * @param Website $object Object website
  51. * @param WebsitePage $objectpage Object websitepage
  52. * @return boolean True if OK
  53. * @see dolSavePageContent()
  54. */
  55. function dolSavePageAlias($filealias, $object, $objectpage)
  56. {
  57. global $conf;
  58. // Now create the .tpl file
  59. dol_syslog("dolSavePageAlias We regenerate the alias page filealias=".$filealias);
  60. $aliascontent = '<?php'."\n";
  61. $aliascontent .= "// File generated to wrap the alias page - DO NOT MODIFY - It is just a wrapper to real page\n";
  62. $aliascontent .= 'global $dolibarr_main_data_root;'."\n";
  63. $aliascontent .= 'if (empty($dolibarr_main_data_root)) require \'./page'.$objectpage->id.'.tpl.php\'; ';
  64. $aliascontent .= 'else require $dolibarr_main_data_root.\'/website/\'.$website->ref.\'/page'.$objectpage->id.'.tpl.php\';'."\n";
  65. $aliascontent .= '?>'."\n";
  66. $result = file_put_contents($filealias, $aliascontent);
  67. if ($result === false) {
  68. dol_syslog("Failed to write file ".$filealias, LOG_WARNING);
  69. }
  70. dolChmod($filealias);
  71. // Save also alias into language subdirectory if it is not a main language
  72. if ($objectpage->lang && in_array($objectpage->lang, explode(',', $object->otherlang))) {
  73. $dirname = dirname($filealias);
  74. $filename = basename($filealias);
  75. $filealiassub = $dirname.'/'.$objectpage->lang.'/'.$filename;
  76. $aliascontent = '<?php'."\n";
  77. $aliascontent .= "// File generated to wrap the alias page - DO NOT MODIFY - It is just a wrapper to real page\n";
  78. $aliascontent .= 'global $dolibarr_main_data_root;'."\n";
  79. $aliascontent .= 'if (empty($dolibarr_main_data_root)) require \'../page'.$objectpage->id.'.tpl.php\'; ';
  80. $aliascontent .= 'else require $dolibarr_main_data_root.\'/website/\'.$website->ref.\'/page'.$objectpage->id.'.tpl.php\';'."\n";
  81. $aliascontent .= '?>'."\n";
  82. $result = file_put_contents($filealiassub, $aliascontent);
  83. if ($result === false) {
  84. dol_syslog("Failed to write file ".$filealiassub, LOG_WARNING);
  85. }
  86. dolChmod($filealiassub);
  87. } elseif (empty($objectpage->lang) || !in_array($objectpage->lang, explode(',', $object->otherlang))) {
  88. // Save also alias into all language subdirectories if it is a main language
  89. if (!getDolGlobalString('WEBSITE_DISABLE_MAIN_LANGUAGE_INTO_LANGSUBDIR') && !empty($object->otherlang)) {
  90. $dirname = dirname($filealias);
  91. $filename = basename($filealias);
  92. foreach (explode(',', $object->otherlang) as $sublang) {
  93. // Avoid to erase main alias file if $sublang is empty string
  94. if (empty(trim($sublang))) {
  95. continue;
  96. }
  97. $filealiassub = $dirname.'/'.$sublang.'/'.$filename;
  98. $aliascontent = '<?php'."\n";
  99. $aliascontent .= "// File generated to wrap the alias page - DO NOT MODIFY - It is just a wrapper to real page\n";
  100. $aliascontent .= 'global $dolibarr_main_data_root;'."\n";
  101. $aliascontent .= 'if (empty($dolibarr_main_data_root)) require \'../page'.$objectpage->id.'.tpl.php\'; ';
  102. $aliascontent .= 'else require $dolibarr_main_data_root.\'/website/\'.$website->ref.\'/page'.$objectpage->id.'.tpl.php\';'."\n";
  103. $aliascontent .= '?>'."\n";
  104. $result = file_put_contents($filealiassub, $aliascontent);
  105. if ($result === false) {
  106. dol_syslog("Failed to write file ".$filealiassub, LOG_WARNING);
  107. }
  108. dolChmod($filealiassub);
  109. }
  110. }
  111. }
  112. return ($result ? true : false);
  113. }
  114. /**
  115. * Save content of a page on disk (page name is generally ID_of_page.php).
  116. * Page contents are always saved into "root" directory. Only aliases pages saved with dolSavePageAlias() can be in root or language subdir.
  117. *
  118. * @param string $filetpl Full path of filename to generate
  119. * @param Website $object Object website
  120. * @param WebsitePage $objectpage Object websitepage
  121. * @param int $backupold 1=Make a backup of old page
  122. * @return boolean True if OK
  123. * @see dolSavePageAlias()
  124. */
  125. function dolSavePageContent($filetpl, Website $object, WebsitePage $objectpage, $backupold = 0)
  126. {
  127. global $conf, $db;
  128. // Now create the .tpl file (duplicate code with actions updatesource or updatecontent but we need this to save new header)
  129. dol_syslog("dolSavePageContent We regenerate the tpl page filetpl=".$filetpl);
  130. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  131. if (dol_is_file($filetpl)) {
  132. if ($backupold) {
  133. dol_delete_file($filetpl.'.old');
  134. $result = dol_move($filetpl, $filetpl.'.old', 0, 1, 0, 0);
  135. if (! $result) {
  136. return false;
  137. }
  138. } else {
  139. dol_delete_file($filetpl);
  140. }
  141. }
  142. $shortlangcode = '';
  143. if ($objectpage->lang) {
  144. $shortlangcode = substr($objectpage->lang, 0, 2); // en_US or en-US -> en
  145. }
  146. if (empty($shortlangcode)) {
  147. $shortlangcode = substr($object->lang, 0, 2); // en_US or en-US -> en
  148. }
  149. $tplcontent = '';
  150. $tplcontent .= "<?php // BEGIN PHP\n";
  151. $tplcontent .= '$websitekey=basename(__DIR__); if (empty($websitepagefile)) $websitepagefile=__FILE__;'."\n";
  152. $tplcontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) {\n";
  153. $tplcontent .= ' $pathdepth = count(explode(\'/\', $_SERVER[\'SCRIPT_NAME\'])) - 2;'."\n";
  154. $tplcontent .= ' require_once ($pathdepth ? str_repeat(\'../\', $pathdepth) : \'./\').\'master.inc.php\';'."\n";
  155. $tplcontent .= "} // Not already loaded\n";
  156. $tplcontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
  157. $tplcontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
  158. $tplcontent .= "ob_start();\n";
  159. $tplcontent .= "// END PHP ?>\n";
  160. if (getDolGlobalString('WEBSITE_FORCE_DOCTYPE_HTML5')) {
  161. $tplcontent .= "<!DOCTYPE html>\n";
  162. }
  163. $tplcontent .= '<html'.($shortlangcode ? ' lang="'.$shortlangcode.'"' : '').'>'."\n";
  164. $tplcontent .= '<head>'."\n";
  165. $tplcontent .= '<title>'.dol_string_nohtmltag($objectpage->title, 0, 'UTF-8').'</title>'."\n";
  166. $tplcontent .= '<meta charset="utf-8">'."\n";
  167. $tplcontent .= '<meta http-equiv="content-type" content="text/html; charset=utf-8" />'."\n";
  168. $tplcontent .= '<meta name="robots" content="index, follow" />'."\n";
  169. $tplcontent .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">'."\n";
  170. $tplcontent .= '<meta name="keywords" content="'.dol_string_nohtmltag($objectpage->keywords).'" />'."\n";
  171. $tplcontent .= '<meta name="title" content="'.dol_string_nohtmltag($objectpage->title, 0, 'UTF-8').'" />'."\n";
  172. $tplcontent .= '<meta name="description" content="'.dol_string_nohtmltag($objectpage->description, 0, 'UTF-8').'" />'."\n";
  173. $tplcontent .= '<meta name="generator" content="'.DOL_APPLICATION_TITLE.' '.DOL_VERSION.' (https://www.dolibarr.org)" />'."\n";
  174. $tplcontent .= '<meta name="dolibarr:pageid" content="'.dol_string_nohtmltag($objectpage->id).'" />'."\n";
  175. // Add canonical reference
  176. if ($object->virtualhost) {
  177. $tplcontent .= '<link rel="canonical" href="'.(($objectpage->id == $object->fk_default_home) ? '/' : (($shortlangcode != substr($object->lang, 0, 2) ? '/'.$shortlangcode : '').'/'.$objectpage->pageurl.'.php')).'" />'."\n";
  178. }
  179. // Add translation reference (main language)
  180. if ($object->isMultiLang()) {
  181. // Add page "translation of"
  182. $translationof = $objectpage->fk_page;
  183. if ($translationof) {
  184. $tmppage = new WebsitePage($db);
  185. $tmppage->fetch($translationof);
  186. if ($tmppage->id > 0) {
  187. $tmpshortlangcode = '';
  188. if ($tmppage->lang) {
  189. $tmpshortlangcode = preg_replace('/[_-].*$/', '', $tmppage->lang); // en_US or en-US -> en
  190. }
  191. if (empty($tmpshortlangcode)) {
  192. $tmpshortlangcode = preg_replace('/[_-].*$/', '', $object->lang); // en_US or en-US -> en
  193. }
  194. if ($tmpshortlangcode != $shortlangcode) {
  195. $tplcontent .= '<link rel="alternate" hreflang="'.$tmpshortlangcode.'" href="<?php echo $website->virtualhost; ?>'.($object->fk_default_home == $tmppage->id ? '/' : (($tmpshortlangcode != substr($object->lang, 0, 2)) ? '/'.$tmpshortlangcode : '').'/'.$tmppage->pageurl.'.php').'" />'."\n";
  196. }
  197. }
  198. }
  199. // Add "has translation pages"
  200. $sql = "SELECT rowid as id, lang, pageurl from ".MAIN_DB_PREFIX.'website_page where fk_page IN ('.$db->sanitize($objectpage->id.($translationof ? ", ".$translationof : '')).")";
  201. $resql = $db->query($sql);
  202. if ($resql) {
  203. $num_rows = $db->num_rows($resql);
  204. if ($num_rows > 0) {
  205. while ($obj = $db->fetch_object($resql)) {
  206. $tmpshortlangcode = '';
  207. if ($obj->lang) {
  208. $tmpshortlangcode = preg_replace('/[_-].*$/', '', $obj->lang); // en_US or en-US -> en
  209. }
  210. if ($tmpshortlangcode != $shortlangcode) {
  211. $tplcontent .= '<link rel="alternate" hreflang="'.$tmpshortlangcode.'" href="<?php echo $website->virtualhost; ?>'.($object->fk_default_home == $obj->id ? '/' : (($tmpshortlangcode != substr($object->lang, 0, 2) ? '/'.$tmpshortlangcode : '')).'/'.$obj->pageurl.'.php').'" />'."\n";
  212. }
  213. }
  214. }
  215. } else {
  216. dol_print_error($db);
  217. }
  218. // Add myself
  219. $tplcontent .= '<?php if ($_SERVER["PHP_SELF"] == "'.(($object->fk_default_home == $objectpage->id) ? '/' : (($shortlangcode != substr($object->lang, 0, 2)) ? '/'.$shortlangcode : '')).'/'.$objectpage->pageurl.'.php") { ?>'."\n";
  220. $tplcontent .= '<link rel="alternate" hreflang="'.$shortlangcode.'" href="<?php echo $website->virtualhost; ?>'.(($object->fk_default_home == $objectpage->id) ? '/' : (($shortlangcode != substr($object->lang, 0, 2)) ? '/'.$shortlangcode : '').'/'.$objectpage->pageurl.'.php').'" />'."\n";
  221. $tplcontent .= '<?php } ?>'."\n";
  222. }
  223. // Add manifest.json. Do we have to add it only on home page ?
  224. $tplcontent .= '<?php if ($website->use_manifest) { print \'<link rel="manifest" href="/manifest.json.php" />\'."\n"; } ?>'."\n";
  225. $tplcontent .= '<!-- Include link to CSS file -->'."\n";
  226. // Add js
  227. $tplcontent .= '<link rel="stylesheet" href="/styles.css.php?website=<?php echo $websitekey; ?>" type="text/css" />'."\n";
  228. $tplcontent .= '<!-- Include link to JS file -->'."\n";
  229. $tplcontent .= '<script nonce="'.getNonce().'" async src="/javascript.js.php?website=<?php echo $websitekey; ?>"></script>'."\n";
  230. // Add headers
  231. $tplcontent .= '<!-- Include HTML header from common file -->'."\n";
  232. $tplcontent .= '<?php if (file_exists(DOL_DATA_ROOT."/website/".$websitekey."/htmlheader.html")) include DOL_DATA_ROOT."/website/".$websitekey."/htmlheader.html"; ?>'."\n";
  233. $tplcontent .= '<!-- Include HTML header from page header block -->'."\n";
  234. $tplcontent .= preg_replace('/<\/?html>/ims', '', $objectpage->htmlheader)."\n";
  235. $tplcontent .= '</head>'."\n";
  236. $tplcontent .= '<!-- File generated by Dolibarr website module editor -->'."\n";
  237. $tplcontent .= '<body id="bodywebsite" class="bodywebsite bodywebpage-'.$objectpage->ref.'">'."\n";
  238. $tplcontent .= $objectpage->content."\n";
  239. $tplcontent .= '</body>'."\n";
  240. $tplcontent .= '</html>'."\n";
  241. $tplcontent .= '<?php // BEGIN PHP'."\n";
  242. $tplcontent .= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "html", '.$objectpage->id.'); dolWebsiteIncrementCounter('.$object->id.', "'.$objectpage->type_container.'", '.$objectpage->id.');'."\n";
  243. $tplcontent .= "// END PHP ?>\n";
  244. //var_dump($filetpl);exit;
  245. $result = file_put_contents($filetpl, $tplcontent);
  246. dolChmod($filetpl);
  247. return $result;
  248. }
  249. /**
  250. * Save content of the index.php and/or the wrapper.php page
  251. *
  252. * @param string $pathofwebsite Path of website root
  253. * @param string $fileindex Full path of file index.php
  254. * @param string $filetpl File tpl the index.php page redirect to (used only if $fileindex is provided)
  255. * @param string $filewrapper Full path of file wrapper.php
  256. * @param Website $object Object website
  257. * @return boolean True if OK
  258. */
  259. function dolSaveIndexPage($pathofwebsite, $fileindex, $filetpl, $filewrapper, $object = null)
  260. {
  261. global $conf, $db;
  262. $result1 = false;
  263. $result2 = false;
  264. dol_mkdir($pathofwebsite);
  265. if ($fileindex) {
  266. dol_delete_file($fileindex);
  267. $indexcontent = '<?php'."\n";
  268. $indexcontent .= "// BEGIN PHP File generated to provide an index.php as Home Page or alias redirector - DO NOT MODIFY - It is just a generated wrapper.\n";
  269. $indexcontent .= '$websitekey=basename(__DIR__); if (empty($websitepagefile)) $websitepagefile=__FILE__;'."\n";
  270. $indexcontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once './master.inc.php'; } // Load master if not already loaded\n";
  271. $indexcontent .= 'if (!empty($_GET[\'pageref\']) || !empty($_GET[\'pagealiasalt\']) || !empty($_GET[\'pageid\'])) {'."\n";
  272. $indexcontent .= " require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
  273. $indexcontent .= " require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
  274. $indexcontent .= ' redirectToContainer($_GET[\'pageref\'], $_GET[\'pagealiasalt\'], $_GET[\'pageid\']);'."\n";
  275. $indexcontent .= "}\n";
  276. $indexcontent .= "include_once './".basename($filetpl)."'\n";
  277. $indexcontent .= '// END PHP ?>'."\n";
  278. $result1 = file_put_contents($fileindex, $indexcontent);
  279. dolChmod($fileindex);
  280. if (is_object($object) && $object->fk_default_home > 0) {
  281. $objectpage = new WebsitePage($db);
  282. $objectpage->fetch($object->fk_default_home);
  283. // Create a version for sublanguages
  284. if (empty($objectpage->lang) || !in_array($objectpage->lang, explode(',', $object->otherlang))) {
  285. if (!getDolGlobalString('WEBSITE_DISABLE_MAIN_LANGUAGE_INTO_LANGSUBDIR') && is_object($object) && !empty($object->otherlang)) {
  286. $dirname = dirname($fileindex);
  287. foreach (explode(',', $object->otherlang) as $sublang) {
  288. // Avoid to erase main alias file if $sublang is empty string
  289. if (empty(trim($sublang))) {
  290. continue;
  291. }
  292. $fileindexsub = $dirname.'/'.$sublang.'/index.php';
  293. // Same indexcontent than previously but with ../ instead of ./ for master and tpl file include/require_once.
  294. $relpath = '..';
  295. $indexcontent = '<?php'."\n";
  296. $indexcontent .= "// BEGIN PHP File generated to provide an index.php as Home Page or alias redirector - DO NOT MODIFY - It is just a generated wrapper.\n";
  297. $indexcontent .= '$websitekey=basename(__DIR__); if (empty($websitepagefile)) $websitepagefile=__FILE__;'."\n";
  298. $indexcontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once '".$relpath."/master.inc.php'; } // Load master if not already loaded\n";
  299. $indexcontent .= 'if (!empty($_GET[\'pageref\']) || !empty($_GET[\'pagealiasalt\']) || !empty($_GET[\'pageid\'])) {'."\n";
  300. $indexcontent .= " require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
  301. $indexcontent .= " require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
  302. $indexcontent .= ' redirectToContainer($_GET[\'pageref\'], $_GET[\'pagealiasalt\'], $_GET[\'pageid\']);'."\n";
  303. $indexcontent .= "}\n";
  304. $indexcontent .= "include_once '".$relpath."/".basename($filetpl)."'\n"; // use .. instead of .
  305. $indexcontent .= '// END PHP ?>'."\n";
  306. $result = file_put_contents($fileindexsub, $indexcontent);
  307. if ($result === false) {
  308. dol_syslog("Failed to write file ".$fileindexsub, LOG_WARNING);
  309. }
  310. dolChmod($fileindexsub);
  311. }
  312. }
  313. }
  314. }
  315. } else {
  316. $result1 = true;
  317. }
  318. if ($filewrapper) {
  319. dol_delete_file($filewrapper);
  320. $wrappercontent = file_get_contents(DOL_DOCUMENT_ROOT.'/website/samples/wrapper.php');
  321. $result2 = file_put_contents($filewrapper, $wrappercontent);
  322. dolChmod($filewrapper);
  323. } else {
  324. $result2 = true;
  325. }
  326. return ($result1 && $result2);
  327. }
  328. /**
  329. * Save content of a page on disk
  330. *
  331. * @param string $filehtmlheader Full path of filename to generate
  332. * @param string $htmlheadercontent Content of file
  333. * @return boolean True if OK
  334. */
  335. function dolSaveHtmlHeader($filehtmlheader, $htmlheadercontent)
  336. {
  337. global $conf, $pathofwebsite;
  338. dol_syslog("Save html header into ".$filehtmlheader);
  339. dol_mkdir($pathofwebsite);
  340. $result = file_put_contents($filehtmlheader, $htmlheadercontent);
  341. dolChmod($filehtmlheader);
  342. return $result;
  343. }
  344. /**
  345. * Save content of a page on disk
  346. *
  347. * @param string $filecss Full path of filename to generate
  348. * @param string $csscontent Content of file
  349. * @return boolean True if OK
  350. */
  351. function dolSaveCssFile($filecss, $csscontent)
  352. {
  353. global $conf, $pathofwebsite;
  354. dol_syslog("Save css file into ".$filecss);
  355. dol_mkdir($pathofwebsite);
  356. $result = file_put_contents($filecss, $csscontent);
  357. dolChmod($filecss);
  358. return $result;
  359. }
  360. /**
  361. * Save content of a page on disk. For example into documents/website/mywebsite/javascript.js.php file.
  362. *
  363. * @param string $filejs Full path of filename to generate
  364. * @param string $jscontent Content of file
  365. * @return boolean True if OK
  366. */
  367. function dolSaveJsFile($filejs, $jscontent)
  368. {
  369. global $conf, $pathofwebsite;
  370. dol_syslog("Save js file into ".$filejs);
  371. dol_mkdir($pathofwebsite);
  372. $result = file_put_contents($filejs, $jscontent);
  373. dolChmod($filejs);
  374. return $result;
  375. }
  376. /**
  377. * Save content of a page on disk
  378. *
  379. * @param string $filerobot Full path of filename to generate
  380. * @param string $robotcontent Content of file
  381. * @return boolean True if OK
  382. */
  383. function dolSaveRobotFile($filerobot, $robotcontent)
  384. {
  385. global $conf, $pathofwebsite;
  386. dol_syslog("Save robot file into ".$filerobot);
  387. dol_mkdir($pathofwebsite);
  388. $result = file_put_contents($filerobot, $robotcontent);
  389. dolChmod($filerobot);
  390. return $result;
  391. }
  392. /**
  393. * Save content of a page on disk
  394. *
  395. * @param string $filehtaccess Full path of filename to generate
  396. * @param string $htaccess Content of file
  397. * @return boolean True if OK
  398. */
  399. function dolSaveHtaccessFile($filehtaccess, $htaccess)
  400. {
  401. global $conf, $pathofwebsite;
  402. dol_syslog("Save htaccess file into ".$filehtaccess);
  403. dol_mkdir($pathofwebsite);
  404. $result = file_put_contents($filehtaccess, $htaccess);
  405. dolChmod($filehtaccess);
  406. return $result;
  407. }
  408. /**
  409. * Save content of a page on disk
  410. *
  411. * @param string $file Full path of filename to generate
  412. * @param string $content Content of file
  413. * @return boolean True if OK
  414. */
  415. function dolSaveManifestJson($file, $content)
  416. {
  417. global $conf, $pathofwebsite;
  418. dol_syslog("Save manifest.js.php file into ".$file);
  419. dol_mkdir($pathofwebsite);
  420. $result = file_put_contents($file, $content);
  421. dolChmod($file);
  422. return $result;
  423. }
  424. /**
  425. * Save content of a page on disk
  426. *
  427. * @param string $file Full path of filename to generate
  428. * @param string $content Content of file
  429. * @return boolean True if OK
  430. */
  431. function dolSaveReadme($file, $content)
  432. {
  433. global $conf, $pathofwebsite;
  434. dol_syslog("Save README.md file into ".$file);
  435. dol_mkdir($pathofwebsite);
  436. $result = file_put_contents($file, $content);
  437. dolChmod($file);
  438. return $result;
  439. }
  440. /**
  441. * Save content of a page on disk
  442. *
  443. * @param string $file Full path of filename to generate
  444. * @param string $content Content of file
  445. * @return boolean True if OK
  446. */
  447. function dolSaveLicense($file, $content)
  448. {
  449. global $conf, $pathofwebsite;
  450. dol_syslog("Save LICENSE file into ".$file);
  451. dol_mkdir($pathofwebsite);
  452. $result = file_put_contents($file, $content);
  453. dolChmod($file);
  454. return $result;
  455. }
  456. /**
  457. * Show list of themes. Show all thumbs of themes/skins
  458. *
  459. * @param Website $website Object website to load the template into
  460. * @return void
  461. */
  462. function showWebsiteTemplates(Website $website)
  463. {
  464. global $conf, $langs, $db, $form, $user;
  465. $dirthemes = array('/doctemplates/websites');
  466. if (!empty($conf->modules_parts['websitetemplates'])) { // Using this feature slow down application
  467. foreach ($conf->modules_parts['websitetemplates'] as $reldir) {
  468. $dirthemes = array_merge($dirthemes, (array) ($reldir.'doctemplates/websites'));
  469. }
  470. }
  471. $dirthemes = array_unique($dirthemes);
  472. // Now dir_themes=array('/themes') or dir_themes=array('/theme','/mymodule/theme')
  473. $colspan = 2;
  474. print '<!-- For website template import -->'."\n";
  475. print '<table class="noborder centpercent">';
  476. // Title
  477. print '<tr class="liste_titre"><th class="titlefield">';
  478. print $form->textwithpicto($langs->trans("Templates"), $langs->trans("ThemeDir").' : '.join(", ", $dirthemes));
  479. print ' ';
  480. print '<a href="'.$_SERVER["PHP_SELF"].'?website='.urlencode($website->ref).'&importsite=1" target="_blank" rel="noopener noreferrer external">';
  481. print img_picto('', 'refresh');
  482. print '</a>';
  483. print '</th>';
  484. print '<th class="right">';
  485. $url = 'https://www.dolistore.com/43-web-site-templates';
  486. print '<a href="'.$url.'" target="_blank" rel="noopener noreferrer external">';
  487. print img_picto('', 'globe', 'class="pictofixedwidth"').$langs->trans('DownloadMoreSkins');
  488. print '</a>';
  489. print '</th></tr>';
  490. print '<tr><td colspan="'.$colspan.'">';
  491. print '<table class="nobordernopadding centpercent"><tr><td><div class="center">';
  492. if (count($dirthemes)) {
  493. $i = 0;
  494. foreach ($dirthemes as $dir) {
  495. //print $dirroot.$dir;exit;
  496. $dirtheme = DOL_DATA_ROOT.$dir; // This include loop on $conf->file->dol_document_root
  497. if (is_dir($dirtheme)) {
  498. $handle = opendir($dirtheme);
  499. if (is_resource($handle)) {
  500. while (($subdir = readdir($handle)) !== false) {
  501. if (is_file($dirtheme."/".$subdir) && substr($subdir, 0, 1) != '.' && substr($subdir, 0, 3) != 'CVS' && preg_match('/\.zip$/i', $subdir)) {
  502. $subdirwithoutzip = preg_replace('/\.zip$/i', '', $subdir);
  503. // Disable not stable themes (dir ends with _exp or _dev)
  504. if (getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2 && preg_match('/_dev$/i', $subdir)) {
  505. continue;
  506. }
  507. if (getDolGlobalInt('MAIN_FEATURES_LEVEL') < 1 && preg_match('/_exp$/i', $subdir)) {
  508. continue;
  509. }
  510. print '<div class="inline-block" style="margin-top: 10px; margin-bottom: 10px; margin-right: 20px; margin-left: 20px;">';
  511. $templatedir = $dirtheme."/".$subdir;
  512. $file = $dirtheme."/".$subdirwithoutzip.".jpg";
  513. $url = DOL_URL_ROOT.'/viewimage.php?modulepart=doctemplateswebsite&file='.$subdirwithoutzip.".jpg";
  514. if (!file_exists($file)) {
  515. $url = DOL_URL_ROOT.'/public/theme/common/nophoto.png';
  516. }
  517. $originalfile = basename($file);
  518. $entity = $conf->entity;
  519. $modulepart = 'doctemplateswebsite';
  520. $cache = '';
  521. $title = $file;
  522. $ret = '';
  523. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 1, '&entity='.$entity);
  524. if (!empty($urladvanced)) {
  525. $ret .= '<a class="'.$urladvanced['css'].'" target="'.$urladvanced['target'].'" mime="'.$urladvanced['mime'].'" href="'.$urladvanced['url'].'">';
  526. } else {
  527. $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.urlencode($modulepart).'&entity='.((int) $entity).'&file='.urlencode($originalfile).'&cache='.((int) $cache).'">';
  528. }
  529. print $ret;
  530. print '<img class="img-skinthumb shadow" src="'.$url.'" border="0" alt="'.$title.'" title="'.$title.'" style="margin-bottom: 5px;">';
  531. print '</a>';
  532. print '<br>';
  533. print $subdir;
  534. print '<br>';
  535. print '<span class="opacitymedium">'.dol_print_size(dol_filesize($dirtheme."/".$subdir), 1, 1).' - '.dol_print_date(dol_filemtime($templatedir), 'dayhour', 'tzuserrel').'</span>';
  536. if ($user->hasRight('website', 'delete')) {
  537. print ' <a href="'.$_SERVER["PHP_SELF"].'?action=deletetemplate&token='.newToken().'&website='.urlencode($website->ref).'&templateuserfile='.urlencode($subdir).'">'.img_picto('', 'delete').'</a>';
  538. }
  539. print '<br><a href="'.$_SERVER["PHP_SELF"].'?action=importsiteconfirm&token='.newToken().'&website='.urlencode($website->ref).'&templateuserfile='.urlencode($subdir).'" class="button">'.$langs->trans("Load").'</a>';
  540. print '</div>';
  541. $i++;
  542. }
  543. }
  544. }
  545. }
  546. }
  547. } else {
  548. print '<span class="opacitymedium">'.$langs->trans("None").'</span>';
  549. }
  550. print '</div></td></tr></table>';
  551. print '</td></tr>';
  552. print '</table>';
  553. }
  554. /**
  555. * Check a new string containing only php code (including <php tag)
  556. * - Block if bad code in the new string.
  557. * - Block also if user has no permission to change PHP code.
  558. *
  559. * @param string $phpfullcodestringold PHP old string. For exemple "<?php echo 'a' ?><php echo 'b' ?>"
  560. * @param string $phpfullcodestring PHP new string. For exemple "<?php echo 'a' ?><php echo 'c' ?>"
  561. * @return int Error or not
  562. * @see dolKeepOnlyPhpCode()
  563. */
  564. function checkPHPCode($phpfullcodestringold, $phpfullcodestring)
  565. {
  566. global $conf, $langs, $user;
  567. $error = 0;
  568. if (empty($phpfullcodestringold) && empty($phpfullcodestring)) {
  569. return 0;
  570. }
  571. // First check forbidden commands
  572. $forbiddenphpcommands = array();
  573. if (!getDolGlobalString('WEBSITE_PHP_ALLOW_EXEC')) { // If option is not on, we disallow functions to execute commands
  574. $forbiddenphpcommands = array("exec", "passthru", "shell_exec", "system", "proc_open", "popen", "eval", "dol_eval", "executeCLI");
  575. }
  576. if (!getDolGlobalString('WEBSITE_PHP_ALLOW_WRITE')) { // If option is not on, we disallow functions to write files
  577. $forbiddenphpcommands = array_merge($forbiddenphpcommands, array("fopen", "file_put_contents", "fputs", "fputscsv", "fwrite", "fpassthru", "unlink", "mkdir", "rmdir", "symlink", "touch", "umask"));
  578. }
  579. foreach ($forbiddenphpcommands as $forbiddenphpcommand) {
  580. if (preg_match('/'.$forbiddenphpcommand.'\s*\(/ms', $phpfullcodestring)) {
  581. $error++;
  582. setEventMessages($langs->trans("DynamicPHPCodeContainsAForbiddenInstruction", $forbiddenphpcommand), null, 'errors');
  583. break;
  584. }
  585. }
  586. // This char can be used to execute RCE for example using with echo `ls`
  587. $forbiddenphpchars = array();
  588. if (!getDolGlobalString('WEBSITE_PHP_ALLOW_DANGEROUS_CHARS')) { // If option is not on, we disallow functions to execute commands
  589. $forbiddenphpchars = array("`");
  590. }
  591. foreach ($forbiddenphpchars as $forbiddenphpchar) {
  592. if (preg_match('/'.$forbiddenphpchar.'/ms', $phpfullcodestring)) {
  593. $error++;
  594. setEventMessages($langs->trans("DynamicPHPCodeContainsAForbiddenInstruction", $forbiddenphpchar), null, 'errors');
  595. break;
  596. }
  597. }
  598. // Deny dynamic functions '${a}(' or '$a[b](' - So we refuse '}(' and ']('
  599. if (preg_match('/[}\]]\(/ims', $phpfullcodestring)) {
  600. $error++;
  601. setEventMessages($langs->trans("DynamicPHPCodeContainsAForbiddenInstruction", ']('), null, 'errors');
  602. }
  603. // Deny dynamic functions $xxx(
  604. if (preg_match('/\$[a-z0-9_]+\(/ims', $phpfullcodestring)) {
  605. $error++;
  606. setEventMessages($langs->trans("DynamicPHPCodeContainsAForbiddenInstruction", '$...('), null, 'errors');
  607. }
  608. if ($phpfullcodestringold != $phpfullcodestring) {
  609. if (!$error && !$user->hasRight('website', 'writephp')) {
  610. $error++;
  611. setEventMessages($langs->trans("NotAllowedToAddDynamicContent"), null, 'errors');
  612. }
  613. if (!$error) {
  614. $dolibarrdataroot = preg_replace('/([\\/]+)$/i', '', DOL_DATA_ROOT);
  615. $allowimportsite = true;
  616. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  617. if (dol_is_file($dolibarrdataroot.'/installmodules.lock')) {
  618. $allowimportsite = false;
  619. }
  620. if (!$allowimportsite) {
  621. $error++;
  622. // Blocked by installmodules.lock
  623. if (getDolGlobalString('MAIN_MESSAGE_INSTALL_MODULES_DISABLED_CONTACT_US')) {
  624. // Show clean corporate message
  625. $message = $langs->trans('InstallModuleFromWebHasBeenDisabledContactUs');
  626. } else {
  627. // Show technical generic message
  628. $message = $langs->trans("InstallModuleFromWebHasBeenDisabledByFile", $dolibarrdataroot.'/installmodules.lock');
  629. }
  630. setEventMessages($message, null, 'errors');
  631. }
  632. }
  633. }
  634. return $error;
  635. }