dolibarr 25.0.0-alpha
website2.lib.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
32function dolSaveMasterFile($filemaster)
33{
34 // Now generate the master.inc.php page
35 dol_syslog("We regenerate the master.inc.php file");
36
37 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
38
39 dol_delete_file($filemaster);
40
41 $mastercontent = '<?php'."\n";
42 $mastercontent .= '// File generated to link to the master file - DO NOT MODIFY - It is just an include'."\n";
43 $mastercontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) {\n";
44 $mastercontent .= " if (! defined('USEEXTERNALSERVER')) define('USEEXTERNALSERVER', 1);\n";
45 $mastercontent .= " require_once '".DOL_DOCUMENT_ROOT."/master.inc.php';\n";
46 $mastercontent .= "}\n";
47 $mastercontent .= '?>'."\n";
48 $result = file_put_contents($filemaster, $mastercontent);
49 dolChmod($filemaster);
50
51 return $result;
52}
53
64function dolSavePageAlias($filealias, $object, $objectpage)
65{
66 // Now create the .tpl file
67 dol_syslog("dolSavePageAlias We regenerate the alias page filealias=".$filealias." and a wrapper into all language subdirectories");
68
69 $aliascontent = '<?php'."\n";
70 $aliascontent .= "// File generated to wrap the alias page - DO NOT MODIFY - It is just a wrapper to real page\n";
71 $aliascontent .= 'global $dolibarr_main_data_root;'."\n";
72 $aliascontent .= 'if (empty($dolibarr_main_data_root)) $res=include \'./page'.$objectpage->id.'.tpl.php\'; ';
73 $aliascontent .= 'else $res=include $dolibarr_main_data_root.\'/website/\'.$website->ref.\'/page'.$objectpage->id.'.tpl.php\';'."\n";
74 $aliascontent .= 'if ($res === false) { http_response_code(500); print \'Failed to make include\'; }'."\n";
75 $aliascontent .= '?>'."\n";
76 $result = file_put_contents($filealias, $aliascontent);
77 if ($result === false) {
78 dol_syslog("Failed to write file ".$filealias, LOG_WARNING);
79 }
80 dolChmod($filealias);
81
82 // Save also alias into language subdirectory if it is not a main language
83 if ($objectpage->lang && in_array($objectpage->lang, explode(',', $object->otherlang))) {
84 $dirname = dirname($filealias);
85 $filename = basename($filealias);
86 $filealiassub = $dirname.'/'.$objectpage->lang.'/'.$filename;
87
88 dol_mkdir($dirname.'/'.$objectpage->lang, DOL_DATA_ROOT);
89
90 $aliascontent = '<?php'."\n";
91 $aliascontent .= "// File generated to wrap the alias page - DO NOT MODIFY - It is just a wrapper to real page\n";
92 $aliascontent .= 'global $dolibarr_main_data_root;'."\n";
93 $aliascontent .= 'if (empty($dolibarr_main_data_root)) $res=include \'../page'.$objectpage->id.'.tpl.php\'; ';
94 $aliascontent .= 'else $res=include $dolibarr_main_data_root.\'/website/\'.$website->ref.\'/page'.$objectpage->id.'.tpl.php\';'."\n";
95 $aliascontent .= 'if ($res === false) { http_response_code(500); print \'Failed to make include\'; }'."\n";
96 $aliascontent .= '?>'."\n";
97 $result = file_put_contents($filealiassub, $aliascontent);
98 if ($result === false) {
99 dol_syslog("Failed to write file ".$filealiassub, LOG_WARNING);
100 }
101 dolChmod($filealiassub);
102 } elseif (empty($objectpage->lang) || !in_array($objectpage->lang, explode(',', $object->otherlang))) {
103 // Save also alias into all language subdirectories if it is a main language
104 if (!getDolGlobalString('WEBSITE_DISABLE_MAIN_LANGUAGE_INTO_LANGSUBDIR') && !empty($object->otherlang)) {
105 $dirname = dirname($filealias);
106 $filename = basename($filealias);
107 foreach (explode(',', $object->otherlang) as $sublang) {
108 // Avoid to erase main alias file if $sublang is empty string
109 if (empty(trim($sublang))) {
110 continue;
111 }
112 $filealiassub = $dirname.'/'.$sublang.'/'.$filename;
113
114 $aliascontent = '<?php'."\n";
115 $aliascontent .= "// File generated to wrap the alias page - DO NOT MODIFY - It is just a wrapper to real page\n";
116 $aliascontent .= 'global $dolibarr_main_data_root;'."\n";
117 $aliascontent .= 'if (empty($dolibarr_main_data_root)) $res=include \'../page'.$objectpage->id.'.tpl.php\'; ';
118 $aliascontent .= 'else $res=include $dolibarr_main_data_root.\'/website/\'.$website->ref.\'/page'.$objectpage->id.'.tpl.php\';'."\n";
119 $aliascontent .= 'if ($res === false) { http_response_code(500); print \'Failed to make include\'; }'."\n";
120 $aliascontent .= '?>'."\n";
121
122 dol_mkdir($dirname.'/'.$sublang);
123 $result = file_put_contents($filealiassub, $aliascontent);
124 if ($result === false) {
125 dol_syslog("Failed to write file ".$filealiassub, LOG_WARNING);
126 }
127 dolChmod($filealiassub);
128 }
129 }
130 }
131
132 return ($result ? true : false);
133}
134
135
147function dolSavePageContent($filetpl, Website $object, WebsitePage $objectpage, $backupold = 0)
148{
149 global $conf, $db;
150
151 // Now create the .tpl file (duplicate code with actions updatesource or updatecontent but we need this to save new header)
152 dol_syslog("dolSavePageContent We regenerate the tpl page filetpl=".$filetpl);
153
154 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
155
156 if (dol_is_file($filetpl)) {
157 if ($backupold) {
158 $result = archiveOrBackupFile($filetpl);
159 if (! $result) {
160 return false;
161 }
162 } else {
163 dol_delete_file($filetpl);
164 }
165 }
166
167 $shortlangcode = '';
168 if ($objectpage->lang) {
169 $shortlangcode = substr($objectpage->lang, 0, 2); // en_US or en-US -> en
170 }
171 if (empty($shortlangcode)) {
172 // Take the language of website
173 $shortlangcode = substr($object->lang, 0, 2); // en_US or en-US -> en
174 }
175
176 if (!empty($objectpage->type_container) && in_array($objectpage->type_container, array('library', 'service'))) {
177 $originalcontentonly = 1;
178 }
179
180 $tplcontent = '';
181 if (!isset($originalcontentonly)) {
182 // If we want to generate a page with some code to manage PHP content
183 $tplcontent .= "<?php // BEGIN PHP\n";
184 $tplcontent .= '$websitekey=basename(__DIR__); if (empty($websitepagefile)) $websitepagefile=__FILE__;'."\n";
185 $tplcontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) {\n";
186 $tplcontent .= ' $pathdepth = count(explode(\'/\', $_SERVER[\'SCRIPT_NAME\'])) - 2;'."\n";
187 $tplcontent .= ' require_once ($pathdepth ? str_repeat(\'../\', $pathdepth) : \'./\').\'master.inc.php\';'."\n";
188 if ($objectpage->disable_waf != 'all') {
189 if (strpos($objectpage->disable_waf, 'NOSCANAUDIOFORINJECTION') !== false) {
190 $tplcontent .= ' define(\'NOSCANAUDIOFORINJECTION\', 1);'."\n";
191 }
192 if (strpos($objectpage->disable_waf, 'NOSCANIFRAMEFORINJECTION') !== false) {
193 $tplcontent .= ' define(\'NOSCANIFRAMEFORINJECTION\', 1);'."\n";
194 }
195 if (strpos($objectpage->disable_waf, 'NOSCANOBJECTFORINJECTION') !== false) {
196 $tplcontent .= ' define(\'NOSCANOBJECTFORINJECTION\', 1);'."\n";
197 }
198 $tplcontent .= ' require_once DOL_DOCUMENT_ROOT.\'/waf.inc.php\';'."\n";
199 }
200 $tplcontent .= "}\n";
201 $tplcontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
202 $tplcontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
203 if (in_array($objectpage->type_container, array('page', 'blogpost', 'service'))) {
204 $tplcontent .= 'dol_syslog("--- Prepare content of page '.((int) $objectpage->id).' - '.preg_replace('/[^\w_-]/', '', $objectpage->pageurl).'");'."\n";
205 }
206 $tplcontent .= "ob_start();\n";
207 $tplcontent .= "try {\n";
208 $tplcontent .= "// END PHP ?>\n";
209 if (getDolGlobalString('WEBSITE_FORCE_DOCTYPE_HTML5')) {
210 $tplcontent .= "<!DOCTYPE html>\n";
211 }
212 // If a language was forced on page, we use it, else we use the lang of visitor else the lang of web site
213 $tplcontent .= '<html'.($objectpage->lang ? ' lang="'.preg_replace('/[^a-z]/i', '', substr($objectpage->lang, 0, 2)).'"' : '<?php echo $weblangs->shortlang ? \' lang="\'.$weblangs->shortlang.\'"\' : \'\' ?>').'>'."\n";
214 $tplcontent .= '<head>'."\n";
215 $tplcontent .= '<title>'.dol_string_nohtmltag($objectpage->title, 1, 'UTF-8').'</title>'."\n";
216 $tplcontent .= '<meta charset="utf-8">'."\n";
217 $tplcontent .= '<meta http-equiv="content-type" content="text/html; charset=utf-8" />'."\n";
218 $tplcontent .= '<meta name="robots" content="'.($objectpage->index ? 'index' : 'noindex').', '.($objectpage->follow ? 'follow' : 'nofollow').'" />'."\n";
219 $tplcontent .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">'."\n";
220 $tplcontent .= '<meta name="keywords" content="'.dol_string_nohtmltag($objectpage->keywords, 1, 'UTF-8').'" />'."\n";
221 $tplcontent .= '<meta name="title" content="'.dol_string_nohtmltag($objectpage->title, 1, 'UTF-8').'" />'."\n";
222 $tplcontent .= '<meta name="description" content="'.dol_string_nohtmltag($objectpage->description, 1, 'UTF-8').'" />'."\n";
223 $tplcontent .= '<meta name="generator" content="'.DOL_APPLICATION_TITLE.' '.DOL_VERSION.' (https://www.dolibarr.org)" />'."\n";
224 $tplcontent .= '<meta name="dolibarr:pageid" content="'.((int) $objectpage->id).'" />'."\n";
225
226 // Add favicon if not already done in htmlheader
227 $htmldeaderindestdir = dol_sanitizePathName($conf->website->dir_temp.'/'.$object->ref.'/containers/htmlheader.html');
228 $htmlheader = file_get_contents($htmldeaderindestdir);
229 if (in_array($objectpage->type_container, array('page', 'blogpost')) && !preg_match('/'.preg_quote('rel="icon"', '/').'/', $htmlheader)) {
230 $tplcontent .= '<link rel="icon" type="image/png" href="/favicon.png" />'."\n";
231 }
232
233 $listofaltlang = $object->otherlang;
234
235 // Note: $object is website, $objectpage is website page
236 if ($object->virtualhost) {
237 // Add the link of the canonical reference
238 $canonicalurladdidlang = '';
239 if ($objectpage->lang) { // A language is forced on the page, it means we may have other language files with hard links into properties of page
240 $canonicalurl = (($objectpage->id == $object->fk_default_home) ? '/' : (($shortlangcode != substr($object->lang, 0, 2) ? '/'.$shortlangcode : '').'/'.$objectpage->pageurl.'.php'));
241 } else { // No language forced, it means the canonical is the one with params making url unique
242 $canonicalurl = '/'.$objectpage->pageurl.'.php';
243
244 if ($object->lang && $listofaltlang) {
245 // Add parameter ID required to be unique/canonical
246 $canonicalurladdidlang = '?__SEO_CANONICAL_URL_PARAMS__';
247 $canonicalurladdidlang .= '&l=__SEO_CANONICAL_LANG__';
248 } else {
249 // Add parameter ID required to be unique/canonical
250 $canonicalurladdidlang = '?__SEO_CANONICAL_URL_PARAMS__';
251 }
252 }
253
254 $tplcontent .= '<link rel="canonical" href="<?php echo $website->virtualhost; ?>'.$canonicalurl.$canonicalurladdidlang.'" />'."\n";
255
256 // Add the link of alternate translation reference
257 if ($listofaltlang) { // If website has other languages to support
258 if ($objectpage->lang) { // A language is forced on the page, it means we may have other language files with hard links into properties of page
259 // Add page "translation of"
260 $translationof = $objectpage->fk_page;
261 if ($translationof) {
262 $tmppage = new WebsitePage($db);
263 $tmppage->fetch($translationof);
264 if ($tmppage->id > 0) {
265 $tmpshortlangcode = '';
266 if ($tmppage->lang) {
267 $tmpshortlangcode = preg_replace('/[_-].*$/', '', $tmppage->lang); // en_US or en-US -> en
268 }
269 if (empty($tmpshortlangcode)) {
270 $tmpshortlangcode = preg_replace('/[_-].*$/', '', $object->lang); // en_US or en-US -> en
271 }
272 if ($tmpshortlangcode != $shortlangcode) {
273 $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";
274 }
275 }
276 }
277
278 // Add "has translation pages"
279 $sql = "SELECT rowid as id, lang, pageurl from ".MAIN_DB_PREFIX.'website_page where fk_page IN ('.$db->sanitize($objectpage->id.($translationof ? ", ".$translationof : '')).")";
280 $resql = $db->query($sql);
281 if ($resql) {
282 $num_rows = $db->num_rows($resql);
283 if ($num_rows > 0) {
284 while ($obj = $db->fetch_object($resql)) {
285 $tmpshortlangcode = '';
286 if ($obj->lang) {
287 $tmpshortlangcode = preg_replace('/[_-].*$/', '', $obj->lang); // en_US or en-US -> en
288 }
289 if ($tmpshortlangcode != $shortlangcode) {
290 $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";
291 }
292 }
293 }
294 } else {
295 dol_print_error($db);
296 }
297
298 // Add myself
299 $tplcontent .= '<?php if ($_SERVER["PHP_SELF"] == "'.(($object->fk_default_home == $objectpage->id) ? '/' : (($shortlangcode != substr($object->lang, 0, 2)) ? '/'.$shortlangcode : '')).'/'.$objectpage->pageurl.'.php") { ?>'."\n";
300 $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";
301
302 $tplcontent .= '<?php } ?>'."\n";
303 } else { // No language forced, it means the canonical is the one withparams making url unique
304 $canonicalurl = '/'.$objectpage->pageurl.'.php';
305 $arrayofaltlang = explode(',', $listofaltlang);
306
307 foreach ($arrayofaltlang as $altlang) {
308 // Add parameter ID required to be unique/canonical
309 $canonicalurladdidlang = '?__SEO_CANONICAL_URL_PARAMS__';
310 $canonicalurladdidlang .= '&l='.$altlang;
311 $tplcontent .= '<link rel="alternate" hreflang="'.$altlang.'" href="<?php echo $website->virtualhost; ?>'.$canonicalurl.$canonicalurladdidlang.'" />'."\n";
312 }
313
314 $tmpshortlangcode = preg_replace('/[_-].*$/', '', $object->lang); // en_US or en-US -> en
315 $canonicalurladdidlang = '?__SEO_CANONICAL_URL_PARAMS__';
316 $canonicalurladdidlang .= '&l='.$tmpshortlangcode;
317 $tplcontent .= '<link rel="alternate" hreflang="'.$tmpshortlangcode.'" href="<?php echo $website->virtualhost; ?>'.$canonicalurl.$canonicalurladdidlang.'" />'."\n";
318 }
319 }
320 }
321
322 // Add manifest.json. Do we have to add it only on home page ?
323 $tplcontent .= '<?php if ($website->use_manifest) { print \'<link rel="manifest" href="/manifest.json.php" />\'."\n"; } ?>'."\n";
324
325 // Add HTML headers (must be before the Add of the common CSS and js). The common js may content javascript using jquery or a framework loaded by the HTML header.
326 $tplcontent .= '<!-- Include HTML header from common file -->'."\n";
327 $tplcontent .= '<?php if (file_exists(DOL_DATA_ROOT."/website/".$websitekey."/htmlheader.html")) include DOL_DATA_ROOT."/website/".$websitekey."/htmlheader.html"; ?>'."\n";
328 $tplcontent .= '<!-- Include HTML header from page header block -->'."\n";
329 $tplcontent .= preg_replace('/<\/?html>/ims', '', $objectpage->htmlheader)."\n";
330
331 // Add css
332 $tplcontent .= '<!-- Include link to common CSS file -->'."\n";
333 $tplcontent .= '<link rel="stylesheet" href="/styles.css.php?website=<?php echo $websitekey; ?>" type="text/css" />'."\n";
334
335 // Add js
336 $tplcontent .= '<!-- Include link to common JS file -->'."\n";
337 $tplcontent .= '<script nonce="'.getNonce().'" async src="/javascript.js.php?website=<?php echo $websitekey; ?>"></script>'."\n";
338 $tplcontent .= '</head>'."\n";
339 $tplcontent .= "\n";
340
341 // Page content
342 $tplcontent .= '<!-- File content defined in Dolibarr website module editor -->'."\n";
343 $tplcontent .= '<body id="bodywebsite" class="bodywebsite bodywebpage-'.$objectpage->ref.'">'."\n";
344
345 // Import necessary environment for the config page
346 if ($objectpage->type_container == 'setup') {
347 $content = '';
348 $content .= '<?php'."\n";
349 $content .= 'require_once DOL_DOCUMENT_ROOT.\'/core/class/html.formsetup.class.php\';'."\n";
350 $content .= '$formSetup = new FormSetup($db);'."\n";
351 $content .= '?>'."\n";
352 $tplcontent .= $content."\n";
353 }
354
355 $tplcontent .= $objectpage->content."\n";
356
357 // Add logic to handle view and actions for managing parameters in the special config page
358 if ($objectpage->type_container == 'setup') {
359 $content = '<div id="websitetemplateconfigpage">'."\n";
360 $content .= '<?php'."\n";
361 $content .= '/*' . "\n";
362 $content .= ' * Actions' . "\n";
363 $content .= ' */' . "\n";
364 $content .= '$websitetemplateconf = GETPOSTINT(\'websitetemplateconf\');' . "\n";
365 $content .= 'include DOL_DOCUMENT_ROOT.\'/core/actions_setmoduleoptions.inc.php\';' . "\n";
366 $content .= '' . "\n";
367 $content .= '/*' . "\n";
368 $content .= ' * View' . "\n";
369 $content .= ' */' . "\n";
370 $content .= 'print load_fiche_titre($langs->trans(\'SetupAndProperties\'), \'\', \'title_setup\');' . "\n";
371 $content .= '' . "\n";
372 $content .= 'if (!empty($message)) {' . "\n";
373 $content .= ' print $message;' . "\n";
374 $content .= '}' . "\n";
375 $content .= '' . "\n";
376 $content .= 'if (!empty($formSetup->items)) {' . "\n";
377 $content .= ' $html = \'\';' . "\n";
378 $content .= '' . "\n";
379 $content .= ' $html .= \'<form action="config.php" method="POST">\';' . "\n";
380 $content .= ' // Generate hidden values from $formSetup->formHiddenInputs' . "\n";
381 $content .= ' if (!empty($formSetup->formHiddenInputs) && is_array($formSetup->formHiddenInputs)) {' . "\n";
382 $content .= ' foreach ($formSetup->formHiddenInputs as $hiddenKey => $hiddenValue) {' . "\n";
383 $content .= ' $html .= \'<input type="hidden" name="\' . dol_escape_htmltag($hiddenKey) . \'" value="\' . dol_escape_htmltag($hiddenValue) . \'">\';' . "\n";
384 $content .= ' }' . "\n";
385 $content .= ' }' . "\n";
386 $content .= '' . "\n";
387 $content .= ' // Generate output table' . "\n";
388 $content .= ' $html .= $formSetup->generateTableOutput(true);' . "\n";
389 $content .= '' . "\n";
390 $content .= ' // Submit button' . "\n";
391 $content .= ' $html .= \'<input type="hidden" name="action" value="preview">\';' . "\n";
392 $content .= ' $html .= \'<input type="hidden" name="websitetemplateconf" value="1">\';' . "\n";
393 $content .= ' $html .= \'<br>\';' . "\n";
394 $content .= ' $html .= \'<div class="form-setup-button-container center">\';' . "\n";
395 $content .= ' $html .= \'<input class="button button-submit" type="submit" value="\' . $langs->trans("Save") . \'">\';' . "\n";
396 $content .= ' $html .= \'</div>\';' . "\n";
397 $content .= ' $html .= \'</form>\';' . "\n";
398 $content .= '' . "\n";
399 $content .= ' print $html;' . "\n";
400 $content .= '}' . "\n";
401 $content .= '?>' . "\n";
402 $content .= '</div>' . "\n";
403 $tplcontent .= $content."\n";
404 }
405
406
407 $tplcontent .= '</body>'."\n";
408 $tplcontent .= '</html>'."\n";
409
410 $tplcontent .= '<?php // BEGIN PHP'."\n";
411 $tplcontent .= '} catch(Exception $e) { print $e->getMessage(); }'."\n";
412 $tplcontent .= '$tmp = ob_get_contents(); ob_end_clean();'."\n"; // replace with ob_get_clean ?
413
414 $tplcontent .= "// Now fix the content for SEO or multilanguage\n";
415 // Old method for custom SEO
416 if (strpos($objectpage->content, '$__PAGE__KEYWORDS__') !== false) {
417 $tplcontent .= '$tmp = preg_replace("/^<meta name=\"keywords\" content=\".*?\" \/>/ms", "<meta name=\"keywords\" content=\"" . dolPrintHTMLForAttribute($__PAGE__KEYWORDS__ ?? "", 1) . "\" />", $tmp);'."\n";
418 }
419 if (strpos($objectpage->content, '$__PAGE__TITLE__') !== false) {
420 $tplcontent .= '$tmp = preg_replace("/^<title>.*?<\/title>/ms", "<title>" . dolPrintHTMLForAttribute($__PAGE__TITLE__ ?? "", 1) . "</title>", $tmp);'."\n";
421 $tplcontent .= '$tmp = preg_replace("/^<meta name=\"title\" content=\".*?\" \/>/ms", "<meta name=\"title\" content=\"" . dolPrintHTMLForAttribute($__PAGE__TITLE__ ?? "", 1) . "\" />", $tmp);'."\n";
422 }
423 if (strpos($objectpage->content, '$__PAGE__DESC__') !== false) {
424 $tplcontent .= '$tmp = preg_replace("/^<meta name=\"description\" content=\".*?\" \/>/ms", "<meta name=\"description\" content=\"" . dolPrintHTMLForAttribute($__PAGE__DESC__ ?? "", 1) . "\" />", $tmp);'."\n";
425 }
426 // New method for custom SEO
427 if (strpos($objectpage->content, 'define("__SEO_PAGE_LANG__"') !== false) {
428 $tmpshortlangcode = preg_replace('/[_-].*$/', '', $object->lang); // en_US or en-US -> en
429 $tplcontent .= '$tmp = preg_replace("/^<html lang=\"[a-z]+\"/ms", "<html lang=\"" . dolPrintHTMLForAttribute(defined("__SEO_PAGE_LANG__") ? preg_replace(\'/\[_-\].*$/\', "", constant("__SEO_PAGE_LANG__")) : (empty($weblangs->shortlang) ? "'.$tmpshortlangcode.'" : $weblangs->shortlang), 1) . "\"", $tmp);'."\n";
430 }
431 if (strpos($objectpage->content, 'define("__SEO_PAGE_KEYWORDS__"') !== false) {
432 $tplcontent .= '$tmp = preg_replace("/^<meta name=\"keywords\" content=\".*?\" \/>/ms", "<meta name=\"keywords\" content=\"" . dolPrintHTMLForAttribute(constant("__SEO_PAGE_KEYWORDS__"), 1) . "\" />", $tmp);'."\n";
433 }
434 if (strpos($objectpage->content, 'define("__SEO_PAGE_TITLE__"') !== false) {
435 $tplcontent .= '$tmp = preg_replace("/^<title>.*?<\/title>/ms", "<title>" . dolPrintHTMLForAttribute(defined("__SEO_PAGE_TITLE__") ? constant("__SEO_PAGE_TITLE__") : "", 1) . "</title>", $tmp);'."\n";
436 $tplcontent .= '$tmp = preg_replace("/^<meta name=\"title\" content=\".*?\" \/>/ms", "<meta name=\"title\" content=\"" . dolPrintHTMLForAttribute(defined("__SEO_PAGE_TITLE__") ? constant("__SEO_PAGE_TITLE__") : "", 1) . "\" />", $tmp);'."\n";
437 }
438 if (strpos($objectpage->content, 'define("__SEO_PAGE_DESC__"') !== false) {
439 $tplcontent .= '$tmp = preg_replace("/^<meta name=\"description\" content=\".*?\" \/>/ms", "<meta name=\"description\" content=\"" . dolPrintHTMLForAttribute(constant("__SEO_PAGE_DESC__"), 1) . "\" />", $tmp);'."\n";
440 }
441 if (empty($objectpage->lang)) { // We may need to use param into the canonical url
442 $tplcontent .= 'defined("__SEO_CANONICAL_URL_PARAMS__") ? ($tmp = preg_replace("/__SEO_CANONICAL_URL_PARAMS__/", dolPrintHTMLForAttributeUrl(constant("__SEO_CANONICAL_URL_PARAMS__")), $tmp)) : ($tmp = preg_replace("/\?__SEO_CANONICAL_URL_PARAMS__\"/", "\"", preg_replace("/\?__SEO_CANONICAL_URL_PARAMS__&/", "?", $tmp)));'."\n";
443
444 $tmpshortlangcode = preg_replace('/[_-].*$/', '', $object->lang); // en_US or en-US -> en
445 $tplcontent .= '$tmp = preg_replace("/__SEO_CANONICAL_LANG__/", (defined("__SEO_PAGE_LANG__") ? preg_replace(\'/\[_-\].*$/\', "", constant("__SEO_PAGE_LANG__")) : (empty($weblangs->shortlang) ? "'.$tmpshortlangcode.'" : $weblangs->shortlang)), $tmp);'."\n";
446 }
447
448 // Let modules rewrite the final page content (e.g. canonical/hreflang links, when a module
449 // implements its own URL rewriting scheme that core has no knowledge of). Runs on every
450 // request (not only at page compile time), so it applies no matter which code path last
451 // recompiled this page (website editor, inline AJAX edit, a module's own template reset...).
452 $tplcontent .= "// Let modules rewrite the final page content (hook)\n";
453 $tplcontent .= 'global $hookmanager;'."\n";
454 $tplcontent .= 'if (is_object($hookmanager)) {'."\n";
455 $tplcontent .= ' $hookmanager->initHooks(array(\'websitepagecontent\'));'."\n";
456 $tplcontent .= ' $parameters = array(\'tmp\' => &$tmp);'."\n";
457 $tplcontent .= ' $hookmanager->executeHooks(\'printWebsitePageContent\', $parameters, $websitepage);'."\n";
458 $tplcontent .= '}'."\n";
459
460 $tplcontent .= "// Now output the generated page content\n";
461 $tplcontent .= 'dolWebsiteOutput($tmp, "html", '.((int) $objectpage->id).'); dolWebsiteIncrementCounter('.((int) $object->id).', "'.preg_replace('/[^\w\-]/', '', (string) $objectpage->type_container).'", '.((int) $objectpage->id).');'."\n";
462 $tplcontent .= "// END PHP ?>\n";
463 } else {
464 $tplcontent .= "<?php // BEGIN PHP\n";
465 $tplcontent .= '$websitekey=basename(__DIR__); if (empty($websitepagefile)) $websitepagefile=__FILE__;'."\n";
466 $tplcontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) {\n";
467 $tplcontent .= ' $pathdepth = count(explode(\'/\', $_SERVER[\'SCRIPT_NAME\'])) - 2;'."\n";
468 $tplcontent .= ' require_once ($pathdepth ? str_repeat(\'../\', $pathdepth) : \'./\').\'master.inc.php\';'."\n";
469 if ($objectpage->disable_waf != 'all') {
470 if (strpos($objectpage->disable_waf, 'NOSCANAUDIOFORINJECTION') !== false) {
471 $tplcontent .= ' define(\'NOSCANAUDIOFORINJECTION\', 1);'."\n";
472 }
473 if (strpos($objectpage->disable_waf, 'NOSCANIFRAMEFORINJECTION') !== false) {
474 $tplcontent .= ' define(\'NOSCANIFRAMEFORINJECTION\', 1);'."\n";
475 }
476 if (strpos($objectpage->disable_waf, 'NOSCANOBJECTFORINJECTION') !== false) {
477 $tplcontent .= ' define(\'NOSCANOBJECTFORINJECTION\', 1);'."\n";
478 }
479 $tplcontent .= ' require_once DOL_DOCUMENT_ROOT.\'/waf.inc.php\';'."\n";
480 }
481 $tplcontent .= "}\n";
482 $tplcontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
483 $tplcontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
484 if (in_array($objectpage->type_container, array('page', 'blogpost', 'service'))) {
485 $tplcontent .= 'dol_syslog("--- Prepare content of page '.((int) $objectpage->id).' - '.preg_replace('/[^\w_-]/', '', $objectpage->pageurl).'");'."\n";
486 }
487 $tplcontent .= "// END PHP ?>\n";
488
489 $tplcontent .= $objectpage->content;
490 }
491
492 //var_dump($filetpl);exit;
493 $result = file_put_contents($filetpl, $tplcontent);
494
495 dolChmod($filetpl);
496
497 return $result;
498}
499
500
511function dolSaveIndexPage($pathofwebsite, $fileindex, $filetpl, $filewrapper, $object = null)
512{
513 global $db;
514
515 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
516
517 $result1 = false;
518 $result2 = false;
519
520 dol_mkdir($pathofwebsite);
521
522 if ($fileindex) {
523 dol_delete_file($fileindex);
524 $indexcontent = '<?php'."\n";
525 $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";
526 $indexcontent .= '$websitekey=basename(__DIR__); if (empty($websitepagefile)) $websitepagefile=__FILE__;'."\n";
527 $indexcontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once './master.inc.php'; } // Load master if not already loaded\n";
528 $indexcontent .= 'if (!empty($_GET[\'pageref\']) || !empty($_GET[\'pagealiasalt\']) || !empty($_GET[\'pageid\'])) {'."\n";
529 $indexcontent .= " require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
530 $indexcontent .= " require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
531 $indexcontent .= ' redirectToContainer($_GET[\'pageref\'], $_GET[\'pagealiasalt\'], $_GET[\'pageid\']);'."\n";
532 $indexcontent .= "}\n";
533 $indexcontent .= "include_once './".basename($filetpl)."'\n";
534 $indexcontent .= '// END PHP ?>'."\n";
535
536 $result1 = file_put_contents($fileindex, $indexcontent);
537
538 dolChmod($fileindex);
539
540 if (is_object($object) && $object->fk_default_home > 0) {
541 $objectpage = new WebsitePage($db);
542 $objectpage->fetch($object->fk_default_home);
543
544 // Create a version for sublanguages
545 if (empty($objectpage->lang) || !in_array($objectpage->lang, explode(',', $object->otherlang))) {
546 if (!getDolGlobalString('WEBSITE_DISABLE_MAIN_LANGUAGE_INTO_LANGSUBDIR') && is_object($object) && !empty($object->otherlang)) {
547 $dirname = dirname($fileindex);
548 foreach (explode(',', $object->otherlang) as $sublang) {
549 // Avoid to erase main alias file if $sublang is empty string
550 if (empty(trim($sublang))) {
551 continue;
552 }
553 $fileindexsub = $dirname.'/'.$sublang.'/index.php';
554
555 // Same indexcontent than previously but with ../ instead of ./ for master and tpl file include/require_once.
556 $relpath = '..';
557 $indexcontent = '<?php'."\n";
558 $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";
559 $indexcontent .= '$websitekey=basename(__DIR__); if (empty($websitepagefile)) $websitepagefile=__FILE__;'."\n";
560 $indexcontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once '".$relpath."/master.inc.php'; } // Load master if not already loaded\n";
561 $indexcontent .= 'if (!empty($_GET[\'pageref\']) || !empty($_GET[\'pagealiasalt\']) || !empty($_GET[\'pageid\'])) {'."\n";
562 $indexcontent .= " require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
563 $indexcontent .= " require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
564 $indexcontent .= ' redirectToContainer($_GET[\'pageref\'], $_GET[\'pagealiasalt\'], $_GET[\'pageid\']);'."\n";
565 $indexcontent .= "}\n";
566 $indexcontent .= "include_once '".$relpath."/".basename($filetpl)."'\n"; // use .. instead of .
567 $indexcontent .= '// END PHP ?>'."\n";
568 $result = file_put_contents($fileindexsub, $indexcontent);
569 if ($result === false) {
570 dol_syslog("Failed to write file ".$fileindexsub, LOG_WARNING);
571 }
572 dolChmod($fileindexsub);
573 }
574 }
575 }
576 }
577 } else {
578 $result1 = true;
579 }
580
581 if ($filewrapper) {
582 dol_delete_file($filewrapper);
583 $wrappercontent = file_get_contents(DOL_DOCUMENT_ROOT.'/website/samples/wrapper.php');
584
585 $result2 = file_put_contents($filewrapper, $wrappercontent);
586 dolChmod($filewrapper);
587 } else {
588 $result2 = true;
589 }
590
591 return ($result1 && $result2);
592}
593
594
602function dolSaveHtmlHeader($filehtmlheader, $htmlheadercontent)
603{
604 global $pathofwebsite;
605
606 dol_syslog("Save html header into ".$filehtmlheader);
607
608 dol_mkdir($pathofwebsite);
609 $result = file_put_contents($filehtmlheader, $htmlheadercontent);
610 dolChmod($filehtmlheader);
611
612 return $result;
613}
614
622function dolSaveCssFile($filecss, $csscontent)
623{
624 global $pathofwebsite;
625
626 dol_syslog("Save css file into ".$filecss);
627
628 dol_mkdir($pathofwebsite);
629 $result = file_put_contents($filecss, $csscontent);
630 dolChmod($filecss);
631
632 return $result;
633}
634
642function dolSaveJsFile($filejs, $jscontent)
643{
644 global $pathofwebsite;
645
646 dol_syslog("Save js file into ".$filejs);
647
648 dol_mkdir($pathofwebsite);
649 $result = file_put_contents($filejs, $jscontent);
650 dolChmod($filejs);
651
652 return $result;
653}
654
662function dolSaveRobotFile($filerobot, $robotcontent)
663{
664 global $pathofwebsite;
665
666 dol_syslog("Save robot file into ".$filerobot);
667
668 dol_mkdir($pathofwebsite);
669 $result = file_put_contents($filerobot, $robotcontent);
670 dolChmod($filerobot);
671
672 return $result;
673}
674
682function dolSaveHtaccessFile($filehtaccess, $htaccess)
683{
684 global $pathofwebsite;
685
686 dol_syslog("Save htaccess file into ".$filehtaccess);
687
688 dol_mkdir($pathofwebsite);
689 $result = file_put_contents($filehtaccess, $htaccess);
690 dolChmod($filehtaccess);
691
692 return $result;
693}
694
702function dolSaveManifestJson($file, $content)
703{
704 global $pathofwebsite;
705
706 dol_syslog("Save manifest.js.php file into ".$file);
707
708 dol_mkdir($pathofwebsite);
709 $result = file_put_contents($file, $content);
710 dolChmod($file);
711
712 return $result;
713}
714
722function dolSaveReadme($file, $content)
723{
724 global $pathofwebsite;
725
726 dol_syslog("Save README.md file into ".$file);
727
728 dol_mkdir($pathofwebsite);
729 $result = file_put_contents($file, $content);
730 dolChmod($file);
731
732 return $result;
733}
734
742function dolSaveLicense($file, $content)
743{
744 global $pathofwebsite;
745
746 dol_syslog("Save LICENSE file into ".$file);
747
748 dol_mkdir($pathofwebsite);
749 $result = file_put_contents($file, $content);
750 dolChmod($file);
751
752 return $result;
753}
754
762function showWebsiteTemplates(Website $website, int $refresh)
763{
764 global $conf, $langs, $form, $user;
765
766 // We want only one directory for dir of website templates. If an external module need to provide a template, the template must be copied into this directory
767 // when module is enabled.
768 $dirthemes = array('/doctemplates/websites');
769
770 $warningtoshow = '';
771 $arrayoftemplatesfound = array();
772
773 if (count($dirthemes)) {
774 $i = 0;
775 // Scan dir to get all deployed qualified templates
776 foreach ($dirthemes as $dir) {
777 $dirtheme = DOL_DATA_ROOT.$dir;
778
779 if (is_dir($dirtheme)) {
780 $handle = opendir($dirtheme);
781 if (is_resource($handle)) {
782 while (($subdir = readdir($handle)) !== false) { // Scan files of directory
783 //var_dump($dirtheme.'/'.$subdir);
784 if (dol_is_file($dirtheme."/".$subdir) && substr($subdir, 0, 1) != '.' && substr($subdir, 0, 3) != 'CVS' && preg_match('/\.zip$/i', $subdir)) {
785 $subdirwithoutzip = preg_replace('/\.zip$/i', '', $subdir);
786 $subdirwithoutzipwithoutver = preg_replace('/(_exp|_dev)$/i', '', $subdirwithoutzip);
787
788 // Disable not stable themes (dir ends with _exp or _dev)
789 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2 && preg_match('/_dev$/i', $subdirwithoutzip)) {
790 continue;
791 }
792 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') < 1 && preg_match('/_exp$/i', $subdirwithoutzip)) {
793 continue;
794 }
795
796 $arrayoftemplatesfound[$subdirwithoutzip] = array('id' => $subdirwithoutzip);
797 $i++;
798 }
799 }
800 }
801 }
802 }
803
804 // Now test if we found template available into source not copied into documents
805 $arrayofsourcetemplates = dol_dir_list(DOL_DOCUMENT_ROOT.'/install/doctemplates/websites', 'directories', 0, 'website_.*$');
806 $arrayofsourcetemplatesnotdeployed = array();
807 foreach ($arrayofsourcetemplates as $val) {
808 // Disable not stable themes (dir ends with _exp or _dev)
809 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2 && preg_match('/_dev$/i', $val['relativename'])) {
810 continue;
811 }
812 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') < 1 && preg_match('/_exp$/i', $val['relativename'])) {
813 continue;
814 }
815
816 if (empty($arrayoftemplatesfound[$val['relativename']])) {
817 // We found a template into sources that is not into documents
818 if ($refresh) { // We copy it
819 $src = DOL_DOCUMENT_ROOT.'/install/doctemplates/websites/'.$val['name'];
820 $dest = DOL_DATA_ROOT.'/doctemplates/websites/'.$val['name'];
821
822 dol_delete_file($dest.'.zip');
823
824 // Compress it
825 global $errormsg; // Used by dol_compress_dir
826 $errormsg = '';
827 $result = dol_compress_dir($src, $dest.'.zip', 'zip');
828 if ($result < 0) {
829 dol_syslog("Error in compress of dir ".$src, LOG_ERR);
830 }
831
832 $srcfile = DOL_DOCUMENT_ROOT.'/install/doctemplates/websites/'.preg_replace('/(_exp|_dev)$/', '', $val['name']).'.jpg';
833 $destfile = DOL_DATA_ROOT.'/doctemplates/websites/'.preg_replace('/(_exp|_dev)$/', '', $val['name']).'.jpg';
834
835 dol_copy($srcfile, $destfile);
836 } else {
837 $arrayofsourcetemplatesnotdeployed[$val['relativename']] = $val;
838 }
839 }
840 }
841
842 if (count($arrayofsourcetemplatesnotdeployed)) {
843 $warningtoshow = img_picto($langs->trans("WarningTemplatesFoundNotDeployedClickRefresh").': '.implode(', ', array_keys($arrayofsourcetemplatesnotdeployed)).'. '.$langs->trans("WarningTemplatesFoundNotDeployedClickRefresh2"), 'warning', 'class="valignmiddle paddingright"');
844 }
845 }
846
847 $colspan = 2;
848
849 $importButtonIsDisabled = 0;
850
851 global $dolibarr_website_allow_custom_php;
852 if (!empty($dolibarr_website_allow_custom_php) && $dolibarr_website_allow_custom_php == 1) {
853 $notdisabledsystemfunction = '';
854 $systemfunctions = array("exec", "passthru", "shell_exec", "system", "popen", "proc_open");
855 foreach ($systemfunctions as $systemfunction) {
856 // @phpstan-ignore-next-line
857 if (function_exists($systemfunction)) {
858 $notdisabledsystemfunction .= ($notdisabledsystemfunction ? ', ' : '').$systemfunction;
859 }
860 }
861 if ($notdisabledsystemfunction) {
862 print '<div class="warning">';
863 print $langs->trans("ImportOfWebsiteTemplateIncludingPHPIsAllowedIf", 'warning');
864 print '</div>';
865
866 $importButtonIsDisabled = 1;
867 }
868 }
869 if (empty($dolibarr_website_allow_custom_php)) {
870 print '<div class="warning">';
871 print $langs->trans("ImportOfWebsiteTemplateIncludingPHPIsDisabled", 'warning');
872 print '</div>';
873
874 $importButtonIsDisabled = 1;
875 }
876
877 print '<!-- For website template import -->'."\n";
878 print '<table class="noborder centpercent">';
879
880 // Title
881 print '<tr class="liste_titre"><th class="titlefield">';
882 print $form->textwithpicto($langs->trans("Templates"), $langs->trans("ThemeDir").' : '.implode(", ", $dirthemes));
883 print ' ';
884 print '<a class="valignmiddle" href="'.$_SERVER["PHP_SELF"].'?website='.urlencode($website->ref).'&importsite=2" rel="noopener noreferrer external">';
885 print $warningtoshow;
886 print img_picto($langs->trans("Refresh"), 'refresh', 'class="valignmiddle"');
887 print '</a>';
888 print '</th>';
889 print '<th class="right">';
890 $url = 'https://www.dolistore.com/index.php?cat=84';
891 print '<a href="'.$url.'" target="_blank" rel="noopener noreferrer external">';
892 print img_picto('', 'globe', 'class="pictofixedwidth"').$langs->trans('DownloadMoreSkins');
893 print '</a>';
894 print '</th></tr>';
895
896 print '<tr><td colspan="'.$colspan.'">';
897
898 print '<table class="nobordernopadding centpercent"><tr><td><div class="display-flex">';
899
900 if (count($dirthemes)) {
901 $i = 0;
902 foreach ($dirthemes as $dir) {
903 $dirtheme = DOL_DATA_ROOT.$dir;
904
905 if (is_dir($dirtheme)) {
906 $handle = opendir($dirtheme);
907 if (is_resource($handle)) {
908 while (($subdir = readdir($handle)) !== false) { // Scan files of directory
909 //var_dump($dirtheme.'/'.$subdir);
910 if (dol_is_file($dirtheme."/".$subdir) && substr($subdir, 0, 1) != '.' && substr($subdir, 0, 3) != 'CVS' && preg_match('/\.zip$/i', $subdir)) {
911 $subdirwithoutzip = preg_replace('/\.zip$/i', '', $subdir);
912 $subdirwithoutzipwithoutver = preg_replace('/(_exp|_dev)$/i', '', $subdirwithoutzip);
913
914 // Disable not stable themes (dir ends with _exp or _dev)
915 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2 && preg_match('/_dev$/i', $subdirwithoutzip)) {
916 continue;
917 }
918 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') < 1 && preg_match('/_exp$/i', $subdirwithoutzip)) {
919 continue;
920 }
921
922 $arrayoftemplatesfound[$subdirwithoutzip] = array('id' => $subdirwithoutzip);
923
924 print '<div class="inline-block center flex-item" style="min-width: 250px; max-width: 400px; margin-top: 10px; margin-bottom: 10px; margin-right: 20px; margin-left: 20px;">';
925
926 $templatedir = $dirtheme."/".$subdir;
927 $file = $dirtheme."/".$subdirwithoutzipwithoutver.".jpg";
928 $url = DOL_URL_ROOT.'/viewimage.php?modulepart=doctemplateswebsite&file='.$subdirwithoutzipwithoutver.".jpg";
929
930 if (!file_exists($file)) {
931 $url = DOL_URL_ROOT.'/public/theme/common/nophoto.png';
932 }
933
934 $originalimgfile = basename($file);
935 $entity = $conf->entity;
936 $modulepart = 'doctemplateswebsite';
937 $cache = '';
938 $title = $file;
939
940 $ret = '';
941 $urladvanced = getAdvancedPreviewUrl($modulepart, $originalimgfile, 1, '&entity='.$entity);
942 if (!empty($urladvanced)) {
943 $ret .= '<a class="'.$urladvanced['css'].'" target="'.$urladvanced['target'].'" mime="'.$urladvanced['mime'].'" href="'.$urladvanced['url'].'">';
944 } else {
945 $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.urlencode($modulepart).'&entity='.((int) $entity).'&file='.urlencode($originalimgfile).'&cache='.((int) $cache).'">';
946 }
947 print $ret;
948 print '<img class="img-skinthumb shadow" src="'.$url.'" border="0" alt="'.$title.'" title="'.$title.'" style="margin-bottom: 5px;">';
949 print '</a>';
950
951 print '<br>';
952 print $subdir;
953 print '<br>';
954 print '<span class="opacitymedium">'.dol_print_size(dol_filesize($dirtheme."/".$subdir), 1, 1).' - '.dol_print_date(dol_filemtime($templatedir), 'dayhour', 'tzuserrel').'</span>';
955 if ($user->hasRight('website', 'delete')) {
956 print ' <a href="'.$_SERVER["PHP_SELF"].'?action=deletetemplate&token='.newToken().'&website='.urlencode($website->ref).'&templateuserfile='.urlencode($subdir).'">'.img_picto('', 'delete').'</a>';
957 }
958 print '<br><a href="'.$_SERVER["PHP_SELF"].'?action=importsiteconfirm&token='.newToken().'&website='.urlencode($website->ref).'&templateuserfile='.urlencode($subdir).'" class="button'.($importButtonIsDisabled ? ' disabled' : '').'">'.$langs->trans("Load").'</a>';
959 print '</div>';
960
961 $i++;
962 }
963 }
964 print '<div class="inline-block center flex-item" style="min-width: 250px; max-width: 400px;margin-top: 10px; margin-bottom: 10px; margin-right: 20px; margin-left: 20px;"></div>';
965 print '<div class="inline-block center flex-item" style="min-width: 250px; max-width: 400px;margin-top: 10px; margin-bottom: 10px; margin-right: 20px; margin-left: 20px;"></div>';
966 print '<div class="inline-block center flex-item" style="min-width: 250px; max-width: 400px;margin-top: 10px; margin-bottom: 10px; margin-right: 20px; margin-left: 20px;"></div>';
967 print '<div class="inline-block center flex-item" style="min-width: 250px; max-width: 400px;margin-top: 10px; margin-bottom: 10px; margin-right: 20px; margin-left: 20px;"></div>';
968 print '<div class="inline-block center flex-item" style="min-width: 250px; max-width: 400px;margin-top: 10px; margin-bottom: 10px; margin-right: 20px; margin-left: 20px;"></div>';
969 }
970 }
971 }
972 } else {
973 print '<span class="opacitymedium">'.$langs->trans("None").'</span>';
974 }
975
976 print '</div></td></tr></table>';
977
978 print '</td></tr>';
979 print '</table>';
980}
981
982
998function checkPHPCode(&$phpfullcodestringold, &$phpfullcodestring)
999{
1000 global $langs, $user;
1001
1002 $error = 0;
1003
1004 if (empty($phpfullcodestringold) && empty($phpfullcodestring)) {
1005 return 0;
1006 }
1007
1008 // First check permission
1009 if ($phpfullcodestringold != $phpfullcodestring) {
1010 global $dolibarr_website_allow_custom_php;
1011 if (empty($dolibarr_website_allow_custom_php)) { // Case of $dolibarr_website_allow_custom_php = 0
1012 $error++;
1013 setEventMessages($langs->trans("NotAllowedToAddDynamicContentDisabledGlobaly", 'dolibarr_website_allow_custom_php'), null, 'errors');
1014 } elseif ($dolibarr_website_allow_custom_php == 1) { // Case of $dolibarr_website_allow_custom_php = 1
1015 $notdisabledsystemfunction = '';
1016 $systemfunctions = array("exec", "passthru", "shell_exec", "system", "popen", "proc_open");
1017 foreach ($systemfunctions as $systemfunction) {
1018 // @phpstan-ignore-next-line
1019 if (function_exists($systemfunction)) {
1020 $notdisabledsystemfunction .= ($notdisabledsystemfunction ? ', ' : '').$systemfunction;
1021 }
1022 }
1023 if ($notdisabledsystemfunction) {
1024 $error++;
1025 $langs->load("errors");
1026 setEventMessages($langs->trans("ErrorDynamicPHPContentNotAllowed", 'dolibarr_website_allow_custom_php'), null, 'errors');
1027 }
1028 }
1029
1030 if (!$error && !$user->hasRight('website', 'writephp')) {
1031 $error++;
1032 setEventMessages($langs->trans("NotAllowedToAddDynamicContent"), null, 'errors');
1033 }
1034 }
1035
1036 $phpfullcodestringnew = $phpfullcodestring;
1037
1038 // Then check forbidden commands
1039 if (!$error) {
1040 if (getDolGlobalString("WEBSITE_DISALLOW_DOLLAR_UNDERSCORE")) {
1041 $phpfullcodestring = preg_replace('/\$_COOKIE\[/', '__DOLLARCOOKIE__', $phpfullcodestring);
1042 $phpfullcodestring = preg_replace('/\$_FILES\[/', '__DOLLARFILES__', $phpfullcodestring);
1043 $phpfullcodestring = preg_replace('/\$_SESSION\[/', '__DOLLARSESSION__', $phpfullcodestring);
1044 $forbiddenphpstrings = array('$$', '$_', '}[');
1045 } else {
1046 $forbiddenphpstrings = array('$$', '}[');
1047 }
1048 //$forbiddenphpstrings = array_merge($forbiddenphpstrings, array('_ENV', '_FILES', '_SESSION', '_COOKIE', '_GET', '_POST', '_REQUEST', 'ReflectionFunction'));
1049 $forbiddenphpstrings = array_merge($forbiddenphpstrings, array('_ENV', 'ReflectionFunction'));
1050
1051 $forbiddenphpfunctions = array();
1052 //$forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("base64"."_"."decode", "rawurl"."decode", "url"."decode", "str"."_rot13", "hex"."2bin")); // name of forbidden functions are split to avoid false positive
1053 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("override_function", "session_id", "session_create_id", "session_regenerate_id"));
1054 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("get_defined_functions", "get_defined_vars", "get_defined_constants", "get_declared_classes"));
1055 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("call_user_func", "call_user_func_array"));
1056 //$forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("require", "include", "require_once", "include_once"));
1057
1058 if (!getDolGlobalString('WEBSITE_PHP_ALLOW_EXEC')) { // If experimental option is not on, we TRY to disallow functions to execute commands
1059 // WARNING: This is not reliable. If you don't want user to run code on the server, just NEVER give him permission to execute dynamic PHP in website module (or never enable website module).
1060 // The following list shares a lot of content with the whitelist guard in dol_eval() function.
1061
1062 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("ob_start"));
1063
1064 // Functions with callable parameters
1065 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("call_user_func", "call_user_func_array"));
1066 //$forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("array_all", "array_any", "array_diff_ukey", "array_filter", "array_find", "array_find_key", "array_map", "array_reduce", "array_intersect_uassoc", "array_intersect_ukey", "array_walk", "array_walk_recursive"));
1067 //$forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("usort", "uasort", "uksort"));
1068 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("preg_replace_callback", "preg_replace_callback_array", "header_register_callback"));
1069 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("error_log", "set_error_handler", "set_exception_handler", "libxml_set_external_entity_loader", "register_shutdown_function", "register_tick_function", "unregister_tick_function"));
1070 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("spl_autoload_register", "spl_autoload_unregister", "iterator_apply", "session_set_save_handler"));
1071 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("forward_static_call", "forward_static_call_array", "register_postsend_function"));
1072 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("readline_completion_function", "readline_callback_handler_install"));
1073
1074 // Exec functions
1075 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("exec", "passthru", "shell_exec", "system", "proc_open", "popen"));
1076 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("pcntl_alarm", "pcntl_exec", "pcntl_fork", "pcntl_waitpid", "pcntl_wait", "pcntl_wifexited", "pcntl_wifstopped", "pcntl_wifsignaled", "pcntl_wifcontinued", "pcntl_wexitstatus", "pcntl_wtermsig", "pcntl_wstopsig", "pcntl_signal"));
1077 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("pcntl_signal_get_handler", "pcntl_signal_dispatch", "pcntl_get_last_error", "pcntl_strerror", "pcntl_sigprocmask", "pcntl_sigwaitinfo", "pcntl_sigtimedwait", "pcntl_getpriority", "pcntl_async_signals", "pcntl_unshare", ));
1078 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("putenv", "dl", "apache_child_terminate", "apache_setenv"));
1079 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("dol_eval", "dol_eval_new", "dol_eval_standard", "executeCLI", "verifCond", "dolEncrypt", "dolDecrypt")); // native dolibarr functions
1080 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("eval", "create_function", "assert", "mb_ereg_replace")); // function with eval capabilities
1081
1082 // Include functions
1083 //$forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("require", "include", "require_once", "include_once"));
1084 }
1085 if (!getDolGlobalString('WEBSITE_PHP_ALLOW_WRITE')) { // If option is not on, we disallow functions to write files
1086 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("dol_compress_dir", "dol_decode", "dol_dir_list", "dol_dir_list_in_database", "dol_delete_file", "dol_delete_dir", "dol_delete_dir_recursive", "dol_copy", "archiveOrBackupFile")); // more dolibarr functions
1087 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("chdir", "dir", "fopen", "file", "file_exists", "file_get_contents", "file_put_contents", "fget", "fgetc", "fgetcsv", "flock", "fputs", "fputscsv", "fpassthru", "fscanf", "fseek", "fwrite", "is_file", "is_dir", "is_link", "mkdir", "opendir", "rmdir", "scandir", "symlink", "touch", "unlink", "umask"));
1088 }
1089 if (getDolGlobalString('WEBSITE_PHP_DISALLOW_READ')) { // If option is not on, we disallow functions to read files
1090 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("dol_decode")); // more dolibarr functions
1091 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("file", "fopen", "file_get_contents", "fgets", "fgetscsv", "fgetss", "fread"));
1092 }
1093
1094 $forbiddenphpmethods = array('invoke', 'invokeArgs'); // Method of ReflectionFunction to execute a function
1095
1096 foreach ($forbiddenphpstrings as $forbiddenphpstring) {
1097 if (preg_match('/'.preg_quote($forbiddenphpstring, '/').'/ims', $phpfullcodestring)) {
1098 $error++;
1099 setEventMessages($langs->trans("DynamicPHPCodeContainsAForbiddenInstruction", $forbiddenphpstring), null, 'errors');
1100 break;
1101 }
1102 }
1103 /* replaced with next block
1104 foreach ($forbiddenphpfunctions as $forbiddenphpfunction) { // Check "function(" but also "'function'(" and "function ("
1105 if (preg_match('/'.$forbiddenphpfunction.'[\'\s]*\‍(/ims', $phpfullcodestring)) {
1106 $error++;
1107 setEventMessages($langs->trans("DynamicPHPCodeContainsAForbiddenInstruction", $forbiddenphpfunction), null, 'errors');
1108 break;
1109 }
1110 }*/
1111 foreach ($forbiddenphpfunctions as $forbiddenphpfunction) { // Check "function" whatever is "function(" or "function'(" or "function (" or "function"
1112 $reg = array();
1113 if (preg_match('/\b'.$forbiddenphpfunction.'(=| class=|\b)/ims', $phpfullcodestring, $reg)) {
1114 if ($reg[1] != '=' && $reg[1] != ' class=') { // So we may accept string ...&file=... even if 'file' is in forbiddenphpfunction. And we accept content with '<dl class=...'
1115 $error++;
1116 //setEventMessages($langs->trans("DynamicPHPCodeContainsAForbiddenInstruction", $forbiddenphpfunction)." :<br>\n".$phpfullcodestring, null, 'errors');
1117 setEventMessages($langs->trans("DynamicPHPCodeContainsAForbiddenInstruction", $forbiddenphpfunction), null, 'errors');
1118 break;
1119 }
1120 }
1121 }
1122
1123 foreach ($forbiddenphpmethods as $forbiddenphpmethod) {
1124 if (preg_match('/->'.$forbiddenphpmethod.'/ims', $phpfullcodestring)) {
1125 $error++;
1126 setEventMessages($langs->trans("DynamicPHPCodeContainsAForbiddenInstruction", $forbiddenphpmethod), null, 'errors');
1127 break;
1128 }
1129 }
1130 }
1131
1132 // This char can be used to execute RCE for example by using echo `ls`
1133 if (!$error) {
1134 $forbiddenphpchars = array();
1135 if (!getDolGlobalString('WEBSITE_PHP_ALLOW_DANGEROUS_CHARS')) { // If option is not on, we disallow functions to execute commands
1136 $forbiddenphpchars = array("`");
1137 }
1138 foreach ($forbiddenphpchars as $forbiddenphpchar) {
1139 if (preg_match('/'.$forbiddenphpchar.'/ims', $phpfullcodestring)) {
1140 $error++;
1141 setEventMessages($langs->trans("DynamicPHPCodeContainsAForbiddenInstruction", $forbiddenphpchar), null, 'errors');
1142 break;
1143 }
1144 }
1145 }
1146
1147 // Deny code to call a function obfuscated with comment, like "exec/*...*/ ('ls')";
1148 if (!$error) {
1149 if (preg_match('/\*\/\s*\‍(/ims', $phpfullcodestring)) {
1150 $error++;
1151 setEventMessages($langs->trans("DynamicPHPCodeContainsAForbiddenInstruction", "exec/*...*/ ('ls')"), null, 'errors');
1152 }
1153 }
1154
1155 // Deny dynamic functions '${a}(' or '$a[b](' => So we refuse '}(' and ']('
1156 if (!$error) {
1157 if (preg_match('/[}\]]\s*\‍(/ims', $phpfullcodestring)) {
1158 $error++;
1159 setEventMessages($langs->trans("DynamicPHPCodeContainsAForbiddenInstruction", ']('), null, 'errors');
1160 }
1161 }
1162
1163 // Deny dynamic functions '$xxx(' or '$xxx (' or '$xxx" ('
1164 if (!$error) {
1165 if (preg_match('/\$[a-z0-9_\-\/\*\"]+\s*\‍(/ims', $phpfullcodestring)) {
1166 $error++;
1167 setEventMessages($langs->trans("DynamicPHPCodeContainsAForbiddenInstruction", '$...('), null, 'errors');
1168 }
1169 }
1170
1171 // No need to block $conf->global->aaa() because PHP try to run the method aaa of $conf->global and not the function into $conf->global->aaa.
1172
1173 // Then check if installmodules.lock does not block dynamic PHP code change.
1174 if ($phpfullcodestringold != $phpfullcodestringnew) {
1175 if (!$error) {
1176 $dolibarrdataroot = preg_replace('/([\\/]+)$/i', '', DOL_DATA_ROOT);
1177 $allowimportsite = true;
1178 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1179 if (dol_is_file($dolibarrdataroot.'/installmodules.lock')) {
1180 $allowimportsite = false;
1181 }
1182
1183 if (!$allowimportsite) {
1184 $error++;
1185 // Blocked by installmodules.lock
1186 if (getDolGlobalString('MAIN_MESSAGE_INSTALL_MODULES_DISABLED_CONTACT_US')) {
1187 // Show clean corporate message
1188 $message = $langs->trans('InstallModuleFromWebHasBeenDisabledContactUs');
1189 } else {
1190 // Show technical generic message
1191 $message = $langs->trans("InstallModuleFromWebHasBeenDisabledByFile", $dolibarrdataroot.'/installmodules.lock');
1192 }
1193 setEventMessages($message, null, 'errors');
1194 }
1195 }
1196 }
1197
1198 return $error;
1199}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class Website.
dol_filemtime($pathoffile)
Return time of a file.
dol_filesize($pathoffile)
Return size of a file.
dol_copy($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=0)
Copy a file to another file.
archiveOrBackupFile($srcfile, $max_versions=5, $archivedir='', $suffix="v", $moveorcopy='move')
Manage backup versions for a given file, ensuring only a maximum number of versions are kept.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_is_file($pathoffile)
Return if path is a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:66
dol_sanitizePathName($str, $newstr='_', $unaccent=0, $allowdash=0)
Clean a string to use it as a path name.
dolChmod($filepath, $newmask='')
Change mod of a file.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='')
Return URL we can use for advanced preview links.
dolSaveMasterFile($filemaster)
Save content of a page on disk.
dolSaveLicense($file, $content)
Save content of a page on disk.
checkPHPCode(&$phpfullcodestringold, &$phpfullcodestring)
Check that the new string $phpfullcodestring contains only php code (including <php tag)
dolSaveHtmlHeader($filehtmlheader, $htmlheadercontent)
Save content of a page on disk.
dolSaveReadme($file, $content)
Save content of a page on disk.
dolSaveManifestJson($file, $content)
Save content of a page on disk.
dolSaveIndexPage($pathofwebsite, $fileindex, $filetpl, $filewrapper, $object=null)
Save content of the index.php and/or the wrapper.php page.
dolSavePageAlias($filealias, $object, $objectpage)
Save an alias page on disk (A page that include the reference page).
dolSaveHtaccessFile($filehtaccess, $htaccess)
Save content of a page on disk.
dolSaveJsFile($filejs, $jscontent)
Save content of a page on disk.
dolSavePageContent($filetpl, Website $object, WebsitePage $objectpage, $backupold=0)
Save content of a page on disk (page name is generally ID_of_page.php).
showWebsiteTemplates(Website $website, int $refresh)
Show list of themes.
dolSaveCssFile($filecss, $csscontent)
Save content of a page on disk.
dolSaveRobotFile($filerobot, $robotcontent)
Save content of a page on disk.