dolibarr 25.0.0-alpha
index.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2016-2023 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2020 Nicolas ZABOURI <info@inovea-conseil.com>
4 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2026 Joachim Kueter <git-jk@bloxera.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
30// We allow POST of rich content with js and style, but only for this php file and if into some given POST variable
31define('NOSCANPOSTFORINJECTION', array('PAGE_CONTENT', 'WEBSITE_CSS_INLINE', 'WEBSITE_JS_INLINE', 'WEBSITE_HTML_HEADER', 'htmlheader'));
32
33define('USEDOLIBARREDITOR', 1);
34define('FORCE_CKEDITOR', 1); // We need CKEditor, even if module is off.
35if (!defined('DISABLE_JS_GRAHP')) {
36 define('DISABLE_JS_GRAPH', 1);
37}
38
39//header('X-XSS-Protection:0'); // Disable XSS filtering protection of some browsers (note: use of Content-Security-Policy is more efficient). Disabled as deprecated.
40
41// Load Dolibarr environment
42require '../main.inc.php';
52require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
53require_once DOL_DOCUMENT_ROOT.'/website/lib/website.lib.php';
54require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
55require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';
56require_once DOL_DOCUMENT_ROOT.'/core/lib/website2.lib.php';
57require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
58require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
59require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
60require_once DOL_DOCUMENT_ROOT.'/core/class/html.formwebsite.class.php';
61require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
62require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
63require_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php';
64require_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php';
65require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
66require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
67
68// Load translation files required by the page
69$langs->loadLangs(array("admin", "other", "users", "website"));
70
71// Security check
72if (!$user->hasRight('website', 'read')) {
74}
75
76$conf->dol_hide_leftmenu = 1; // Force hide of left menu.
77
78$error = 0;
79$virtualurl = '';
80$dataroot = '';
81$websiteid = GETPOSTINT('websiteid');
82$websitekey = GETPOST('website', 'alpha');
83$page = GETPOST('page', 'alpha');
84$pageid = GETPOSTINT('pageid');
85$pageref = GETPOST('pageref', 'alphanohtml');
86
87$action = GETPOST('action', 'aZ09');
88$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
89$confirm = GETPOST('confirm', 'alpha');
90$cancel = GETPOST('cancel', 'alpha');
91$toselect = GETPOST('toselect', 'array:int'); // Array of ids of elements selected into a list
92$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'websitelist'; // To manage different context of search
93$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
94$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
95$dol_hide_topmenu = GETPOSTINT('dol_hide_topmenu');
96$dol_hide_leftmenu = GETPOSTINT('dol_hide_leftmenu');
97$dol_openinpopup = GETPOST('dol_openinpopup', 'aZ09');
98
99$type_container = GETPOST('WEBSITE_TYPE_CONTAINER', 'alpha');
100$section_dir = GETPOST('section_dir', 'alpha');
101$file_manager = GETPOST('file_manager', 'alpha');
102$replacesite = GETPOST('replacesite', 'alpha');
103$mode = GETPOST('mode', 'alpha');
104
105if (GETPOST('deletesite', 'alpha')) {
106 $action = 'deletesite';
107}
108if (GETPOST('delete', 'alpha')) {
109 $action = 'delete';
110}
111if (GETPOST('preview', 'alpha')) {
112 $action = 'preview';
113}
114if (GETPOST('createsite', 'alpha')) {
115 $action = 'createsite';
116}
117if (GETPOST('createcontainer', 'alpha')) {
118 $action = 'createcontainer';
119}
120if (GETPOST('editcss', 'alpha')) {
121 $action = 'editcss';
122}
123if (GETPOST('editmenu', 'alpha')) {
124 $action = 'editmenu';
125}
126if (GETPOST('setashome', 'alpha')) {
127 $action = 'setashome';
128}
129if (GETPOST('editmeta', 'alpha')) {
130 $action = 'editmeta';
131}
132if (GETPOST('editsource', 'alpha')) {
133 $action = 'editsource';
134}
135if (GETPOST('editcontent', 'alpha')) {
136 $action = 'editcontent';
137}
138if (GETPOST('exportsite', 'alpha')) {
139 $action = 'exportsite';
140}
141if (GETPOST('importsite')) { // Can be a string when clicking on button "Import site"
142 $action = 'importsite';
143}
144if (GETPOST('createfromclone', 'alpha')) {
145 $action = 'createfromclone';
146}
147if (GETPOST('createpagefromclone', 'alpha')) {
148 $action = 'createpagefromclone';
149}
150if (empty($action) && $file_manager) {
151 $action = 'file_manager';
152}
153if ($action == 'replacesite' || (empty($action) && $replacesite)) { // Test on permission not required
154 $mode = 'replacesite';
155}
156if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x')) {
157 $pageid = 0;
158}
159
160// Load variable for pagination
161$limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
162$sortfield = (string) GETPOST('sortfield', 'aZ09comma');
163$sortorder = GETPOST('sortorder', 'aZ09comma');
164$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
165if (empty($page) || $page == -1) {
166 $page = 0;
167} // If $page is not defined, or '' or -1
168$offset = $limit * $page;
169$pageprev = $page - 1;
170$pagenext = $page + 1;
171
172if (empty($action)) {
173 $action = 'preview';
174}
175
176$object = new Website($db);
177$objectpage = new WebsitePage($db);
178
179$listofwebsites = $object->fetchAll('ASC', 'position'); // Init list of websites
180
181// If website not defined, we take first found
182if (!($websiteid > 0) && empty($websitekey) && $action != 'createsite') {
183 foreach ($listofwebsites as $key => $valwebsite) {
184 $websitekey = $valwebsite->ref;
185 break;
186 }
187}
188if ($websiteid > 0 || $websitekey) {
189 $res = $object->fetch($websiteid, $websitekey);
190 $websitekey = $object->ref;
191}
192
193$website = $object;
194
195// Check pageid received as parameter
196if ($pageid < 0) {
197 $pageid = 0;
198}
199if (($pageid > 0 || $pageref) && $action != 'addcontainer') {
200 $res = $objectpage->fetch($pageid, ($object->id > 0 ? $object->id : null), $pageref);
201 // @phan-suppress
202 if ($res == 0) {
203 $res = $objectpage->fetch($pageid, ($object->id > 0 ? $object->id : null), null, $pageref);
204 }
205
206 // Check if pageid is inside the new website, if not we reset param pageid
207 if ($res >= 0 && $object->id > 0) {
208 if ($objectpage->fk_website != $object->id) { // We have a bad page that does not belong to web site
209 if ($object->fk_default_home > 0) {
210 $res = $objectpage->fetch($object->fk_default_home, (string) $object->id, ''); // We search first page of web site
211 if ($res > 0) {
212 $pageid = $object->fk_default_home;
213 }
214 } else {
215 $res = $objectpage->fetch(0, (string) $object->id, ''); // We search first page of web site
216 if ($res == 0) { // Page was not found, we reset it
217 $objectpage = new WebsitePage($db);
218 } else { // We found a page, we set pageid to it.
219 $pageid = $objectpage->id;
220 }
221 }
222 } else { // We have a valid page. We force pageid for the case we got the page with a fetch on ref.
223 $pageid = $objectpage->id;
224 }
225 }
226}
227
228// Define pageid if pageid and pageref not received as parameter or was wrong
229$atleastonepage = false;
230if (empty($pageid) && empty($pageref) && $object->id > 0 && $action != 'createcontainer') {
231 $pageid = $object->fk_default_home;
232 if (empty($pageid)) {
233 $array = $objectpage->fetchAll($object->id, 'ASC,ASC', 'type_container,pageurl');
234 if (!is_array($array) && $array < 0) {
235 dol_print_error(null, $objectpage->error, $objectpage->errors);
236 }
237 $atleastonepage = (is_array($array) && count($array) > 0);
238
239 $firstpageid = 0;
240 $homepageid = 0;
241 foreach ($array as $key => $valpage) {
242 if (empty($firstpageid)) {
243 $firstpageid = $valpage->id;
244 }
245 if ($object->fk_default_home && $key == $object->fk_default_home) {
246 $homepageid = $valpage->id;
247 }
248 }
249 $pageid = ($homepageid ? $homepageid : $firstpageid); // We choose home page and if not defined yet, we take first page
250 }
251}
252
253
254global $dolibarr_main_data_root;
255$pathofwebsite = $dolibarr_main_data_root.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.$websitekey;
256$filehtmlheader = $pathofwebsite.'/htmlheader.html';
257$filecss = $pathofwebsite.'/styles.css.php';
258$filejs = $pathofwebsite.'/javascript.js.php';
259$filerobot = $pathofwebsite.'/robots.txt';
260$filehtaccess = $pathofwebsite.'/.htaccess';
261$filetpl = $pathofwebsite.'/page'.$pageid.'.tpl.php';
262$fileindex = $pathofwebsite.'/index.php';
263$filewrapper = $pathofwebsite.'/wrapper.php';
264$filemanifestjson = $pathofwebsite.'/manifest.json.php';
265$filereadme = $pathofwebsite.'/README.md';
266$filelicense = $pathofwebsite.'/LICENSE';
267$filemaster = $pathofwebsite.'/master.inc.php';
268
269// Get the archived version of the page to show (0 = current page).
270// Version files are the backup files page<pageid>.tpl.php.v<timestamp> saved by archiveOrBackupFile() each time the page is saved.
271$pageversion = GETPOSTINT('pageversion');
272$filetplversion = '';
273if ($pageid > 0 && $pageversion > 0) {
274 $filetplversion = $pathofwebsite.'/page'.((int) $pageid).'.tpl.php.v'.((int) $pageversion);
275 if (!dol_is_file($filetplversion)) {
276 $filetplversion = '';
277 $pageversion = 0;
278 }
279}
280
281$forceCSP = getDolGlobalString("WEBSITE_".$object->id."_SECURITY_FORCECSP");
282
283// Define $urlwithroot
284$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
285$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
286//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
287
288
289$permtouploadfile = $user->hasRight('website', 'write');
290$diroutput = $conf->medias->multidir_output[$conf->entity];
291
292$relativepath = $section_dir;
293$upload_dir = preg_replace('/\/$/', '', $diroutput).'/'.preg_replace('/^\//', '', $relativepath);
294
295$htmlheadercontentdefault = '';
296$htmlheadercontentdefault .= '<link rel="stylesheet" id="google-fonts-css" href="//fonts.googleapis.com/css?family=Open+Sans:300,400,700" />'."\n";
297$htmlheadercontentdefault .= '<link rel="stylesheet" id="font-wasesome-css" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />'."\n";
298$htmlheadercontentdefault .= '<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>'."\n";
299$htmlheadercontentdefault .= '<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>'."\n";
300$htmlheadercontentdefault .= '<!--'."\n";
301$htmlheadercontentdefault .= '<script src="/document.php?modulepart=medias&file=css/myfile.css"></script>'."\n";
302$htmlheadercontentdefault .= '<script src="/document.php?modulepart=medias&file=js/myfile.js"></script>'."\n";
303$htmlheadercontentdefault .= '-->'."\n";
304
305$manifestjsoncontentdefault = '';
306$manifestjsoncontentdefault .= '{
307 "name": "MyWebsite",
308 "short_name": "MyWebsite",
309 "start_url": "/",
310 "lang": "en-US",
311 "display": "standalone",
312 "background_color": "#fff",
313 "description": "A simple Web app.",
314 "icons": [{
315 "src": "images/'.urlencode($website->ref).'/homescreen48.png",
316 "sizes": "48x48",
317 "type": "image/png"
318 }, {
319 "src": "image/'.urlencode($website->ref).'/homescreen72.png",
320 "sizes": "72x72",
321 "type": "image/png"
322 }, {
323 "src": "image/'.urlencode($website->ref).'/homescreen96.png",
324 "sizes": "96x96",
325 "type": "image/png"
326 }, {
327 "src": "image/'.urlencode($website->ref).'/homescreen144.png",
328 "sizes": "144x144",
329 "type": "image/png"
330 }, {
331 "src": "image/'.urlencode($website->ref).'/homescreen168.png",
332 "sizes": "168x168",
333 "type": "image/png"
334 }, {
335 "src": "image/'.urlencode($website->ref).'/homescreen192.png",
336 "sizes": "192x192",
337 "type": "image/png"
338 }],
339 "related_applications": [{
340 "platform": "play",
341 "url": "https://play.google.com/store/apps/details?id=com.nltechno.dolidroidpro"
342 }]
343}';
344
345$listofpages = array();
346
347$algo = '';
348if (GETPOST('optionpcontent')) {
349 $algo .= 'content';
350}
351if (GETPOST('optionmeta')) {
352 $algo .= 'meta';
353}
354if (GETPOST('optionsitefiles')) {
355 $algo .= 'sitefiles';
356}
357
358$searchkey = GETPOST('searchstring', 'restricthtmlallowunvalid'); // or 'none', must be same as $searchstring
359
360if ($sortfield == '') {
361 if ($action == 'file_manager') { // Test on permission not required
362 $sortfield = 'name';
363 $sortorder = 'ASC';
364 } else {
365 $sortfield = 'pageurl';
366 $sortorder = 'ASC';
367 }
368}
369'@phan-var-force string $sortfield';
370
371$langcode = '';
372$containertype = '';
373$otherfilters = array();
374
375if ($action == 'replacesite' || $mode == 'replacesite') { // Test on permission not required
376 $containertype = GETPOST('optioncontainertype', 'aZ09') != '-1' ? GETPOST('optioncontainertype', 'aZ09') : '';
377 $langcode = GETPOST('optionlanguage', 'aZ09');
378 if (GETPOSTINT('optioncategory') > 0) {
379 $otherfilters['category'] = GETPOSTINT('optioncategory');
380 }
381
382 $listofpages = getPagesFromSearchCriterias($containertype, $algo, $searchkey, 1000, $sortfield, $sortorder, $langcode, $otherfilters, -1);
383}
384
385$usercanedit = $user->hasRight('website', 'write');
386$permissiontoadd = $user->hasRight('website', 'write'); // Used by the include of actions_addupdatedelete.inc.php and actions_linkedfiles.inc.php
387$permissiontodelete = $user->hasRight('website', 'delete');
388
389
390/*
391 * Actions
392 */
393
394// Protections
395if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x') || GETPOST('refreshpage') || GETPOST('refreshpage_x') || GETPOST('refreshpage.x')) {
396 $action = 'preview'; // To avoid to make an action on another page or another site when we click on button to select another site or page.
397}
398if (GETPOST('refreshsite', 'alpha') || GETPOST('refreshsite.x', 'alpha') || GETPOST('refreshsite_x', 'alpha')) { // If we change the site, we reset the pageid and cancel addsite action.
399 if ($action == 'addsite') { // Test on permission not required here
400 $action = 'preview';
401 }
402 if ($action == 'updatesource') { // Test on permission not required here
403 $action = 'preview';
404 }
405
406 $pageid = $object->fk_default_home;
407 if (empty($pageid)) {
408 $array = $objectpage->fetchAll($object->id, 'ASC,ASC', 'type_container,pageurl');
409 if (!is_array($array) && $array < 0) {
410 dol_print_error(null, $objectpage->error, $objectpage->errors);
411 }
412 $atleastonepage = (is_array($array) && count($array) > 0);
413
414 $firstpageid = 0;
415 $homepageid = 0;
416 foreach ($array as $key => $valpage) {
417 if (empty($firstpageid)) {
418 $firstpageid = $valpage->id;
419 }
420 if ($object->fk_default_home && $key == $object->fk_default_home) {
421 $homepageid = $valpage->id;
422 }
423 }
424 $pageid = ($homepageid ? $homepageid : $firstpageid); // We choose home page and if not defined yet, we take first page
425 }
426}
427if (GETPOST('refreshpage', 'alpha') && !in_array($action, array('updatecss'))) {
428 $action = 'preview';
429}
430
431if ($cancel && $action == 'renamefile') { // Test on permission not required here
432 $cancel = '';
433}
434
435// Cancel
436if ($cancel) {
437 $action = 'preview';
438 $mode = '';
439 if ($backtopage) {
440 header("Location: ".$backtopage);
441 exit;
442 }
443}
444
445$savbacktopage = $backtopage;
446$backtopage = $_SERVER["PHP_SELF"].'?file_manager=1&website='.urlencode($websitekey).'&pageid='.urlencode((string) $pageid).(GETPOST('section_dir', 'alpha') ? '&section_dir='.urlencode(GETPOST('section_dir', 'alpha')) : ''); // used after a confirm_deletefile into actions_linkedfiles.inc.php
447if ($sortfield) {
448 $backtopage .= '&sortfield='.urlencode($sortfield);
449}
450if ($sortorder) {
451 $backtopage .= '&sortorder='.urlencode($sortorder);
452}
453if ($dol_hide_topmenu) {
454 $backtopage .= '&dol_hide_topmenu='.((int) $dol_hide_topmenu);
455}
456if ($dol_hide_leftmenu) {
457 $backtopage .= '&dol_hide_leftmenu='.((int) $dol_hide_leftmenu);
458}
459if ($dol_openinpopup) {
460 $backtopage .= '&dol_openinpopup='.urlencode($dol_openinpopup);
461}
462include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; // This manage 'sendit', 'confirm_deletefile', 'renamefile' action when submitting a new file.
463
464$backtopage = $savbacktopage;
465//var_dump($backtopage);
466//var_dump($action);
467
468if ($action == 'renamefile') { // Test on permission not required here. Must be after include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; If action were renamefile, we set it to 'file_manager'
469 $action = 'file_manager';
470}
471
472if ($action == 'setwebsiteonline' && $usercanedit) {
473 $website->setStatut($website::STATUS_VALIDATED, null, '', 'WEBSITE_MODIFY', 'status');
474
475 header("Location: ".$_SERVER["PHP_SELF"].'?website='.urlencode(GETPOST('website')).'&pageid='.GETPOSTINT('websitepage'));
476 exit;
477}
478if ($action == 'setwebsiteoffline' && $usercanedit) {
479 $result = $website->setStatut($website::STATUS_DRAFT, null, '', 'WEBSITE_MODIFY', 'status');
480
481 header("Location: ".$_SERVER["PHP_SELF"].'?website='.urlencode(GETPOST('website')).'&pageid='.GETPOSTINT('websitepage'));
482 exit;
483}
484if ($action == 'seteditinline') { // Test on permission not required here
485 // Explain which elements can be edited
486 // The span with class editinlineallowedareas is used to close this sticky warning automatically after 10 seconds
487 setEventMessages('<span class="editinlineallowedareas">'.$langs->trans("EditInLineAllowedAreas").'</span>', null, 'warnings');
488
489 dolibarr_set_const($db, 'WEBSITE_EDITINLINE', 1);
490 //dolibarr_set_const($db, 'WEBSITE_SUBCONTAINERSINLINE', 0); // Force disable of 'Include dynamic content'
491 header("Location: ".$_SERVER["PHP_SELF"].'?website='.urlencode(GETPOST('website')).'&pageid='.GETPOSTINT('pageid'));
492 exit;
493}
494if ($action == 'unseteditinline') { // Test on permission not required here
495 dolibarr_del_const($db, 'WEBSITE_EDITINLINE');
496 header("Location: ".$_SERVER["PHP_SELF"].'?website='.urlencode(GETPOST('website')).'&pageid='.GETPOSTINT('pageid'));
497 exit;
498}
499if ($action == 'setshowsubcontainers') { // Test on permission not required here
500 dolibarr_set_const($db, 'WEBSITE_SUBCONTAINERSINLINE', 1);
501 //dolibarr_set_const($db, 'WEBSITE_EDITINLINE', 0); // Force disable of edit inline
502 header("Location: ".$_SERVER["PHP_SELF"].'?website='.urlencode(GETPOST('website')).'&pageid='.GETPOSTINT('pageid'));
503 exit;
504}
505if ($action == 'unsetshowsubcontainers') { // Test on permission not required here
506 dolibarr_del_const($db, 'WEBSITE_SUBCONTAINERSINLINE');
507 header("Location: ".$_SERVER["PHP_SELF"].'?website='.urlencode(GETPOST('website')).'&pageid='.GETPOSTINT('pageid'));
508 exit;
509}
510
511if ($massaction == 'replace' && GETPOST('confirmmassaction', 'alpha') && !$searchkey && $usercanedit) {
512 $mode = 'replacesite';
513 $action = 'replacesite';
514 $massaction = '';
515}
516
517if ($action == 'deletetemplate' && $usercanedit) {
518 $dirthemes = array('/doctemplates/websites');
519 if (!empty($conf->modules_parts['websitetemplates'])) { // Using this feature slow down application
520 foreach ($conf->modules_parts['websitetemplates'] as $reldir) {
521 $dirthemes = array_merge($dirthemes, (array) ($reldir.'doctemplates/websites'));
522 }
523 }
524 $dirthemes = array_unique($dirthemes);
525
526
527 // Delete template files and dir
528 $mode = 'importsite';
529 $action = 'importsite';
530
531 if (count($dirthemes)) {
532 $i = 0;
533 foreach ($dirthemes as $dir) {
534 //print $dirroot.$dir;exit;
535 $dirtheme = DOL_DATA_ROOT.$dir; // This include loop on $conf->file->dol_document_root
536 if (is_dir($dirtheme)) {
537 $templateuserfile = GETPOST('templateuserfile');
538 $imguserfile = preg_replace('/\.zip$/', '', $templateuserfile).'.jpg';
539 dol_delete_file($dirtheme.'/'.$templateuserfile);
540 dol_delete_file($dirtheme.'/'.$imguserfile);
541 }
542 }
543 }
544}
545
546// Set category
547if ($massaction == 'setcategory' && GETPOST('confirmmassaction', 'alpha') && $usercanedit) {
548 $error = 0;
549 $nbupdate = 0;
550
551 $db->begin();
552
553 $categoryid = GETPOSTINT('setcategory');
554 if ($categoryid > 0) {
555 $tmpwebsitepage = new WebsitePage($db);
556 $category = new Categorie($db);
557 $category->fetch($categoryid);
558
559 foreach ($toselect as $tmpid) {
560 $tmpwebsitepage->id = (int) $tmpid;
561 $result = $category->add_type($tmpwebsitepage, 'website_page');
562 if ($result < 0 && $result != -3) {
563 $error++;
564 setEventMessages($category->error, $category->errors, 'errors');
565 break;
566 } else {
567 $nbupdate++;
568 }
569 }
570 }
571
572 if ($error) {
573 $db->rollback();
574 } else {
575 if ($nbupdate) {
576 setEventMessages($langs->trans("RecordsModified", $nbupdate), null, 'mesgs');
577 }
578
579 $db->commit();
580 }
581 // Now we reload list
582 $listofpages = getPagesFromSearchCriterias($containertype, $algo, $searchkey, 1000, $sortfield, $sortorder, $langcode, $otherfilters, -1);
583}
584
585// Del category
586if ($massaction == 'delcategory' && GETPOST('confirmmassaction', 'alpha') && $usercanedit) {
587 $error = 0;
588 $nbupdate = 0;
589
590 $db->begin();
591
592 $categoryid = GETPOSTINT('setcategory');
593 if ($categoryid > 0) {
594 $tmpwebsitepage = new WebsitePage($db);
595 $category = new Categorie($db);
596 $category->fetch($categoryid);
597
598 foreach ($toselect as $tmpid) {
599 $tmpwebsitepage->id = (int) $tmpid;
600 $result = $category->del_type($tmpwebsitepage, 'website_page');
601 if ($result < 0 && $result != -3) {
602 $error++;
603 setEventMessages($category->error, $category->errors, 'errors');
604 break;
605 } else {
606 $nbupdate++;
607 }
608 }
609 }
610
611 if ($error) {
612 $db->rollback();
613 } else {
614 if ($nbupdate) {
615 setEventMessages($langs->trans("RecordsModified", $nbupdate), null, 'mesgs');
616 }
617
618 $db->commit();
619 }
620 // Now we reload list
621 $listofpages = getPagesFromSearchCriterias($containertype, $algo, $searchkey, 1000, $sortfield, $sortorder, $langcode, $otherfilters, -1);
622}
623
624// Replacement of string into pages
625if ($massaction == 'replace' && GETPOST('confirmmassaction', 'alpha') && $usercanedit) {
626 $replacestring = GETPOST('replacestring', 'restricthtmlallowunvalid'); // or 'none', must be same then $searchstring
627
628 $dolibarrdataroot = preg_replace('/([\\/]+)$/i', '', DOL_DATA_ROOT);
629 $allowimportsite = true;
630 if (dol_is_file($dolibarrdataroot.'/installmodules.lock')) {
631 $allowimportsite = false;
632 }
633
634 if (!$allowimportsite) {
635 // Blocked by installmodules.lock
636 if (getDolGlobalString('MAIN_MESSAGE_INSTALL_MODULES_DISABLED_CONTACT_US')) {
637 // Show clean corporate message
638 $message = $langs->trans('InstallModuleFromWebHasBeenDisabledContactUs');
639 } else {
640 // Show technical generic message
641 $message = $langs->trans("InstallModuleFromWebHasBeenDisabledByFile", $dolibarrdataroot.'/installmodules.lock');
642 }
643 setEventMessages($message, null, 'errors');
644 } elseif (!$user->hasRight('website', 'writephp')) {
645 setEventMessages("NotAllowedToAddDynamicContent", null, 'errors');
646 } elseif (!$replacestring) {
647 setEventMessages("ErrorReplaceStringEmpty", null, 'errors');
648 } else {
649 $nbreplacement = 0;
650
651 foreach ($toselect as $keyselected) {
652 $objectpage = $listofpages['list'][$keyselected];
653 if ($objectpage->pageurl) {
654 dol_syslog("Replace string into page ".$objectpage->pageurl);
655
656 if (GETPOST('optionpcontent', 'aZ09')) {
657 $objectpage->content = str_replace($searchkey, $replacestring, $objectpage->content);
658 }
659 if (GETPOST('optionmeta', 'aZ09')) {
660 $objectpage->title = str_replace($searchkey, $replacestring, $objectpage->title);
661 $objectpage->description = str_replace($searchkey, $replacestring, $objectpage->description);
662 $objectpage->keywords = str_replace($searchkey, $replacestring, $objectpage->keywords);
663 }
664
665 $filealias = $pathofwebsite.'/'.$objectpage->pageurl.'.php';
666 $filetpl = $pathofwebsite.'/page'.$objectpage->id.'.tpl.php';
667
668 // Save page alias
669 $result = dolSavePageAlias($filealias, $object, $objectpage);
670 if (!$result) {
671 setEventMessages('Failed to write file '.basename($filealias), null, 'errors');
672 }
673
674 // Save page of content
675 $result = dolSavePageContent($filetpl, $object, $objectpage, 1);
676 if ($result) {
677 $nbreplacement++;
678 //var_dump($objectpage->content);exit;
679 $objectpage->update($user);
680 } else {
681 $error++;
682 setEventMessages('Failed to write file '.$filetpl, null, 'errors');
683 $action = 'createcontainer';
684 break;
685 }
686 }
687 }
688
689 if ($nbreplacement > 0) {
690 setEventMessages($langs->trans("ReplacementDoneInXPages", $nbreplacement), null, 'mesgs');
691 }
692
693 $containertype = GETPOST('optioncontainertype', 'aZ09') != '-1' ? GETPOST('optioncontainertype', 'aZ09') : '';
694 $langcode = GETPOST('optionlanguage', 'aZ09');
695 $otherfilters = array();
696 if (GETPOSTINT('optioncategory') > 0) {
697 $otherfilters['category'] = GETPOSTINT('optioncategory');
698 }
699
700 // Now we reload list
701 $listofpages = getPagesFromSearchCriterias($containertype, $algo, $searchkey, 1000, $sortfield, $sortorder, $langcode, $otherfilters);
702 }
703}
704
705
706// Add directory
707/*
708if ($action == 'adddir' && $permtouploadfile)
709{
710 $ecmdir->ref = 'NOTUSEDYET';
711 $ecmdir->label = GETPOST("label");
712 $ecmdir->description = GETPOST("desc");
713
714 //$id = $ecmdir->create($user);
715 if ($id > 0)
716 {
717 header("Location: ".$_SERVER["PHP_SELF"]);
718 exit;
719 }
720 else
721 {
722 setEventMessages('Error '.$langs->trans($ecmdir->error), null, 'errors');
723 $action = "createcontainer";
724 }
725
726 clearstatcache();
727}
728*/
729
730// Add a website
731if ($action == 'addsite' && $usercanedit) {
732 $db->begin();
733
734 if (GETPOST('virtualhost', 'alpha') && !preg_match('/^http/', GETPOST('virtualhost', 'alpha'))) {
735 $error++;
736 setEventMessages($langs->trans('ErrorURLMustStartWithHttp', $langs->transnoentitiesnoconv("VirtualHost")), null, 'errors');
737 }
738
739 if (!$error && !GETPOST('WEBSITE_REF', 'alpha')) {
740 $error++;
741 $langs->load("errors");
742 setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities("WebsiteName")), null, 'errors');
743 }
744 if (!$error && !preg_match('/^[a-z0-9_\-\.]+$/i', GETPOST('WEBSITE_REF', 'alpha'))) {
745 $error++;
746 $langs->load("errors");
747 setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities("Ref")), null, 'errors');
748 }
749
750 $tmpobject = null;
751 if (!$error) {
752 $arrayotherlang = explode(',', GETPOST('WEBSITE_OTHERLANG', 'alphanohtml'));
753 foreach ($arrayotherlang as $key => $val) {
754 // It possible we have empty val here if postparam WEBSITE_OTHERLANG is empty or set like this : 'en,,sv' or 'en,sv,'
755 if (empty(trim($val))) {
756 continue;
757 }
758 $arrayotherlang[$key] = substr(trim($val), 0, 2); // Kept short language code only
759 }
760
761 $tmpobject = new Website($db);
762 $tmpobject->ref = GETPOST('WEBSITE_REF', 'alpha');
763 $tmpobject->description = GETPOST('WEBSITE_DESCRIPTION', 'alphanohtml');
764 $tmpobject->lang = GETPOST('WEBSITE_LANG', 'aZ09');
765 $tmpobject->otherlang = implode(',', $arrayotherlang);
766 $tmpobject->virtualhost = GETPOST('virtualhost', 'alpha');
767
768 $result = $tmpobject->create($user);
769 if ($result == 0) {
770 $error++;
771 setEventMessages($langs->trans("ErrorLabelAlreadyExists"), null, 'errors');
772 } elseif ($result < 0) {
773 $error++;
774 setEventMessages($tmpobject->error, $tmpobject->errors, 'errors');
775 }
776 }
777
778 if (!$error && $tmpobject !== null) {
779 $db->commit();
780 setEventMessages($langs->trans("SiteAdded", $object->ref), null, 'mesgs');
781 $action = '';
782
783 header("Location: ".$_SERVER["PHP_SELF"].'?website='.$tmpobject->ref);
784 exit;
785 } else {
786 $db->rollback();
787 $action = 'createsite';
788 }
789
790 if (!$error) {
791 $action = 'preview';
792 $id = $object->id;
793 }
794}
795
796'@phan-var-force int $error';
797
798// Add page/container
799if ($action == 'addcontainer' && $usercanedit) {
800 dol_mkdir($pathofwebsite);
801
802 $db->begin();
803
804 $objectpage->fk_website = $object->id;
805 $objectpage->status = $objectpage::STATUS_DRAFT;
806
807 if (GETPOSTISSET('fetchexternalurl')) { // Fetch from external url
808 $urltograb = GETPOST('externalurl', 'alpha');
809 $grabimages = GETPOSTINT('grabimages') ? 1 : 0;
810 $grabimagesinto = GETPOST('grabimagesinto', 'alpha');
811
812 include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
813 // The include seems to break typing on variables
814
815 if (empty($urltograb)) {
816 $error++;
817 $langs->load("errors");
818 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("URL")), null, 'errors');
819 $action = 'createcontainer';
820 } elseif (!preg_match('/^http/', $urltograb)) {
821 $error++;
822 $langs->load("errors");
823 setEventMessages('Error URL must start with http:// or https://', null, 'errors');
824 $action = 'createcontainer';
825 }
826
827 $pageurl = '';
828 $urltograbdirwithoutslash = '';
829 $urltograbdirrootwithoutslash = '';
830 if (!$error) {
831 // Clean url to grab, so url can be
832 // http://www.example.com/ or http://www.example.com/dir1/ or http://www.example.com/dir1/aaa
833 $urltograbwithoutdomainandparam = preg_replace('/^https?:\/\/[^\/]+\/?/i', '', $urltograb);
834 //$urltograbwithoutdomainandparam = preg_replace('/^file:\/\/[^\/]+\/?/i', '', $urltograb);
835 $urltograbwithoutdomainandparam = preg_replace('/\?.*$/', '', $urltograbwithoutdomainandparam);
836 if (empty($urltograbwithoutdomainandparam) && !preg_match('/\/$/', $urltograb)) {
837 $urltograb .= '/';
838 }
839 $pageurl = dol_sanitizeFileName(preg_replace('/[\/\.]/', '-', preg_replace('/\/+$/', '', $urltograbwithoutdomainandparam)));
840
841 $urltograbdirwithoutslash = dirname($urltograb.'.');
842 $urltograbdirrootwithoutslash = getRootURLFromURL($urltograbdirwithoutslash);
843 // Example, now $urltograbdirwithoutslash is https://www.dolimed.com/screenshots
844 // and $urltograbdirrootwithoutslash is https://www.dolimed.com
845 }
846
847 // Check pageurl is not already used
848 if ($pageurl) {
849 $tmpwebsitepage = new WebsitePage($db);
850 $result = $tmpwebsitepage->fetch(0, (string) $object->id, $pageurl);
851 if ($result > 0) {
852 setEventMessages($langs->trans("AliasPageAlreadyExists", $pageurl), null, 'errors');
853 $error++;
854 $action = 'createcontainer';
855 }
856 }
857
858 if (!$error) {
859 // Download URL to grab
860 $tmp = getURLContent($urltograb, 'GET', '', 1, array(), array('http', 'https'), 0);
861
862 // Test charset of result and convert it into UTF-8 if not in this encoding charset
863 if (!empty($tmp['content_type']) && preg_match('/ISO-8859-1/', $tmp['content_type'])) {
864 if (function_exists('mb_check_encoding')) {
865 if (mb_check_encoding($tmp['content'], 'ISO-8859-1')) {
866 // This is a ISO-8829-1 encoding string
867 $tmp['content'] = mb_convert_encoding($tmp['content'], 'ISO-8859-1', 'UTF-8');
868 } else {
869 $error++;
870 setEventMessages('Error getting '.$urltograb.': content seems non valid ISO-8859-1', null, 'errors');
871 $action = 'createcontainer';
872 }
873 } else {
874 $error++;
875 setEventMessages('Error getting '.$urltograb.': content seems ISO-8859-1 but functions to convert into UTF-8 are not available in your PHP', null, 'errors');
876 $action = 'createcontainer';
877 }
878 }
879 if (empty($tmp['content_type']) || (!empty($tmp['content_type']) && preg_match('/UTF-8/', $tmp['content_type']))) {
880 if (function_exists('mb_check_encoding')) {
881 if (mb_check_encoding($tmp['content'], 'UTF-8')) {
882 // This is a UTF8 or ASCII compatible string
883 } else {
884 $error++;
885 setEventMessages('Error getting '.$urltograb.': content seems not a valid UTF-8', null, 'errors');
886 $action = 'createcontainer';
887 }
888 }
889 }
890
891 if (!empty($tmp['curl_error_no'])) {
892 $error++;
893 setEventMessages('Error getting '.$urltograb.': '.$tmp['curl_error_msg'], null, 'errors');
894 $action = 'createcontainer';
895 } elseif ($tmp['http_code'] != 200) {
896 $error++;
897 setEventMessages('Error getting '.$urltograb.': '.$tmp['http_code'], null, 'errors');
898 $action = 'createcontainer';
899 } else {
900 // Remove comments
901 $tmp['content'] = removeHtmlComment($tmp['content']);
902
903 /* disable this, moved into the create() method
904 // Check there is no PHP content into the imported file (must be only HTML + JS)
905 $phpcontent = dolKeepOnlyPhpCode($tmp['content']);
906 if ($phpcontent) {
907 $error++;
908 setEventMessages('Error getting '.$urltograb.': file that include PHP content is not allowed', null, 'errors');
909 $action = 'createcontainer';
910 }
911 */
912 }
913
914 if (!$error) {
915 $regs = array();
916
917 preg_match('/<head>(.*)<\/head>/ims', $tmp['content'], $regs);
918 $head = $regs[1];
919
920 $objectpage->type_container = 'page';
921 $objectpage->pageurl = $pageurl;
922 if (empty($objectpage->pageurl)) {
923 $tmpdomain = getDomainFromURL($urltograb);
924 $objectpage->pageurl = $tmpdomain.'-home';
925 }
926
927 $objectpage->aliasalt = '';
928
929 if (preg_match('/^(\d+)\-/', basename($urltograb), $regs)) {
930 $objectpage->aliasalt = $regs[1];
931 }
932
933 $regtmp = array();
934 if (preg_match('/<title>(.*)<\/title>/ims', $head, $regtmp)) {
935 $objectpage->title = $regtmp[1];
936 }
937 if (preg_match('/<meta name="title"[^"]+content="([^"]+)"/ims', $head, $regtmp)) {
938 if (empty($objectpage->title)) {
939 $objectpage->title = $regtmp[1]; // If title not found into <title>, we get it from <meta title>
940 }
941 }
942 if (preg_match('/<meta name="description"[^"]+content="([^"]+)"/ims', $head, $regtmp)) {
943 $objectpage->description = $regtmp[1];
944 }
945 if (preg_match('/<meta name="keywords"[^"]+content="([^"]+)"/ims', $head, $regtmp)) {
946 $objectpage->keywords = $regtmp[1];
947 }
948 if (preg_match('/<html\s+lang="([^"]+)"/ims', $tmp['content'], $regtmp)) {
949 $tmplang = explode('-', $regtmp[1]);
950 $objectpage->lang = $tmplang[0].(empty($tmplang[1]) ? '' : '_'.strtoupper($tmplang[1]));
951 }
952
953 $tmp['content'] = preg_replace('/\s*<meta name="generator"[^"]+content="([^"]+)"\s*\/?>/ims', '', $tmp['content']);
954
955 $objectpage->content = $tmp['content'];
956 $objectpage->content = preg_replace('/^.*<body(\s[^>]*)*>/ims', '', $objectpage->content);
957 $objectpage->content = preg_replace('/<\/body(\s[^>]*)*>.*$/ims', '', $objectpage->content);
958
959 // TODO Replace 'action="$urltograbdirwithoutslash' into action="/"
960 // TODO Replace 'action="$urltograbdirwithoutslash..."' into action="..."
961 // TODO Replace 'a href="$urltograbdirwithoutslash' into a href="/"
962 // TODO Replace 'a href="$urltograbdirwithoutslash..."' into a href="..."
963
964 // Now loop to fetch all css files. Include them inline into header of page
965 $objectpage->htmlheader = $tmp['content'];
966 $objectpage->htmlheader = preg_replace('/^.*<head(\s[^>]*)*>/ims', '', $objectpage->htmlheader);
967 $objectpage->htmlheader = preg_replace('/<\/head(\s[^>]*)*>.*$/ims', '', $objectpage->htmlheader);
968 $objectpage->htmlheader = preg_replace('/<base(\s[^>]*)*>\n*/ims', '', $objectpage->htmlheader);
969 $objectpage->htmlheader = preg_replace('/<meta http-equiv="content-type"([^>]*)*>\n*/ims', '', $objectpage->htmlheader);
970 $objectpage->htmlheader = preg_replace('/<meta name="robots"([^>]*)*>\n*/ims', '', $objectpage->htmlheader);
971 $objectpage->htmlheader = preg_replace('/<meta name="title"([^>]*)*>\n*/ims', '', $objectpage->htmlheader);
972 $objectpage->htmlheader = preg_replace('/<meta name="description"([^>]*)*>\n*/ims', '', $objectpage->htmlheader);
973 $objectpage->htmlheader = preg_replace('/<meta name="keywords"([^>]*)*>\n*/ims', '', $objectpage->htmlheader);
974 $objectpage->htmlheader = preg_replace('/<meta name="generator"([^>]*)*>\n*/ims', '', $objectpage->htmlheader);
975 //$objectpage->htmlheader = preg_replace('/<meta name="verify-v1[^>]*>\n*/ims', '', $objectpage->htmlheader);
976 //$objectpage->htmlheader = preg_replace('/<meta name="msvalidate.01[^>]*>\n*/ims', '', $objectpage->htmlheader);
977 $objectpage->htmlheader = preg_replace('/<title>[^<]*<\/title>\n*/ims', '', $objectpage->htmlheader);
978 $objectpage->htmlheader = preg_replace('/<link[^>]*rel="shortcut[^>]*>\n/ims', '', $objectpage->htmlheader);
979 $objectpage->htmlheader = preg_replace('/<link[^>]*rel="alternate[^>]*>\n/ims', '', $objectpage->htmlheader);
980 $objectpage->htmlheader = preg_replace('/<link[^>]*rel="canonical[^>]*>\n/ims', '', $objectpage->htmlheader);
981
982 // Now loop to fetch JS
983 $tmp = $objectpage->htmlheader;
984
985 // We grab files found into <script> tags
986 preg_match_all('/<script([^\.>]+)src=["\']([^"\'>]+)["\']([^>]*)><\/script>/i', $objectpage->htmlheader, $regs);
987 $errorforsubresource = 0;
988 foreach ($regs[0] as $key => $val) {
989 dol_syslog("We will grab the script resource found into script tag ".$regs[2][$key]);
990
991 $linkwithoutdomain = $regs[2][$key];
992 if (preg_match('/^\//', $regs[2][$key])) {
993 $urltograbbis = $urltograbdirrootwithoutslash.$regs[2][$key]; // We use dirroot
994 } else {
995 $urltograbbis = $urltograbdirwithoutslash.'/'.$regs[2][$key]; // We use dir of grabbed file
996 }
997
998 //$filetosave = $conf->medias->multidir_output[$conf->entity].'/css/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key];
999 if (preg_match('/^http/', $regs[2][$key])) {
1000 $urltograbbis = $regs[2][$key];
1001 $linkwithoutdomain = preg_replace('/^https?:\/\/[^\/]+\//i', '', $regs[2][$key]);
1002 //$filetosave = $conf->medias->multidir_output[$conf->entity].'/css/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain;
1003 }
1004
1005 //print $domaintograb.' - '.$domaintograbbis.' - '.$urltograbdirwithoutslash.' - ';
1006 //print $linkwithoutdomain.' - '.$urltograbbis."<br>\n";
1007
1008 // Test if this is an external URL of grabbed web site. If yes, we do not load resource
1009 $domaintograb = getDomainFromURL($urltograbdirwithoutslash);
1010 $domaintograbbis = getDomainFromURL($urltograbbis);
1011 if ($domaintograb != $domaintograbbis) {
1012 continue;
1013 }
1014
1015 /*
1016 $tmpgeturl = getURLContent($urltograbbis, 'GET', '', 1, array(), array('http', 'https'), 0);
1017 if (!empty($tmpgeturl['curl_error_no']))
1018 {
1019 $error++;
1020 setEventMessages('Error getting script url '.$urltograbbis.': '.$tmpgeturl['curl_error_msg'], null, 'errors');
1021 $errorforsubresource++;
1022 $action='createcontainer';
1023 }
1024 elseif ($tmpgeturl['http_code'] != 200)
1025 {
1026 $error++;
1027 setEventMessages('Error getting script url '.$urltograbbis.': '.$tmpgeturl['http_code'], null, 'errors');
1028 $errorforsubresource++;
1029 $action='createcontainer';
1030 }
1031 else
1032 {
1033 dol_mkdir(dirname($filetosave));
1034
1035 $fp = fopen($filetosave, "w");
1036 fputs($fp, $tmpgeturl['content']);
1037 fclose($fp);
1038 dolChmod($file);
1039 }
1040 */
1041
1042 //$filename = 'image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain;
1043 $tmp = preg_replace('/'.preg_quote($regs[0][$key], '/').'/i', '', $tmp);
1044 }
1045 $objectpage->htmlheader = trim($tmp)."\n";
1046
1047
1048 // Now we grab CSS found into <link> tags
1049 $pagecsscontent = "\n".'<style>'."\n";
1050
1051 preg_match_all('/<link([^\.>]+)href=["\']([^"\'>]+\.css[^"\'>]*)["\']([^>]*)>/i', $objectpage->htmlheader, $regs);
1052 $errorforsubresource = 0;
1053 foreach ($regs[0] as $key => $val) {
1054 dol_syslog("We will grab the css resources found into link tag ".$regs[2][$key]);
1055
1056 $linkwithoutdomain = $regs[2][$key];
1057 if (preg_match('/^\//', $regs[2][$key])) {
1058 $urltograbbis = $urltograbdirrootwithoutslash.$regs[2][$key]; // We use dirroot
1059 } else {
1060 $urltograbbis = $urltograbdirwithoutslash.'/'.$regs[2][$key]; // We use dir of grabbed file
1061 }
1062
1063 //$filetosave = $conf->medias->multidir_output[$conf->entity].'/css/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key];
1064 if (preg_match('/^http/', $regs[2][$key])) {
1065 $urltograbbis = $regs[2][$key];
1066 $linkwithoutdomain = preg_replace('/^https?:\/\/[^\/]+\//i', '', $regs[2][$key]);
1067 //$filetosave = $conf->medias->multidir_output[$conf->entity].'/css/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain;
1068 }
1069
1070 //print $domaintograb.' - '.$domaintograbbis.' - '.$urltograbdirwithoutslash.' - ';
1071 //print $linkwithoutdomain.' - '.$urltograbbis."<br>\n";
1072
1073 // Test if this is an external URL of grabbed web site. If yes, we do not load resource
1074 $domaintograb = getDomainFromURL($urltograbdirwithoutslash);
1075 $domaintograbbis = getDomainFromURL($urltograbbis);
1076 if ($domaintograb != $domaintograbbis) {
1077 continue;
1078 }
1079
1080 $tmpgeturl = getURLContent($urltograbbis, 'GET', '', 1, array(), array('http', 'https'), 0);
1081 if (!empty($tmpgeturl['curl_error_no'])) {
1082 $errorforsubresource++;
1083 setEventMessages('Error getting link tag url '.$urltograbbis.': '.$tmpgeturl['curl_error_msg'], null, 'errors');
1084 dol_syslog('Error getting '.$urltograbbis.': '.$tmpgeturl['curl_error_msg']);
1085 $action = 'createcontainer';
1086 } elseif ($tmpgeturl['http_code'] != 200) {
1087 $errorforsubresource++;
1088 setEventMessages('Error getting link tag url '.$urltograbbis.': '.$tmpgeturl['http_code'], null, 'errors');
1089 dol_syslog('Error getting '.$urltograbbis.': '.$tmpgeturl['curl_error_msg']);
1090 $action = 'createcontainer';
1091 } else {
1092 // Clean some comment
1093 //$tmpgeturl['content'] = dol_string_is_good_iso($tmpgeturl['content'], 1);
1094 //$tmpgeturl['content'] = mb_convert_encoding($tmpgeturl['content'], 'UTF-8', 'UTF-8');
1095 //$tmpgeturl['content'] = remove_bs($tmpgeturl['content']);
1096 //$tmpgeturl['content'] = str_replace('$screen-md-max', 'auto', $tmpgeturl['content']);
1097
1098 //var_dump($tmpgeturl['content']);exit;
1099 $tmpgeturl['content'] = preg_replace('/\/\*\s+CSS content[a-z\s]*\s+\*\//', '', $tmpgeturl['content']);
1100
1101 //dol_mkdir(dirname($filetosave));
1102
1103 //$fp = fopen($filetosave, "w");
1104 //fputs($fp, $tmpgeturl['content']);
1105 //fclose($fp);
1106 //dolChmod($file);
1107
1108 // $filename = 'image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain;
1109 $pagecsscontent .= "\n".'/* Content of file '.$urltograbbis.' */'."\n";
1110
1111 getAllImages($object, $objectpage, $urltograbbis, $tmpgeturl['content'], $action, 1, $grabimages, $grabimagesinto);
1112
1113 // We try to convert the CSS we got by adding a prefix .bodywebsite with lessc to avoid conflict with CSS of Dolibarr.
1114 include_once DOL_DOCUMENT_ROOT.'/core/class/lessc.class.php';
1115 $lesscobj = new Lessc();
1116 try {
1117 $contentforlessc = ".bodywebsite {\n".$tmpgeturl['content']."\n}\n";
1118 //print '<pre>'.$contentforlessc.'</pre>';
1119 $contentforlessc = $lesscobj->compile($contentforlessc);
1120 //var_dump($contentforlessc); exit;
1121
1122 $pagecsscontent .= $contentforlessc."\n";
1123 //$pagecsscontent.=$tmpgeturl['content']."\n";
1124 } catch (Exception $e) {
1125 //echo "failed to compile lessc";
1126 dol_syslog("Failed to compile the CSS from URL ".$urltograbbis." with lessc: ".$e->getMessage(), LOG_WARNING);
1127 $pagecsscontent .= $tmpgeturl['content']."\n";
1128 }
1129
1130 $objectpage->htmlheader = preg_replace('/'.preg_quote($regs[0][$key], '/').'\n*/ims', '', $objectpage->htmlheader);
1131 }
1132 }
1133
1134 $pagecsscontent .= '</style>';
1135 //var_dump($pagecsscontent);
1136
1137 //print dol_escape_htmltag($tmp);exit;
1138 $objectpage->htmlheader .= trim($pagecsscontent)."\n";
1139
1140
1141 // Now we have to fetch all images into page
1142 $tmp = $objectpage->content;
1143
1144 getAllImages($object, $objectpage, $urltograb, $tmp, $action, 1, $grabimages, $grabimagesinto);
1145
1146 // Normalize links href to Dolibarr internal naming
1147 $tmp = preg_replace('/a href="\/([^\/"]+)\/([^\/"]+)"/', 'a href="/\1-\2.php"', $tmp);
1148 $tmp = preg_replace('/a href="\/([^\/"]+)\/([^\/"]+)\/([^\/"]+)"/', 'a href="/\1-\2-\3.php"', $tmp);
1149 $tmp = preg_replace('/a href="\/([^\/"]+)\/([^\/"]+)\/([^\/"]+)\/([^\/"]+)"/', 'a href="/\1-\2-\3-\4.php"', $tmp);
1150
1151 //print dol_escape_htmltag($tmp);exit;
1152 $objectpage->content = $tmp;
1153
1154 $objectpage->grabbed_from = $urltograb;
1155 }
1156 }
1157 } else { // add website from scratch
1158 $newaliasnames = '';
1159 if (!$error && GETPOST('WEBSITE_ALIASALT', 'alpha')) {
1160 $arrayofaliastotest = explode(',', str_replace(array('<', '>'), '', GETPOST('WEBSITE_ALIASALT', 'alpha')));
1161 $websitepagetemp = new WebsitePage($db);
1162 foreach ($arrayofaliastotest as $aliastotest) {
1163 $aliastotest = trim(preg_replace('/\.php$/i', '', $aliastotest));
1164
1165 // Disallow alias name pageX (already used to save the page with id)
1166 if (preg_match('/^page\d+/i', $aliastotest)) {
1167 $error++;
1168 $langs->load("errors");
1169 setEventMessages("Alias name 'pageX' is not allowed", null, 'errors');
1170 $action = 'createcontainer';
1171 break;
1172 } else {
1173 $result = $websitepagetemp->fetch(0, (string) $object->id, $aliastotest);
1174 if ($result < 0) {
1175 $error++;
1176 $langs->load("errors");
1177 setEventMessages($websitepagetemp->error, $websitepagetemp->errors, 'errors');
1178 $action = 'createcontainer';
1179 break;
1180 }
1181 if ($result > 0) {
1182 $error++;
1183 $langs->load("errors");
1184 setEventMessages($langs->trans("ErrorAPageWithThisNameOrAliasAlreadyExists", $websitepagetemp->pageurl), null, 'errors');
1185 $action = 'createcontainer';
1186 break;
1187 }
1188 $newaliasnames .= ($newaliasnames ? ', ' : '').$aliastotest;
1189 }
1190 }
1191 }
1192
1193 $objectpage->title = str_replace(array('<', '>'), '', GETPOST('WEBSITE_TITLE', 'alphanohtml'));
1194 $objectpage->type_container = GETPOST('WEBSITE_TYPE_CONTAINER', 'aZ09');
1195 $objectpage->pageurl = dol_sanitizeUrl(GETPOST('WEBSITE_PAGENAME', 'alpha'));
1196 $objectpage->ref = $objectpage->pageurl;
1197 $objectpage->aliasalt = $newaliasnames;
1198 $objectpage->description = str_replace(array('<', '>'), '', GETPOST('WEBSITE_DESCRIPTION', 'alphanohtml'));
1199 $objectpage->lang = GETPOST('WEBSITE_LANG', 'aZ09');
1200 $objectpage->otherlang = GETPOST('WEBSITE_OTHERLANG', 'aZ09comma');
1201 $objectpage->image = GETPOST('WEBSITE_IMAGE', 'alpha');
1202 $objectpage->keywords = str_replace(array('<', '>'), '', GETPOST('WEBSITE_KEYWORDS', 'alphanohtml'));
1203 $objectpage->allowed_in_frames = GETPOST('WEBSITE_ALLOWED_IN_FRAMES', 'aZ09') ? 1 : 0;
1204 $objectpage->htmlheader = GETPOST('htmlheader', 'restricthtmlallowlinkscript'); // Must accept tags like '<script>' and '<link>'
1205
1206 $objectpage->author_alias = GETPOST('WEBSITE_AUTHORALIAS', 'alphanohtml');
1207 $objectpage->object_type = GETPOST('WEBSITE_OBJECTCLASS');
1208 $objectpage->fk_object = GETPOST('WEBSITE_OBJECTID');
1209 $substitutionarray = array();
1210 $substitutionarray['__WEBSITE_CREATED_BY__'] = $user->getFullName($langs);
1211
1212 // Define id of the page the new page is translation of
1213 /*
1214 if ($objectpage->lang == $object->lang) {
1215 // If
1216 $pageidfortranslation = (GETPOSTINT('pageidfortranslation') > 0 ? GETPOSTINT('pageidfortranslation') : 0);
1217 if ($pageidfortranslation > 0) {
1218 // We must update the page $pageidfortranslation to set fk_page = $object->id.
1219 // But what if page $pageidfortranslation is already linked to another ?
1220 }
1221 } else {
1222 */
1223 $pageidfortranslation = (GETPOSTINT('pageidfortranslation') > 0 ? GETPOSTINT('pageidfortranslation') : 0);
1224 if ($pageidfortranslation > 0) {
1225 // Check if the page we are translation of is already a translation of a source page. if yes, we will use source id instead
1226 $objectpagetmp = new WebsitePage($db);
1227 $objectpagetmp->fetch($pageidfortranslation);
1228 if ($objectpagetmp->fk_page > 0) {
1229 $pageidfortranslation = $objectpagetmp->fk_page;
1230 }
1231 }
1232 $objectpage->fk_page = $pageidfortranslation;
1233 //}
1234
1235 $content = '';
1236 if (GETPOSTISSET('content')) {
1237 //$content = GETPOST('content', 'restricthtmlallowunvalid'); // @TODO Use a restricthtmlallowunvalidwithphp
1238 $content = GETPOST('content', 'none'); // @TODO Use a restricthtmlallowunvalidwithphp
1239
1240 $objectpage->content = make_substitutions($content, $substitutionarray);
1241 } else {
1242 /*$sample = GETPOST('sample', 'alpha');
1243 if (empty($sample)) {
1244 $sample = 'empty';
1245 }
1246
1247 $pathtosample = DOL_DOCUMENT_ROOT.'/website/samples/page-sample-'.dol_sanitizeFileName(strtolower($sample)).'.html';
1248 */
1249 // Init content with content into page-sample-...
1250 //$objectpage->content = make_substitutions(@file_get_contents($pathtosample), $substitutionarray);
1251 }
1252 }
1253
1254 if (!$error) {
1255 if (empty($objectpage->pageurl)) {
1256 $langs->load("errors");
1257 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_PAGENAME")), null, 'errors');
1258 $error++;
1259 $action = 'createcontainer';
1260 } elseif (!preg_match('/^[a-z0-9\-\_]+$/i', $objectpage->pageurl)) {
1261 $langs->load("errors");
1262 setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities('WEBSITE_PAGENAME')), null, 'errors');
1263 $error++;
1264 $action = 'createcontainer';
1265 }
1266 if (empty($objectpage->title)) {
1267 $langs->load("errors");
1268 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_TITLE")), null, 'errors');
1269 $error++;
1270 $action = 'createcontainer';
1271 }
1272 if ($objectpage->fk_page > 0 && empty($objectpage->lang)) {
1273 $langs->load("errors");
1274 setEventMessages($langs->trans("ErrorLanguageRequiredIfPageIsTranslationOfAnother"), null, 'errors');
1275 $error++;
1276 $action = 'createcontainer';
1277 }
1278 if ($objectpage->fk_page > 0 && !empty($objectpage->lang)) {
1279 if ($objectpage->lang == $website->lang) {
1280 $langs->load("errors");
1281 setEventMessages($langs->trans("ErrorLanguageMustNotBeSourceLanguageIfPageIsTranslationOfAnother"), null, 'errors');
1282 $error++;
1283 $action = 'createcontainer';
1284 }
1285 }
1286 }
1287
1288 $pageid = 0;
1289 if (!$error) {
1290 // Create page. This also check there is no PHP content if user has no permissions for that.
1291 $pageid = $objectpage->create($user);
1292 if ($pageid <= 0) {
1293 $error++;
1294 setEventMessages($objectpage->error, $objectpage->errors, 'errors');
1295 $action = 'createcontainer';
1296 }
1297 }
1298
1299 if (!$error) {
1300 // Website categories association
1301 $categoriesarray = GETPOST('categories', 'array:int');
1302 $result = $objectpage->setCategories($categoriesarray);
1303 if ($result < 0) {
1304 $error++;
1305 setEventMessages($object->error, $object->errors, 'errors');
1306 }
1307 }
1308
1309 if (!$error) {
1310 // If there is no home page yet, this new page will be set as the home page
1311 if (empty($object->fk_default_home)) {
1312 $object->fk_default_home = $pageid;
1313 $res = $object->update($user);
1314 if ($res <= 0) {
1315 $error++;
1316 setEventMessages($object->error, $object->errors, 'errors');
1317 } else {
1318 $filetpl = $pathofwebsite.'/page'.$pageid.'.tpl.php';
1319
1320 // Generate the index.php page (to be the home page) and the wrapper.php file
1321 $result = dolSaveIndexPage($pathofwebsite, $fileindex, $filetpl, $filewrapper, $object);
1322
1323 if ($result <= 0) {
1324 setEventMessages('Failed to write file '.$fileindex, null, 'errors');
1325 }
1326 }
1327 }
1328 }
1329
1330 if (!$error) {
1331 if ($pageid > 0) {
1332 $filealias = $pathofwebsite.'/'.$objectpage->pageurl.'.php';
1333 $filetpl = $pathofwebsite.'/page'.$objectpage->id.'.tpl.php';
1334
1335 // Save page alias
1336 $result = dolSavePageAlias($filealias, $object, $objectpage);
1337 if (!$result) {
1338 setEventMessages('Failed to write file '.basename($filealias), null, 'errors');
1339 }
1340
1341 // Save page of content
1342 $result = dolSavePageContent($filetpl, $object, $objectpage, 1);
1343 if ($result) {
1344 setEventMessages($langs->trans("Saved"), null, 'mesgs');
1345 } else {
1346 setEventMessages('Failed to write file '.$filetpl, null, 'errors');
1347 $action = 'createcontainer';
1348 }
1349 }
1350 }
1351
1352 if (!$error) {
1353 $db->commit();
1354 setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs');
1355 $action = '';
1356 } else {
1357 $db->rollback();
1358 }
1359
1360 if (!$error) {
1361 $pageid = $objectpage->id;
1362
1363 // To generate the CSS, robot and htmlheader file.
1364
1365 // Check symlink documents/website/mywebsite/medias to point to documents/medias and restore it if ko.
1366 // Recreate also dir of website if not found.
1367 $pathtomedias = DOL_DATA_ROOT.'/medias';
1368 $pathtomediasinwebsite = $pathofwebsite.'/medias';
1369 if (!is_link(dol_osencode($pathtomediasinwebsite))) {
1370 dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite);
1371 dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure that the directory for website exists
1372 $result = symlink($pathtomedias, $pathtomediasinwebsite);
1373 if (!$result) {
1374 $langs->load("errors");
1375 setEventMessages($langs->trans("ErrorFailedToCreateSymLinkToMedias", $pathtomediasinwebsite, $pathtomedias), null, 'errors');
1376 }
1377 }
1378
1379 // Now generate the master.inc.php page if it does not exists yet
1380 if (!dol_is_file($filemaster)) {
1381 $result = dolSaveMasterFile($filemaster);
1382 if (!$result) {
1383 $error++;
1384 setEventMessages('Failed to write file '.$filemaster, null, 'errors');
1385 }
1386 }
1387
1388 if (!dol_is_file($filehtmlheader)) {
1389 $htmlheadercontent = "<html>\n";
1390 $htmlheadercontent .= $htmlheadercontentdefault;
1391 $htmlheadercontent .= "</html>";
1392 $result = dolSaveHtmlHeader($filehtmlheader, $htmlheadercontent);
1393 }
1394
1395 if (!dol_is_file($filecss)) {
1396 $csscontent = "/* CSS content (all pages) */\nbody.bodywebsite { margin: 0; font-family: 'Open Sans', sans-serif; }\n.bodywebsite h1 { margin-top: 0; margin-bottom: 0; padding: 10px;}";
1397 $result = dolSaveCssFile($filecss, $csscontent);
1398 }
1399
1400 if (!dol_is_file($filejs)) {
1401 $jscontent = "/* JS content (all pages) */\n";
1402 $result = dolSaveJsFile($filejs, $jscontent);
1403 }
1404
1405 if (!dol_is_file($filerobot)) {
1406 $robotcontent = "# Robot file. Generated with Dolibarr\nUser-agent: *\nAllow: /public/\nDisallow: /administrator/";
1407 $result = dolSaveRobotFile($filerobot, $robotcontent);
1408 }
1409
1410 if (!dol_is_file($filehtaccess)) {
1411 $htaccesscontent = "# Order allow,deny\n# Deny from all";
1412 $result = dolSaveHtaccessFile($filehtaccess, $htaccesscontent);
1413 }
1414
1415 if (!dol_is_file($filemanifestjson)) {
1416 $manifestjsoncontent = "";
1417 $result = dolSaveManifestJson($filemanifestjson, $manifestjsoncontent);
1418 }
1419
1420 if (!dol_is_file($filereadme)) {
1421 $readmecontent = "Website generated by Dolibarr ERP CRM";
1422 $result = dolSaveReadme($filereadme, $readmecontent);
1423 }
1424
1425 if (!dol_is_file($filelicense)) {
1426 $licensecontent = "LICENSE\n-------\nThis website template content (HTML and PHP code) is published under the license CC-BY-SA - https://creativecommons.org/licenses/by/4.0/";
1427 $result = dolSaveLicense($filelicense, $licensecontent);
1428 }
1429
1430 $action = 'preview';
1431 }
1432}
1433
1434// Delete site
1435if ($action == 'confirm_deletesite' && $confirm == 'yes' && $permissiontodelete) {
1436 $error = 0;
1437
1438 $db->begin();
1439
1440 $res = $object->fetch(GETPOSTINT('id'));
1441 $website = $object;
1442
1443 if ($res > 0) {
1444 $object->oldcopy = dol_clone($object, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
1445 $res = $object->delete($user);
1446 if ($res <= 0) {
1447 $error++;
1448 setEventMessages($object->error, $object->errors, 'errors');
1449 }
1450 }
1451 if (!$error) {
1452 if (GETPOST('delete_also_js', 'alpha') == 'on') {
1453 $pathofwebsitejs = DOL_DATA_ROOT.'/medias/js/'.$object->ref;
1454
1455 dol_delete_dir_recursive($pathofwebsitejs);
1456 }
1457 if (GETPOST('delete_also_medias', 'alpha') == 'on') {
1458 $pathofwebsitemedias = DOL_DATA_ROOT.'/medias/image/'.$object->ref;
1459
1460 dol_delete_dir_recursive($pathofwebsitemedias);
1461 }
1462 }
1463
1464 if (!$error) {
1465 $db->commit();
1466 setEventMessages($langs->trans("SiteDeleted", $object->ref), null, 'mesgs');
1467
1468 header("Location: ".$_SERVER["PHP_SELF"].'?id='.$object->id);
1469 exit;
1470 } else {
1471 $db->rollback();
1472 setEventMessages($object->error, $object->errors, 'errors');
1473 }
1474}
1475
1476// Delete page (from website page menu)
1477if (GETPOSTISSET('pageid') && $action == 'delete' && $permissiontodelete && !GETPOST('file_manager')) {
1478 $error = 0;
1479
1480 $db->begin();
1481
1482 $res = $object->fetch(0, $websitekey);
1483 $website = $object;
1484
1485 $res = $objectpage->fetch($pageid, (string) $object->id);
1486
1487 if ($res > 0) {
1488 $res = $objectpage->delete($user);
1489 if ($res <= 0) {
1490 $error++;
1491 setEventMessages($objectpage->error, $objectpage->errors, 'errors');
1492 }
1493 }
1494
1495 if (!$error) {
1496 $db->commit();
1497 setEventMessages($langs->trans("PageDeleted", $objectpage->pageurl, $websitekey), null, 'mesgs');
1498
1499 header("Location: ".$_SERVER["PHP_SELF"].'?website='.$websitekey);
1500 exit;
1501 } else {
1502 $db->rollback();
1503 dol_print_error($db);
1504 }
1505}
1506// Delete page (from menu search)
1507if (!GETPOSTISSET('pageid')) {
1508 $objectclass = 'WebsitePage';
1509
1510 // Add part of code from actions_massactions.inc.php
1511 // Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before)
1512 if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permissiontodelete) {
1513 $db->begin();
1514
1515 $objecttmp = new $objectclass($db);
1516 $nbok = 0;
1517 foreach ($toselect as $toselectid) {
1518 $result = $objecttmp->fetch($toselectid);
1519 if ($result > 0) {
1520 $result = $objecttmp->delete($user);
1521
1522 if ($result <= 0) {
1523 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1524 $error++;
1525 break;
1526 } else {
1527 $nbok++;
1528 }
1529 } else {
1530 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1531 $error++;
1532 break;
1533 }
1534 }
1535
1536 if (!$error) {
1537 if ($nbok > 1) {
1538 setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
1539 } else {
1540 setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
1541 }
1542 $db->commit();
1543 } else {
1544 $db->rollback();
1545 }
1546 //var_dump($listofobjectthirdparties);exit;
1547 }
1548
1549 if ($action == 'delete') { // Test on permission not required here
1550 $mode = 'replacesite';
1551 $action = 'replacesite';
1552
1553 $containertype = GETPOST('optioncontainertype', 'aZ09') != '-1' ? GETPOST('optioncontainertype', 'aZ09') : '';
1554 $langcode = GETPOST('optionlanguage', 'aZ09');
1555 $otherfilters = array();
1556 if (GETPOSTINT('optioncategory') > 0) {
1557 $otherfilters['category'] = GETPOSTINT('optioncategory');
1558 }
1559
1560 $listofpages = getPagesFromSearchCriterias($containertype, $algo, $searchkey, 1000, $sortfield, $sortorder, $langcode, $otherfilters);
1561 }
1562}
1563
1564// Update css site properties. Re-generates also the wrapper.
1565if ($action == 'updatecss' && $usercanedit) {
1566 // If we tried to reload another site/page, we stay on editcss mode.
1567 if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x') || GETPOST('refreshpage') || GETPOST('refreshpage_x') || GETPOST('refreshpage.x')) {
1568 $action = 'editcss';
1569 } else {
1570 $res = $object->fetch(0, $websitekey);
1571 $website = $object;
1572
1573 if (GETPOSTISSET('virtualhost')) {
1574 $tmpvirtualhost = preg_replace('/\/$/', '', GETPOST('virtualhost', 'alpha'));
1575 if ($tmpvirtualhost && !preg_match('/^http/', $tmpvirtualhost)) {
1576 $error++;
1577 setEventMessages($langs->trans('ErrorURLMustStartWithHttp', $langs->transnoentitiesnoconv("VirtualHost")), null, 'errors');
1578 $action = 'editcss';
1579 }
1580
1581 if (!$error) {
1582 $arrayotherlang = explode(',', GETPOST('WEBSITE_OTHERLANG', 'alphanohtml'));
1583 foreach ($arrayotherlang as $key => $val) {
1584 // It possible we have empty val here if postparam WEBSITE_OTHERLANG is empty or set like this : 'en,,sv' or 'en,sv,'
1585 if (empty(trim($val))) {
1586 continue;
1587 }
1588 $arrayotherlang[$key] = substr(trim($val), 0, 2); // Kept short language code only
1589 }
1590
1591 $object->virtualhost = $tmpvirtualhost;
1592 $object->lang = GETPOST('WEBSITE_LANG', 'aZ09');
1593 $object->otherlang = implode(',', $arrayotherlang);
1594 $object->use_manifest = GETPOSTINT('use_manifest');
1595
1596 $result = $object->update($user);
1597 if ($result < 0) {
1598 $error++;
1599 setEventMessages($object->error, $object->errors, 'errors');
1600 $action = 'editcss';
1601 }
1602 }
1603 }
1604
1605 if (!$error) {
1606 if (($_FILES['addedfile']["name"] != '')) {
1607 $uploadfolder = $conf->website->dir_output.'/'.$websitekey;
1608 if ($_FILES['addedfile']['type'] != 'image/png') {
1609 $error++;
1610 setEventMessages($langs->trans('ErrorFaviconType'), array(), 'errors');
1611 }
1612 $filetoread = realpath(dol_osencode($_FILES['addedfile']['tmp_name']));
1613 $filesize = getimagesize($filetoread);
1614 if ($filesize[0] != $filesize[1]) {
1615 $error++;
1616 setEventMessages($langs->trans('ErrorFaviconMustBeASquaredImage'), array(), 'errors');
1617 }
1618 if (! $error && ($filesize[0] != 16 && $filesize[0] != 32 && $filesize[0] != 64)) {
1619 $error++;
1620 setEventMessages($langs->trans('ErrorFaviconSize'), array(), 'errors');
1621 }
1622 if (!$error) {
1623 dol_add_file_process($uploadfolder, 1, 0, 'addedfile', 'favicon.png');
1624 }
1625 }
1626 if ($error) {
1627 if (!GETPOSTISSET('updateandstay')) { // If we click on "Save And Stay", we don not make the redirect
1628 $action = 'preview';
1629 if ($backtopage) {
1630 $backtopage = preg_replace('/searchstring=[^&]*/', '', $backtopage); // Clean backtopage url
1631 header("Location: ".$backtopage);
1632 exit;
1633 }
1634 } else {
1635 $action = 'editcss';
1636 }
1637 }
1638 }
1639
1640 if (!$error) {
1641 // Save master.inc.php file
1642 dol_syslog("Save master file ".$filemaster);
1643
1644 dol_mkdir($pathofwebsite);
1645
1646 // Now generate the master.inc.php page
1647 $result = dolSaveMasterFile($filemaster);
1648 if (!$result) {
1649 $error++;
1650 setEventMessages('Failed to write file '.$filemaster, null, 'errors');
1651 }
1652
1653
1654 $dataposted = trim(GETPOST('WEBSITE_HTML_HEADER', 'restricthtmlallowlinkscript')); // Must accept tags like '<script>' and '<link>'
1655
1656 $dataposted = preg_replace(array('/<html>\n*/ims', '/<\/html>\n*/ims'), array('', ''), $dataposted);
1657 $dataposted = str_replace('<?=', '<?php', $dataposted);
1658
1659 // Html header file
1660 $phpfullcodestringold = '';
1661 $phpfullcodestring = dolKeepOnlyPhpCode($dataposted);
1662
1663 // Security analysis
1664 $errorphpcheck = checkPHPCode($phpfullcodestringold, $phpfullcodestring); // Contains the setEventMessages
1665
1666 if (!$errorphpcheck) {
1667 $htmlheadercontent = '';
1668
1669 /* We disable php code since global htmlheader for all website is never executed as an include but only read by fgets_content.
1670 $htmlheadercontent.= "<?php // BEGIN PHP\n";
1671 $htmlheadercontent.= '$websitekey=basename(__DIR__);'."\n";
1672 $htmlheadercontent.= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once './master.inc.php'; } // Load env if not already loaded"."\n";
1673 $htmlheadercontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
1674 $htmlheadercontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
1675 $htmlheadercontent.= "ob_start();\n";
1676 // $htmlheadercontent.= "header('Content-type: text/html');\n"; // Not required. htmlheader.html is never call as a standalone page
1677 $htmlheadercontent.= "// END PHP ?>\n";*/
1678
1679 $htmlheadercontent .= $dataposted."\n";
1680
1681 /*$htmlheadercontent.= "\n".'<?php // BEGIN PHP'."\n";
1682 $htmlheadercontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp);'."\n";
1683 $htmlheadercontent.= "// END PHP"."\n";*/
1684
1685 $result = dolSaveHtmlHeader($filehtmlheader, $htmlheadercontent);
1686 if (!$result) {
1687 $error++;
1688 setEventMessages('Failed to write file '.$filehtmlheader, null, 'errors');
1689 }
1690 } else {
1691 $error++;
1692 }
1693
1694 $dataposted = trim(GETPOST('WEBSITE_CSS_INLINE', 'none'));
1695 $dataposted = str_replace('<?=', '<?php', $dataposted);
1696
1697 // Css file
1698 $phpfullcodestringold = '';
1699 $phpfullcodestring = dolKeepOnlyPhpCode($dataposted);
1700
1701 // Security analysis
1702 $errorphpcheck = checkPHPCode($phpfullcodestringold, $phpfullcodestring); // Contains the setEventMessages
1703
1704 if (!$errorphpcheck) {
1705 $csscontent = '';
1706
1707 $csscontent .= "<?php // BEGIN PHP\n";
1708 $csscontent .= '$websitekey=basename(__DIR__);'."\n";
1709 $csscontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded\n"; // For the css, we need to set path of master using the dirname of css file.
1710 $csscontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
1711 $csscontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
1712 $csscontent .= "ob_start();\n";
1713 $csscontent .= "if (! headers_sent()) { /* because file is included inline when in edit mode and we don't want warning */ \n";
1714 $csscontent .= "header('Cache-Control: max-age=3600, public, must-revalidate');\n";
1715 $csscontent .= "header('Content-type: text/css');\n";
1716 $csscontent .= "}\n";
1717 $csscontent .= "// END PHP ?>\n";
1718
1719 $csscontent .= $dataposted."\n";
1720
1721 $csscontent .= '<?php // BEGIN PHP'."\n";
1722 $csscontent .= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "css");'."\n";
1723 $csscontent .= "// END PHP\n";
1724
1725 dol_syslog("Save css content into ".$filecss);
1726
1727 $result = dolSaveCssFile($filecss, $csscontent);
1728 if (!$result) {
1729 $error++;
1730 setEventMessages('Failed to write file '.$filecss, null, 'errors');
1731 }
1732 } else {
1733 $error++;
1734 }
1735
1736
1737 $dataposted = trim(GETPOST('WEBSITE_JS_INLINE', 'none'));
1738 $dataposted = str_replace('<?=', '<?php', $dataposted);
1739
1740 // Js file
1741 $phpfullcodestringold = '';
1742 $phpfullcodestring = dolKeepOnlyPhpCode($dataposted);
1743
1744 // Security analysis
1745 $errorphpcheck = checkPHPCode($phpfullcodestringold, $phpfullcodestring); // Contains the setEventMessages
1746
1747 if (!$errorphpcheck) {
1748 $jscontent = '';
1749
1750 $jscontent .= "<?php // BEGIN PHP\n";
1751 $jscontent .= '$websitekey=basename(__DIR__);'."\n";
1752 $jscontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded\n"; // For the css, we need to set path of master using the dirname of css file.
1753 $jscontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
1754 $jscontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
1755 $jscontent .= "ob_start();\n";
1756 $jscontent .= "header('Cache-Control: max-age=3600, public, must-revalidate');\n";
1757 $jscontent .= "header('Content-type: application/javascript');\n";
1758 $jscontent .= "// END PHP ?>\n";
1759
1760 $jscontent .= $dataposted."\n";
1761
1762 $jscontent .= '<?php // BEGIN PHP'."\n";
1763 $jscontent .= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "js");'."\n";
1764 $jscontent .= "// END PHP\n";
1765
1766 $result = dolSaveJsFile($filejs, $jscontent);
1767 if (!$result) {
1768 $error++;
1769 setEventMessages('Failed to write file '.$filejs, null, 'errors');
1770 }
1771 } else {
1772 $error++;
1773 }
1774
1775 $dataposted = trim(GETPOST('WEBSITE_ROBOT', 'nohtml')); // We must use 'nohtml' and not 'alphanohtml' because we must accept "
1776 $dataposted = str_replace('<?=', '<?php', $dataposted);
1777
1778 // Robot file
1779 $phpfullcodestringold = '';
1780 $phpfullcodestring = dolKeepOnlyPhpCode($dataposted);
1781
1782 // Security analysis
1783 $errorphpcheck = checkPHPCode($phpfullcodestringold, $phpfullcodestring); // Contains the setEventMessages
1784
1785 if (!$errorphpcheck) {
1786 $robotcontent = '';
1787
1788 /*$robotcontent.= "<?php // BEGIN PHP\n";
1789 $robotcontent.= '$websitekey=basename(__DIR__);'."\n";
1790 $robotcontent.= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once './master.inc.php'; } // Load env if not already loaded"."\n";
1791 $robotcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
1792 $robotcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
1793 $robotcontent.= "ob_start();\n";
1794 $robotcontent.= "header('Cache-Control: max-age=3600, public, must-revalidate');\n";
1795 $robotcontent.= "header('Content-type: text/css');\n";
1796 $robotcontent.= "// END PHP ?>\n";*/
1797
1798 $robotcontent .= $dataposted."\n";
1799
1800 /*$robotcontent.= "\n".'<?php // BEGIN PHP'."\n";
1801 $robotcontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "robot");'."\n";
1802 $robotcontent.= "// END PHP ?>"."\n";*/
1803
1804 $result = dolSaveRobotFile($filerobot, $robotcontent);
1805 if (!$result) {
1806 $error++;
1807 setEventMessages('Failed to write file '.$filerobot, null, 'errors');
1808 }
1809 } else {
1810 $error++;
1811 }
1812
1813 $dataposted = trim(GETPOST('WEBSITE_HTACCESS', 'nohtml')); // We must use 'nohtml' and not 'alphanohtml' because we must accept "
1814 $dataposted = str_replace('<?=', '<?php', $dataposted);
1815
1816 // Htaccess file
1817 $phpfullcodestringold = '';
1818 $phpfullcodestring = dolKeepOnlyPhpCode($dataposted);
1819
1820 // Security analysis
1821 $errorphpcheck = checkPHPCode($phpfullcodestringold, $phpfullcodestring); // Contains the setEventMessages
1822
1823 if (!$errorphpcheck) {
1824 if ($dataposted) {
1825 $htaccesscontent = '';
1826 $htaccesscontent .= $dataposted."\n";
1827
1828 $result = dolSaveHtaccessFile($filehtaccess, $htaccesscontent);
1829 if (!$result) {
1830 $error++;
1831 setEventMessages('Failed to write file '.$filehtaccess, null, 'errors');
1832 }
1833 } else {
1834 dol_delete_file($filehtaccess, 0, 0);
1835 }
1836 } else {
1837 $error++;
1838 }
1839
1840
1841 $dataposted = trim(GETPOST('WEBSITE_MANIFEST_JSON', 'restricthtmlallowunvalid'));
1842 $dataposted = str_replace('<?=', '<?php', $dataposted);
1843
1844 // Manifest.json file
1845 $phpfullcodestringold = '';
1846 $phpfullcodestring = dolKeepOnlyPhpCode($dataposted);
1847
1848 // Security analysis
1849 $errorphpcheck = checkPHPCode($phpfullcodestringold, $phpfullcodestring); // Contains the setEventMessages
1850
1851 if (!$errorphpcheck) {
1852 $manifestjsoncontent = '';
1853
1854 $manifestjsoncontent .= "<?php // BEGIN PHP\n";
1855 $manifestjsoncontent .= '$websitekey=basename(__DIR__);'."\n";
1856 $manifestjsoncontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded\n"; // For the css, we need to set path of master using the dirname of css file.
1857 $manifestjsoncontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
1858 $manifestjsoncontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
1859 $manifestjsoncontent .= "ob_start();\n";
1860 $manifestjsoncontent .= "header('Cache-Control: max-age=3600, public, must-revalidate');\n";
1861 $manifestjsoncontent .= "header('Content-type: application/manifest+json');\n";
1862 $manifestjsoncontent .= "// END PHP ?>\n";
1863
1864 $manifestjsoncontent .= $dataposted."\n";
1865
1866 $manifestjsoncontent .= '<?php // BEGIN PHP'."\n";
1867 $manifestjsoncontent .= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "manifest");'."\n";
1868 $manifestjsoncontent .= "// END PHP\n";
1869
1870 $result = dolSaveManifestJson($filemanifestjson, $manifestjsoncontent);
1871 if (!$result) {
1872 $error++;
1873 setEventMessages('Failed to write file '.$filemanifestjson, null, 'errors');
1874 }
1875 } else {
1876 $error++;
1877 }
1878
1879
1880 $dataposted = trim(GETPOST('WEBSITE_README', 'nohtml')); // We must use 'nohtml' and not 'alphanohtml' because we must accept "
1881 $dataposted = str_replace('<?=', '<?php', $dataposted);
1882
1883 // README.md file
1884 $phpfullcodestringold = '';
1885 $phpfullcodestring = dolKeepOnlyPhpCode($dataposted);
1886
1887 // Security analysis
1888 $errorphpcheck = checkPHPCode($phpfullcodestringold, $phpfullcodestring); // Contains the setEventMessages
1889
1890 if (!$errorphpcheck) {
1891 $readmecontent = '';
1892
1893 /*$readmecontent.= "<?php // BEGIN PHP\n";
1894 $readmecontent.= '$websitekey=basename(__DIR__);'."\n";
1895 $readmecontent.= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded"."\n"; // For the css, we need to set path of master using the dirname of css file.
1896 $readmecontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
1897 $readmecontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
1898 $readmecontent.= "ob_start();\n";
1899 $readmecontent.= "header('Cache-Control: max-age=3600, public, must-revalidate');\n";
1900 $readmecontent.= "header('Content-type: application/manifest+json');\n";
1901 $readmecontent.= "// END PHP ?>\n";*/
1902
1903 $readmecontent .= $dataposted."\n";
1904
1905 /*$readmecontent.= '<?php // BEGIN PHP'."\n";
1906 $readmecontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "manifest");'."\n";
1907 $readmecontent.= "// END PHP ?>"."\n";*/
1908
1909 $result = dolSaveReadme($filereadme, $readmecontent);
1910 if (!$result) {
1911 $error++;
1912 setEventMessages('Failed to write file '.$filereadme, null, 'errors');
1913 }
1914 } else {
1915 $error++;
1916 }
1917
1918
1919 $dataposted = trim(GETPOST('WEBSITE_LICENSE', 'nohtml')); // We must use 'nohtml' and not 'alphanohtml' because we must accept "
1920 $dataposted = str_replace('<?=', '<?php', $dataposted);
1921
1922 // LICENSE file
1923 $phpfullcodestringold = '';
1924 $phpfullcodestring = dolKeepOnlyPhpCode($dataposted);
1925
1926 // Security analysis
1927 $errorphpcheck = checkPHPCode($phpfullcodestringold, $phpfullcodestring); // Contains the setEventMessages
1928
1929 if (!$errorphpcheck) {
1930 $licensecontent = '';
1931
1932 /*$readmecontent.= "<?php // BEGIN PHP\n";
1933 $readmecontent.= '$websitekey=basename(__DIR__);'."\n";
1934 $readmecontent.= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded"."\n"; // For the css, we need to set path of master using the dirname of css file.
1935 $readmecontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
1936 $readmecontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
1937 $readmecontent.= "ob_start();\n";
1938 $readmecontent.= "header('Cache-Control: max-age=3600, public, must-revalidate');\n";
1939 $readmecontent.= "header('Content-type: application/manifest+json');\n";
1940 $readmecontent.= "// END PHP ?>\n";*/
1941
1942 $licensecontent .= $dataposted."\n";
1943
1944 /*$readmecontent.= '<?php // BEGIN PHP'."\n";
1945 $readmecontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "manifest");'."\n";
1946 $readmecontent.= "// END PHP ?>"."\n";*/
1947
1948 $result = dolSaveLicense($filelicense, $licensecontent);
1949 if (!$result) {
1950 $error++;
1951 setEventMessages('Failed to write file '.$filelicense, null, 'errors');
1952 }
1953 } else {
1954 $error++;
1955 }
1956
1957 // Save wrapper.php
1958 $result = dolSaveIndexPage($pathofwebsite, '', '', $filewrapper, $object);
1959
1960
1961 // Message if no error
1962 if (!$error) {
1963 setEventMessages($langs->trans("Saved"), null, 'mesgs');
1964 }
1965
1966 if (!GETPOSTISSET('updateandstay')) { // If we click on "Save And Stay", we don not make the redirect
1967 $action = 'preview';
1968 if ($backtopage) {
1969 $backtopage = preg_replace('/searchstring=[^&]*/', '', $backtopage); // Clean backtopage url
1970 header("Location: ".$backtopage);
1971 exit;
1972 }
1973 } else {
1974 $action = 'editcss';
1975 }
1976 }
1977 }
1978}
1979
1980$sourcetype = '';
1981if ($action == "updatesecurity" && $usercanedit && GETPOST("btn_WEBSITE_SECURITY_FORCECSP")) {
1982 $directivecsp = GETPOST("select_identifier_WEBSITE_SECURITY_FORCECSP");
1983 $sourcecsp = GETPOST("select_source_WEBSITE_SECURITY_FORCECSP");
1984 $sourcedatacsp = GETPOST("input_data_WEBSITE_SECURITY_FORCECSP");
1985
1986 $forceCSPArr = websiteGetContentPolicyToArray($forceCSP);
1987 $directivesarray = websiteGetContentPolicyDirectives();
1988 $sourcesarray = websiteGetContentPolicySources();
1989 if (empty($directivecsp)) {
1990 $error++;
1991 }
1992 if ($error || (!isset($sourcecsp) && $directivesarray[$directivecsp]["data-directivetype"] != "none")) {
1993 $error++;
1994 }
1995 if (!$error) {
1996 $directivetype = $directivesarray[$directivecsp]["data-directivetype"];
1997 if (isset($sourcecsp)) {
1998 $sourcetype = $sourcesarray[$directivetype][$sourcecsp]["data-sourcetype"];
1999 }
2000 $securityspstring = "";
2001 if (isset($sourcetype) && $sourcetype == "data") {
2002 $forceCSPArr[$directivecsp][] = "data:".$sourcedatacsp;
2003 } elseif (isset($sourcetype) && $sourcetype == "input") {
2004 if (empty($forceCSPArr[$directivecsp])) {
2005 $forceCSPArr[$directivecsp] = array();
2006 }
2007 $forceCSPArr[$directivecsp] = array_merge(explode(" ", $sourcedatacsp), $forceCSPArr[$directivecsp]);
2008 } else {
2009 if (empty($forceCSPArr[$directivecsp])) {
2010 $forceCSPArr[$directivecsp] = array();
2011 }
2012 if (!isset($sourcecsp)) {
2013 $sourcecsp = "";
2014 }
2015 array_unshift($forceCSPArr[$directivecsp], $sourcecsp);
2016 }
2017 foreach ($forceCSPArr as $directive => $sourcekeys) {
2018 if ($securityspstring != "") {
2019 $securityspstring .= "; ";
2020 }
2021 $sourcestring = "";
2022 foreach ($sourcekeys as $key => $source) {
2023 $directivetype = $directivesarray[$directive]["data-directivetype"];
2024 $sourcetype = $sourcesarray[$directivetype][$source]["data-sourcetype"];
2025 if (isset($sourcetype) && $sourcetype == "quoted") {
2026 $sourcestring .= " '".$source."'";
2027 } elseif ($directivetype != "none") {
2028 $sourcestring .= " ".$source;
2029 }
2030 }
2031 $securityspstring .= $directive . $sourcestring;
2032 }
2033 $res = dolibarr_set_const($db, 'WEBSITE_'.$object->id.'_SECURITY_FORCECSP', $securityspstring, 'chaine', 0, '', $conf->entity);
2034 if ($res <= 0) {
2035 $error++;
2036 }
2037 }
2038
2039 if (!$error) {
2040 $db->commit();
2041 setEventMessages($langs->trans("SecurityPolicySucesfullyAdded"), null, 'mesgs');
2042 } else {
2043 $db->rollback();
2044 setEventMessages($langs->trans("ErrorAddingSecurityPolicy"), null, 'errors');
2045 }
2046 header("Location: ".$_SERVER["PHP_SELF"].'?websiteid='.$websiteid."&action=editsecurity");
2047 exit();
2048}
2049
2050if ($action == "updatesecurity" && $usercanedit) {
2051 $db->begin();
2052 $res1 = $res2 = $res3 = $res4 = 0;
2053 $securityrp = GETPOST('WEBSITE_'.$object->id.'_SECURITY_FORCERP', 'alpha');
2054 $securitysts = GETPOST('WEBSITE_'.$object->id.'_SECURITY_FORCESTS', 'alpha');
2055 $securitypp = GETPOST('WEBSITE_'.$object->id.'_SECURITY_FORCEPP', 'alpha');
2056 $securitysp = GETPOST('WEBSITE_'.$object->id.'_SECURITY_FORCECSP', 'alpha');
2057 $securitycspro = GETPOST('WEBSITE_'.$object->id.'_SECURITY_FORCECSPRO', 'alpha');
2058
2059 $res1 = dolibarr_set_const($db, 'WEBSITE_'.$object->id.'_SECURITY_FORCERP', $securityrp, 'chaine', 0, '', $conf->entity);
2060 $res2 = dolibarr_set_const($db, 'WEBSITE_'.$object->id.'_SECURITY_FORCESTS', $securitysts, 'chaine', 0, '', $conf->entity);
2061 $res3 = dolibarr_set_const($db, 'WEBSITE_'.$object->id.'_SECURITY_FORCEPP', $securitypp, 'chaine', 0, '', $conf->entity);
2062 $res4 = dolibarr_set_const($db, 'WEBSITE_'.$object->id.'_SECURITY_FORCECSP', $securitysp, 'chaine', 0, '', $conf->entity);
2063 $res5 = dolibarr_set_const($db, 'WEBSITE_'.$object->id.'_SECURITY_FORCECSPRO', $securitycspro, 'chaine', 0, '', $conf->entity);
2064
2065 if ($res1 >= 0 && $res2 >= 0 && $res3 >= 0 && $res4 >= 0 && $res5 >= 0) {
2066 $db->commit();
2067 setEventMessages($langs->trans("Saved"), null, 'mesgs');
2068 } else {
2069 $db->rollback();
2070 setEventMessages($langs->trans("ErrorSavingChanges"), null, 'errors');
2071 }
2072
2073 if (!GETPOSTISSET('updateandstay')) { // If we click on "Save And Stay", we don not make the redirect
2074 $action = 'preview';
2075 if ($backtopage) {
2076 $backtopage = preg_replace('/searchstring=[^&]*/', '', $backtopage); // Clean backtopage url
2077 header("Location: ".$backtopage);
2078 exit;
2079 }
2080 } else {
2081 $action = 'editsecurity';
2082 $forceCSP = getDolGlobalString("WEBSITE_".$object->id."_SECURITY_FORCECSP");
2083 }
2084}
2085
2086// Update page
2087if ($action == 'setashome' && $confirm == 'yes' && $usercanedit) {
2088 $db->begin();
2089 $object->fetch(0, $websitekey);
2090 $website = $object;
2091
2092 $object->fk_default_home = $pageid;
2093 $res = $object->update($user);
2094 if (! ($res > 0)) {
2095 $error++;
2096 setEventMessages($object->error, $object->errors, 'errors');
2097 }
2098
2099 if (!$error) {
2100 $db->commit();
2101
2102 $filetpl = $pathofwebsite.'/page'.$pageid.'.tpl.php';
2103
2104 // Generate the index.php page to be the home page
2105 $result = dolSaveIndexPage($pathofwebsite, $fileindex, $filetpl, $filewrapper, $object);
2106
2107 if ($result) {
2108 setEventMessages($langs->trans("Saved"), null, 'mesgs');
2109 } else {
2110 setEventMessages('Failed to write file '.$fileindex, null, 'errors');
2111 }
2112
2113 $action = 'preview';
2114 } else {
2115 $db->rollback();
2116 }
2117}
2118
2119// Update page properties (meta)
2120if ($action == 'updatemeta' && $usercanedit) {
2121 $db->begin();
2122
2123 $result = $object->fetch(0, $websitekey);
2124 $website = $object;
2125
2126 $objectpage->fk_website = $object->id;
2127
2128 // Check parameters
2129 if (!preg_match('/^[a-z0-9\-\_]+$/i', GETPOST('WEBSITE_PAGENAME', 'alpha'))) {
2130 $error++;
2131 $langs->load("errors");
2132 setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities('WEBSITE_PAGENAME')), null, 'errors');
2133 $action = 'editmeta';
2134 }
2135
2136 $res = $objectpage->fetch($pageid, (string) $object->id);
2137 if ($res <= 0) {
2138 $error++;
2139 setEventMessages('Page not found '.$objectpage->error, $objectpage->errors, 'errors');
2140 }
2141
2142 // Check alias not exists
2143 if (!$error && GETPOST('WEBSITE_PAGENAME', 'alpha')) {
2144 $websitepagetemp = new WebsitePage($db);
2145 $result = $websitepagetemp->fetch(-1 * $objectpage->id, (string) $object->id, GETPOST('WEBSITE_PAGENAME', 'alpha'));
2146 if ($result < 0) {
2147 $error++;
2148 $langs->load("errors");
2149 setEventMessages($websitepagetemp->error, $websitepagetemp->errors, 'errors');
2150 $action = 'editmeta';
2151 }
2152 if ($result > 0) {
2153 $error++;
2154 $langs->load("errors");
2155 setEventMessages($langs->trans("ErrorAPageWithThisNameOrAliasAlreadyExists", $websitepagetemp->pageurl), null, 'errors');
2156 $action = 'editmeta';
2157 }
2158 }
2159
2160 $newaliasnames = '';
2161 if (!$error && GETPOST('WEBSITE_ALIASALT', 'alpha')) {
2162 $arrayofaliastotest = explode(',', str_replace(array('<', '>'), '', GETPOST('WEBSITE_ALIASALT', 'alpha')));
2163
2164 $websitepagetemp = new WebsitePage($db);
2165 foreach ($arrayofaliastotest as $aliastotest) {
2166 $aliastotest = trim(preg_replace('/\.php$/i', '', $aliastotest));
2167
2168 // Disallow alias name pageX (already used to save the page with id)
2169 if (preg_match('/^page\d+/i', $aliastotest)) {
2170 $error++;
2171 $langs->load("errors");
2172 setEventMessages("Alias name 'pageX' is not allowed", null, 'errors');
2173 $action = 'editmeta';
2174 break;
2175 } else {
2176 $result = $websitepagetemp->fetch(-1 * $objectpage->id, (string) $object->id, $aliastotest);
2177 if ($result < 0) {
2178 $error++;
2179 $langs->load("errors");
2180 setEventMessages($websitepagetemp->error, $websitepagetemp->errors, 'errors');
2181 $action = 'editmeta';
2182 break;
2183 }
2184 if ($result > 0) {
2185 $error++;
2186 $langs->load("errors");
2187 setEventMessages($langs->trans("ErrorAPageWithThisNameOrAliasAlreadyExists", $websitepagetemp->pageurl), null, 'errors');
2188 $action = 'editmeta';
2189 break;
2190 }
2191 $newaliasnames .= ($newaliasnames ? ', ' : '').$aliastotest;
2192 }
2193 }
2194 }
2195
2196 if (!$error) {
2197 $objectpage->old_object = clone $objectpage;
2198
2199 $objectpage->title = str_replace(array('<', '>'), '', GETPOST('WEBSITE_TITLE', 'alphanohtml'));
2200 $objectpage->type_container = GETPOST('WEBSITE_TYPE_CONTAINER', 'aZ09');
2201 $objectpage->pageurl = dol_sanitizeUrl(GETPOST('WEBSITE_PAGENAME', 'alpha'));
2202 $objectpage->aliasalt = $newaliasnames;
2203 $objectpage->lang = GETPOST('WEBSITE_LANG', 'aZ09');
2204 $objectpage->otherlang = GETPOST('WEBSITE_OTHERLANG', 'aZ09comma');
2205 $objectpage->description = str_replace(array('<', '>'), '', GETPOST('WEBSITE_DESCRIPTION', 'alphanohtml'));
2206 $objectpage->image = GETPOST('WEBSITE_IMAGE', 'alpha');
2207 $objectpage->keywords = str_replace(array('<', '>'), '', GETPOST('WEBSITE_KEYWORDS', 'alphanohtml'));
2208 $objectpage->allowed_in_frames = GETPOST('WEBSITE_ALLOWED_IN_FRAMES', 'aZ09') ? 1 : 0;
2209 $objectpage->keep_history = GETPOSTINT('WEBSITE_KEEP_HISTORY');
2210 $objectpage->htmlheader = trim(GETPOST('htmlheader', 'restricthtmlallowlinkscript')); // Must accept tags like '<script>' and '<link>'
2211 $objectpage->fk_page = (GETPOSTINT('pageidfortranslation') > 0 ? GETPOSTINT('pageidfortranslation') : 0);
2212 $objectpage->author_alias = trim(GETPOST('WEBSITE_AUTHORALIAS', 'alphanohtml'));
2213 $objectpage->object_type = GETPOST('WEBSITE_OBJECTCLASS', 'alpha');
2214 $objectpage->fk_object = GETPOST('WEBSITE_OBJECTID', 'aZ09');
2215
2216 $newdatecreation = dol_mktime(GETPOSTINT('datecreationhour'), GETPOSTINT('datecreationmin'), GETPOSTINT('datecreationsec'), GETPOSTINT('datecreationmonth'), GETPOSTINT('datecreationday'), GETPOSTINT('datecreationyear'));
2217 if ($newdatecreation) {
2218 $objectpage->date_creation = $newdatecreation;
2219 }
2220
2221 $res = $objectpage->update($user);
2222 if (!($res > 0)) {
2223 $langs->load("errors");
2224 if ($db->lasterrno == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2225 $error++;
2226 setEventMessages($langs->trans("ErrorAPageWithThisNameOrAliasAlreadyExists"), null, 'errors');
2227 $action = 'editmeta';
2228 } else {
2229 $error++;
2230 setEventMessages($objectpage->error, $objectpage->errors, 'errors');
2231 $action = 'editmeta';
2232 }
2233 }
2234 }
2235
2236 if (!$error) {
2237 // Website categories association
2238 $categoriesarray = GETPOST('categories', 'array:int');
2239 $result = $objectpage->setCategories($categoriesarray);
2240 if ($result < 0) {
2241 $error++;
2242 setEventMessages($object->error, $object->errors, 'errors');
2243 }
2244 }
2245
2246 if (!$error) {
2247 $db->commit();
2248 } else {
2249 $db->rollback();
2250 }
2251
2252 if (!$error) {
2253 $filemaster = $pathofwebsite.'/master.inc.php';
2254 $fileoldalias = $pathofwebsite.'/'.$objectpage->old_object->pageurl.'.php';
2255 $filealias = $pathofwebsite.'/'.$objectpage->pageurl.'.php';
2256
2257 dol_mkdir($pathofwebsite);
2258
2259 // Now generate the master.inc.php page
2260 $result = dolSaveMasterFile($filemaster);
2261 if (!$result) {
2262 setEventMessages('Failed to write file '.$filemaster, null, 'errors');
2263 }
2264
2265 // Now delete the alias.php page
2266 if (!empty($fileoldalias)) {
2267 dol_syslog("We delete old alias page name=".$fileoldalias." to build a new alias page=".$filealias);
2268 dol_delete_file($fileoldalias);
2269
2270 // Delete also pages into language subdirectories
2271 if (empty($objectpage->lang) || !in_array($objectpage->lang, explode(',', $object->otherlang))) {
2272 $dirname = dirname($fileoldalias);
2273 $filename = basename($fileoldalias);
2274 $sublangs = explode(',', $object->otherlang);
2275 foreach ($sublangs as $sublang) {
2276 // Under certain conditions $sublang can be an empty string
2277 // ($object->otherlang with empty string or with string like this 'en,,sv')
2278 // if is the case we try to re-delete the main alias file. Avoid it.
2279 if (empty(trim($sublang))) {
2280 continue;
2281 }
2282 $fileoldaliassub = $dirname.'/'.$sublang.'/'.$filename;
2283 dol_delete_file($fileoldaliassub);
2284 }
2285 }
2286 }
2287 // Now delete the alternative alias.php pages
2288 if (!empty($objectpage->old_object->aliasalt)) {
2289 $tmpaltaliases = explode(',', $objectpage->old_object->aliasalt);
2290 if (is_array($tmpaltaliases)) {
2291 foreach ($tmpaltaliases as $tmpaliasalt) {
2292 dol_syslog("We delete old alt alias pages name=".trim($tmpaliasalt));
2293 dol_delete_file($pathofwebsite.'/'.trim($tmpaliasalt).'.php');
2294
2295 // Delete also pages into language subdirectories
2296 if (empty($objectpage->lang) || !in_array($objectpage->lang, explode(',', $object->otherlang))) {
2297 $dirname = dirname($pathofwebsite.'/'.trim($tmpaliasalt).'.php');
2298 $filename = basename($pathofwebsite.'/'.trim($tmpaliasalt).'.php');
2299 $sublangs = explode(',', $object->otherlang);
2300 foreach ($sublangs as $sublang) {
2301 // Under certain conditions $ sublang can be an empty string
2302 // ($object->otherlang with empty string or with string like this 'en,,sv')
2303 // if is the case we try to re-delete the main alias file. Avoid it.
2304 if (empty(trim($sublang))) {
2305 continue;
2306 }
2307 $fileoldaliassub = $dirname.'/'.$sublang.'/'.$filename;
2308 dol_delete_file($fileoldaliassub);
2309 }
2310 }
2311 }
2312 }
2313 }
2314
2315 // Save page main alias
2316 $result = dolSavePageAlias($filealias, $object, $objectpage);
2317 if (!$result) {
2318 setEventMessages('Failed to write file '.$filealias, null, 'errors');
2319 }
2320 // Save alt aliases
2321 if (!empty($objectpage->aliasalt)) {
2322 $tmpaltaliases = explode(',', $objectpage->aliasalt);
2323 if (is_array($tmpaltaliases)) {
2324 foreach ($tmpaltaliases as $tmpaliasalt) {
2325 if (trim($tmpaliasalt)) {
2326 $filealias = $pathofwebsite.'/'.trim($tmpaliasalt).'.php';
2327 $result = dolSavePageAlias($filealias, $object, $objectpage);
2328 if (!$result) {
2329 setEventMessages('Failed to write file '.basename($filealias), null, 'errors');
2330 }
2331 }
2332 }
2333 }
2334 }
2335
2336
2337 // Save page of content
2338 $result = dolSavePageContent($filetpl, $object, $objectpage, 1);
2339 if ($result) {
2340 setEventMessages($langs->trans("Saved"), null, 'mesgs');
2341
2342 if (!GETPOSTISSET('updateandstay')) { // If we click on "Save And Stay", we do not make the redirect
2343 //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$websitekey.'&pageid='.$pageid);
2344 //exit;
2345 $action = 'preview';
2346 } else {
2347 $action = 'editmeta';
2348 }
2349 } else {
2350 setEventMessages('Failed to write file '.$filetpl, null, 'errors');
2351 //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$websitekey.'&pageid='.$pageid);
2352 //exit;
2353 $action = 'preview';
2354 }
2355 }
2356}
2357
2358// Update page
2359if ((($action == 'updatesource' || $action == 'updatecontent' || $action == 'confirm_createfromclone' || $action == 'confirm_createpagefromclone') || ($action == 'preview' && (GETPOST('refreshsite') || GETPOST('refreshpage') || GETPOST('preview')))) && $usercanedit) {
2360 $object->fetch(0, $websitekey);
2361 $website = $object;
2362
2363 if ($action == 'confirm_createfromclone') { // Test on permissions already done
2364 $db->begin();
2365
2366 $objectnew = new Website($db);
2367 $result = $objectnew->createFromClone($user, GETPOSTINT('id'), GETPOST('siteref'), (GETPOSTINT('newlang') ? GETPOSTINT('newlang') : ''));
2368
2369 if ($result < 0) {
2370 $error++;
2371 setEventMessages($objectnew->error, $objectnew->errors, 'errors');
2372 $action = 'preview';
2373
2374 $db->rollback();
2375 } else {
2376 setEventMessages("ObjectClonedSuccessfuly", null, 'mesgs');
2377 $object = $objectnew;
2378 $id = $object->id;
2379 $pageid = $object->fk_default_home;
2380 $websitekey = GETPOST('siteref', 'aZ09');
2381
2382 $db->commit();
2383 }
2384 }
2385
2386 if ($action == 'confirm_createpagefromclone') { // Test on permissions already done
2387 $istranslation = (GETPOST('is_a_translation', 'aZ09') == 'on' ? 1 : 0);
2388 // Protection if it is a translation page
2389 if ($istranslation) {
2390 if (GETPOST('newlang', 'aZ09') == $objectpage->lang || !GETPOST('newlang', 'aZ09')) {
2391 $error++;
2392 setEventMessages($langs->trans("LanguageMustNotBeSameThanClonedPage"), null, 'errors');
2393 $action = 'preview';
2394 }
2395 if (GETPOSTINT('newwebsite') != $object->id) {
2396 $error++;
2397 setEventMessages($langs->trans("WebsiteMustBeSameThanClonedPageIfTranslation"), null, 'errors');
2398 $action = 'preview';
2399 }
2400 }
2401
2402 if (!$error) {
2403 $db->begin();
2404
2405 $newwebsiteid = GETPOSTINT('newwebsite');
2406 $pathofwebsitenew = $pathofwebsite;
2407
2408 $tmpwebsite = new Website($db);
2409 if ($newwebsiteid > 0 && $newwebsiteid != $object->id) {
2410 $tmpwebsite->fetch($newwebsiteid);
2411 $pathofwebsitenew = $dolibarr_main_data_root.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.$tmpwebsite->ref;
2412 } else {
2413 $tmpwebsite = $object;
2414 }
2415
2416 $objectpage = new WebsitePage($db);
2417 $resultpage = $objectpage->createFromClone($user, $pageid, GETPOST('newpageurl', 'aZ09'), (GETPOST('newlang', 'aZ09') ? GETPOST('newlang', 'aZ09') : ''), $istranslation, $newwebsiteid, GETPOST('newtitle', 'alphanohtml'), $tmpwebsite);
2418 if ($resultpage < 0) {
2419 $error++;
2420 setEventMessages($objectpage->error, $objectpage->errors, 'errors');
2421 $action = 'createpagefromclone';
2422
2423 $db->rollback();
2424 } else {
2425 $filetpl = $pathofwebsitenew.'/page'.$resultpage->id.'.tpl.php';
2426 $fileindex = $pathofwebsitenew.'/index.php';
2427 $filewrapper = $pathofwebsitenew.'/wrapper.php';
2428
2429 //var_dump($pathofwebsitenew);
2430 //var_dump($filetpl);
2431 //exit;
2432
2433 dolSavePageContent($filetpl, $tmpwebsite, $resultpage, 1);
2434
2435 // Switch on the new page if web site of new page/container is same
2436 if (empty($newwebsiteid) || $newwebsiteid == $object->id) {
2437 $pageid = $resultpage->id;
2438 }
2439
2440 $db->commit();
2441 }
2442 }
2443 }
2444
2445 $res = 0;
2446
2447 if (!$error) {
2448 // Check symlink documents/website/mywebsite/medias to point to documents/medias and restore it if ko.
2449 // Recreate also dir of website if not found.
2450 $pathtomedias = DOL_DATA_ROOT.'/medias';
2451 $pathtomediasinwebsite = $pathofwebsite.'/medias';
2452 if (!is_link(dol_osencode($pathtomediasinwebsite))) {
2453 dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite);
2454 dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure that the directory for website exists
2455 $result = symlink($pathtomedias, $pathtomediasinwebsite);
2456 if (!$result) {
2457 $langs->load("errors");
2458 setEventMessages($langs->trans("ErrorFailedToCreateSymLinkToMedias", $pathtomediasinwebsite, $pathtomedias), null, 'errors');
2459 }
2460 }
2461
2462 /*if (GETPOST('savevirtualhost') && $object->virtualhost != GETPOST('previewsite'))
2463 {
2464 $object->virtualhost = GETPOST('previewsite', 'alpha');
2465 $object->update($user);
2466 }*/
2467
2468 $objectpage->fk_website = $object->id;
2469
2470 if ($pageid > 0) {
2471 $res = $objectpage->fetch($pageid);
2472 } else {
2473 $res = 0;
2474 if ($object->fk_default_home > 0) {
2475 $res = $objectpage->fetch($object->fk_default_home);
2476 }
2477 if (!($res > 0)) {
2478 $res = $objectpage->fetch(0, (string) $object->id);
2479 }
2480 }
2481 }
2482
2483 if (!$error && $res > 0) {
2484 if ($action == 'updatesource' || $action == 'updatecontent') { // Test on permissions already done
2485 $db->begin();
2486
2487 $phpfullcodestringold = dolKeepOnlyPhpCode($objectpage->content);
2488
2489 $objectpage->content = GETPOST('PAGE_CONTENT', 'none'); // any HTML content allowed
2490
2491 $phpfullcodestring = dolKeepOnlyPhpCode($objectpage->content);
2492
2493 // Security analysis (check PHP content and check permission website->writephp if php content is modified)
2494 $error = checkPHPCode($phpfullcodestringold, $phpfullcodestring);
2495
2496 if ($error) {
2497 if ($action == 'updatesource') { // Test on permissions already done
2498 $action = 'editsource';
2499 }
2500 if ($action == 'updatecontent') { // Test on permissions already done
2501 $action = 'editcontent';
2502 }
2503 }
2504
2505 // Clean data. We remove all the head section.
2506 $objectpage->content = preg_replace('/<head>.*<\/head>/ims', '', $objectpage->content);
2507 /* $objectpage->content = preg_replace('/<base\s+href=[\'"][^\'"]+[\'"]\s/?>/s', '', $objectpage->content); */
2508
2509
2510 $res = $objectpage->update($user);
2511 if ($res < 0) {
2512 $error++;
2513 setEventMessages($objectpage->error, $objectpage->errors, 'errors');
2514 if ($action == 'updatesource') { // Test on permissions already done
2515 $action = 'editsource';
2516 }
2517 if ($action == 'updatecontent') { // Test on permissions already done
2518 $action = 'editcontent';
2519 }
2520 }
2521
2522 if (!$error) {
2523 $db->commit();
2524
2525 $filemaster = $pathofwebsite.'/master.inc.php';
2526 //$fileoldalias=$pathofwebsite.'/'.$objectpage->old_object->pageurl.'.php';
2527 $filealias = $pathofwebsite.'/'.$objectpage->pageurl.'.php';
2528
2529 dol_mkdir($pathofwebsite);
2530
2531 // Now generate the master.inc.php page
2532 $result = dolSaveMasterFile($filemaster);
2533
2534 if (!$result) {
2535 setEventMessages('Failed to write the master file file '.$filemaster, null, 'errors');
2536 }
2537
2538 // Now delete the old alias.php page if we removed one
2539 /*if (!empty($fileoldalias))
2540 {
2541 dol_syslog("We regenerate alias page new name=".$filealias.", old name=".$fileoldalias);
2542 dol_delete_file($fileoldalias);
2543
2544 // Delete also pages into language subdirectories
2545 if (empty($objectpage->lang) || !in_array($objectpage->lang, explode(',', $object->otherlang))) {
2546 $dirname = dirname($fileoldalias);
2547 $filename = basename($fileoldalias);
2548 $sublangs = explode(',', $object->otherlang);
2549 foreach ($sublangs as $sublang) {
2550 $fileoldaliassub = $dirname.'/'.$sublang.'/'.$filename;
2551 dol_delete_file($fileoldaliassub);
2552 }
2553 }
2554 }*/
2555
2556 // Save page alias
2557 $result = dolSavePageAlias($filealias, $object, $objectpage);
2558 if (!$result) {
2559 setEventMessages('Failed to write the alias file '.basename($filealias), null, 'errors');
2560 }
2561
2562 // Save page content
2563 $result = dolSavePageContent($filetpl, $object, $objectpage, 1);
2564 if ($result) {
2565 setEventMessages($langs->trans("Saved"), null, 'mesgs');
2566
2567 if (!GETPOSTISSET('updateandstay')) { // If we click on "Save And Stay", we do not make the redirect
2568 if ($backtopage) {
2569 header("Location: ".$backtopage);
2570 exit;
2571 } else {
2572 header("Location: ".$_SERVER["PHP_SELF"].'?website='.$websitekey.'&pageid='.$pageid);
2573 exit;
2574 }
2575 } else {
2576 if ($action == 'updatesource') { // Test on permissions already done
2577 $action = 'editsource';
2578 }
2579 if ($action == 'updatecontent') { // Test on permissions already done
2580 $action = 'editcontent';
2581 }
2582 }
2583 } else {
2584 setEventMessages('Failed to write file '.$filetpl, null, 'errors');
2585 header("Location: ".$_SERVER["PHP_SELF"].'?website='.$websitekey.'&pageid='.$pageid);
2586 exit;
2587 }
2588 } else {
2589 $db->rollback();
2590 }
2591 } else {
2592 header("Location: ".$_SERVER["PHP_SELF"].'?website='.$websitekey.'&pageid='.$pageid);
2593 exit;
2594 }
2595 } else {
2596 if (!$error) {
2597 if (empty($websitekey) || $websitekey == '-1') {
2598 setEventMessages($langs->trans("NoWebSiteCreateOneFirst"), null, 'warnings');
2599 } else {
2600 setEventMessages($langs->trans("NoPageYet"), null, 'warnings');
2601 setEventMessages($langs->trans("YouCanCreatePageOrImportTemplate"), null, 'warnings');
2602 }
2603 }
2604 }
2605}
2606
2607if ($action == 'deletelang' && $usercanedit) {
2608 $sql = "UPDATE ".MAIN_DB_PREFIX."website_page SET fk_page = NULL";
2609 $sql .= " WHERE rowid = ".GETPOSTINT('deletelangforid');
2610 //$sql .= " AND fk_page = ".((int) $objectpage->id);
2611
2612 $resql = $db->query($sql);
2613 if (!$resql) {
2614 setEventMessages($db->lasterror(), null, 'errors');
2615 } else {
2616 $objectpage->fk_page = null;
2617 }
2618
2619 $action = 'editmeta';
2620}
2621
2622
2623// Export site
2624if ($action == 'exportsite' && $user->hasRight('website', 'export')) {
2625 $fileofzip = $object->exportWebSite();
2626
2627 if ($fileofzip) {
2628 $file_name = basename($fileofzip);
2629 header("Content-Type: application/zip");
2630 header("Content-Disposition: attachment; filename=".$file_name);
2631 header("Content-Length: ".filesize($fileofzip));
2632
2633 readfile($fileofzip);
2634 exit;
2635 } else {
2636 setEventMessages($object->error, $object->errors, 'errors');
2637 $action = 'preview';
2638 }
2639}
2640
2641// Overwrite site
2642if ($action == 'overwritesite' && $user->hasRight('website', 'export')) {
2643 if (getDolGlobalString('WEBSITE_ALLOW_OVERWRITE_GIT_SOURCE')) {
2644 // Generate a zip of the website
2645 $fileofzip = $object->exportWebSite();
2646 $pathToExport = GETPOST('export_path');
2647 if ($fileofzip) {
2648 // Uncompress the exported web site into a destination directory
2649 $result = $object->overwriteTemplate($fileofzip, $pathToExport);
2650 if ($result < 0) {
2651 setEventMessages($object->error, $object->errors, 'errors');
2652 $action = 'preview';
2653 }
2654 } else {
2655 setEventMessages($object->error, $object->errors, 'errors');
2656 $action = 'preview';
2657 }
2658 }
2659}
2660// Regenerate site
2661if ($action == 'regeneratesite' && $usercanedit) {
2662 // Check symlink documents/website/mywebsite/medias to point to documents/medias and restore it if ko.
2663 // Recreate also dir of website if not found.
2664 $pathtomedias = DOL_DATA_ROOT.'/medias';
2665 $pathtomediasinwebsite = $pathofwebsite.'/medias';
2666 if (!is_link(dol_osencode($pathtomediasinwebsite))) {
2667 dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite);
2668 dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure that the directory for website exists
2669 $result = symlink($pathtomedias, $pathtomediasinwebsite);
2670 if (!$result) {
2671 $langs->load("errors");
2672 setEventMessages($langs->trans("ErrorFailedToCreateSymLinkToMedias", $pathtomediasinwebsite, $pathtomedias), null, 'errors');
2673 $action = 'preview';
2674 }
2675 }
2676
2677 $result = $object->rebuildWebSiteFiles();
2678 if ($result > 0) {
2679 setEventMessages($langs->trans("PagesRegenerated", $result), null, 'mesgs');
2680 $action = 'preview';
2681 } else {
2682 setEventMessages($object->error, $object->errors, 'errors');
2683 $action = 'preview';
2684 }
2685}
2686
2687// Import site
2688if ($action == 'importsiteconfirm' && $usercanedit) {
2689 $dolibarrdataroot = preg_replace('/([\\/]+)$/i', '', DOL_DATA_ROOT);
2690 $allowimportsite = true;
2691 if (dol_is_file($dolibarrdataroot.'/installmodules.lock')) {
2692 $allowimportsite = false;
2693 }
2694
2695 if ($allowimportsite) {
2696 if (empty($_FILES) && !GETPOSTISSET('templateuserfile')) {
2697 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("File")), null, 'errors');
2698 $action = 'importsite';
2699 } else {
2700 if (!empty($_FILES) || GETPOSTISSET('templateuserfile')) {
2701 // Check symlink documents/website/mywebsite/medias to point to documents/medias and restore it if ko.
2702 // Recreate also dir of website if not found.
2703 $pathtomedias = DOL_DATA_ROOT.'/medias';
2704 $pathtomediasinwebsite = $pathofwebsite.'/medias';
2705 if (!is_link(dol_osencode($pathtomediasinwebsite))) {
2706 dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite);
2707 dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists
2708 $result = symlink($pathtomedias, $pathtomediasinwebsite);
2709 if (!$result) {
2710 $langs->load("errors");
2711 setEventMessages($langs->trans("ErrorFailedToCreateSymLinkToMedias", $pathtomediasinwebsite, $pathtomedias), null, 'errors');
2712 $action = 'importsite';
2713 }
2714 }
2715
2716 $fileofzip = '';
2717 if (GETPOSTISSET('templateuserfile')) {
2718 // Case we selected one template
2719 $fileofzip = DOL_DATA_ROOT.'/doctemplates/websites/'.GETPOST('templateuserfile', 'alpha'); // $fileofzip will be sanitized later into the importWebSite()
2720 } elseif (!empty($_FILES) && is_array($_FILES['userfile'])) {
2721 // Case we upload a new template
2722 if (is_array($_FILES['userfile']['tmp_name'])) {
2723 $userfiles = $_FILES['userfile']['tmp_name'];
2724 } else {
2725 $userfiles = array($_FILES['userfile']['tmp_name']);
2726 }
2727
2728 // Check if $_FILES is ok
2729 foreach ($userfiles as $key => $userfile) {
2730 if (empty($_FILES['userfile']['tmp_name'][$key])) {
2731 $error++;
2732 if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2) {
2733 setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors');
2734 $action = 'importsite';
2735 } else {
2736 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("File")), null, 'errors');
2737 $action = 'importsite';
2738 }
2739 }
2740 }
2741
2742 if (!$error) {
2743 //$upload_dir = $conf->website->dir_temp;
2744 $upload_dir = DOL_DATA_ROOT.'/doctemplates/websites/';
2745 $result = dol_add_file_process($upload_dir, 1, -1, 'userfile', '');
2746 }
2747
2748 // Get name of file (take last one if several name provided)
2749 /*
2750 $fileofzip = $upload_dir.'/unknown';
2751 foreach ($_FILES as $key => $ifile) {
2752 foreach ($ifile['name'] as $key2 => $ifile2) {
2753 $fileofzip = $upload_dir.'/'.$ifile2;
2754 }
2755 }
2756 */
2757
2758 $action = 'importsite';
2759 }
2760
2761 if (!$error && GETPOSTISSET('templateuserfile')) {
2762 $templatewithoutzip = preg_replace('/\.zip$/i', '', GETPOST('templateuserfile'));
2763 $object->setTemplateName($templatewithoutzip);
2764
2765 $result = $object->importWebSite($fileofzip);
2766
2767 if ($result < 0) {
2768 setEventMessages($object->error, $object->errors, 'errors');
2769 $action = 'importsite';
2770 } else {
2771 // Force mode dynamic on
2772 dolibarr_set_const($db, 'WEBSITE_SUBCONTAINERSINLINE', 1, 'chaine', 0, '', $conf->entity);
2773
2774 header("Location: ".$_SERVER["PHP_SELF"].'?website='.$object->ref);
2775 exit();
2776 }
2777 }
2778 }
2779 }
2780 } else {
2781 if (getDolGlobalString('MAIN_MESSAGE_INSTALL_MODULES_DISABLED_CONTACT_US')) {
2782 // Show clean corporate message
2783 $message = $langs->trans('InstallModuleFromWebHasBeenDisabledContactUs');
2784 } else {
2785 // Show technical generic message
2786 $message = $langs->trans("InstallModuleFromWebHasBeenDisabledByFile", $dolibarrdataroot.'/installmodules.lock');
2787 }
2788 setEventMessages($message, null, 'errors');
2789 }
2790}
2791
2792$domainname = '0.0.0.0:8080';
2793$tempdir = $conf->website->dir_output.'/'.$websitekey.'/';
2794
2795// Generate web site sitemaps
2796if ($action == 'generatesitemaps' && $usercanedit) {
2797 // Define $domainname
2798 if ($website->virtualhost) {
2799 $domainname = $website->virtualhost;
2800 }
2801 if (! preg_match('/^http/i', $domainname)) {
2802 $domainname = 'https://'.$domainname;
2803 }
2804
2805 $domtree = new DOMDocument('1.0', 'UTF-8');
2806
2807 $root = $domtree->createElementNS('http://www.sitemaps.org/schemas/sitemap/0.9', 'urlset');
2808 $root->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:xhtml', 'http://www.w3.org/1999/xhtml');
2809
2810 $domtree->formatOutput = true;
2811
2812 $addrsswrapper = 0;
2813 $xmlname = 'sitemap.xml';
2814
2815 $sql = "SELECT wp.rowid, wp.type_container , wp.pageurl, wp.lang, wp.fk_page, wp.tms as tms,";
2816 $sql .= " w.virtualhost, w.fk_default_home";
2817 $sql .= " FROM ".MAIN_DB_PREFIX."website_page as wp, ".MAIN_DB_PREFIX."website as w";
2818 $sql .= " WHERE wp.type_container IN ('page', 'blogpost')";
2819 $sql .= " AND wp.fk_website = w.rowid";
2820 $sql .= " AND wp.status = ".WebsitePage::STATUS_VALIDATED;
2821 $sql .= " AND wp.pageurl NOT IN ('404', '500', '501', '503')";
2822 $sql .= " AND w.ref = '".dol_escape_json($websitekey)."'";
2823 $sql .= " ORDER BY wp.tms DESC, wp.rowid DESC";
2824 $resql = $db->query($sql);
2825 if ($resql) {
2826 $num_rows = $db->num_rows($resql);
2827 if ($num_rows > 0) {
2828 $i = 0;
2829 while ($i < $num_rows) {
2830 $objp = $db->fetch_object($resql);
2831 $url = $domtree->createElement('url');
2832
2833 $shortlangcode = '';
2834 if ($objp->lang) {
2835 $shortlangcode = substr($objp->lang, 0, 2); // en_US or en-US -> en
2836 }
2837 if (empty($shortlangcode)) {
2838 $shortlangcode = substr($object->lang, 0, 2); // Use short lang code of website
2839 }
2840
2841 // Is it a blog post for the RSS wrapper ?
2842 if ($objp->type_container == 'blogpost') {
2843 $addrsswrapper = 1;
2844 }
2845
2846 // Forge $pageurl, adding language prefix if it is an alternative language
2847 $pageurl = $objp->pageurl.'.php';
2848 if ($objp->fk_default_home == $objp->rowid) {
2849 $pageurl = '';
2850 } else {
2851 if ($shortlangcode != substr($object->lang, 0, 2)) {
2852 $pageurl = $shortlangcode.'/'.$pageurl;
2853 }
2854 }
2855
2856 //$pathofpage = $dolibarr_main_url_root.'/'.$pageurl.'.php';
2857
2858 // URL of sitemaps must end with trailing slash if page is ''
2859 $loc = $domtree->createElement('loc', $domainname.'/'.$pageurl);
2860 $lastmod = $domtree->createElement('lastmod', dol_print_date($db->jdate($objp->tms), 'dayrfc', 'gmt'));
2861 $priority = $domtree->createElement('priority', '1');
2862
2863 $url->appendChild($loc);
2864 $url->appendChild($lastmod);
2865 // Add suggested frequency for refresh
2866 if (getDolGlobalString('WEBSITE_SITEMAPS_ADD_WEEKLY_FREQ')) {
2867 $changefreq = $domtree->createElement('changefreq', 'weekly'); // TODO Manage other values
2868 $url->appendChild($changefreq);
2869 }
2870 // Add higher priority for home page
2871 if ($objp->fk_default_home == $objp->rowid) {
2872 $url->appendChild($priority);
2873 }
2874
2875 // Now add alternate language entries
2876 if ($object->isMultiLang()) {
2877 $alternatefound = 0;
2878
2879 // Add page "translation of"
2880 $translationof = $objp->fk_page;
2881 if ($translationof) {
2882 $tmppage = new WebsitePage($db);
2883 $tmppage->fetch($translationof);
2884 if ($tmppage->id > 0) {
2885 $tmpshortlangcode = '';
2886 if ($tmppage->lang) {
2887 $tmpshortlangcode = preg_replace('/[_-].*$/', '', $tmppage->lang); // en_US or en-US -> en
2888 }
2889 if (empty($tmpshortlangcode)) {
2890 $tmpshortlangcode = preg_replace('/[_-].*$/', '', $object->lang); // en_US or en-US -> en
2891 }
2892 if ($tmpshortlangcode != $shortlangcode) {
2893 $xhtmllink = $domtree->createElement('xhtml:link', '');
2894 $xhtmllink->setAttribute("rel", "alternate");
2895 $xhtmllink->setAttribute("hreflang", $tmpshortlangcode);
2896 $xhtmllink->setAttribute("href", $domainname.($objp->fk_default_home == $tmppage->id ? '/' : (($tmpshortlangcode != substr($object->lang, 0, 2)) ? '/'.$tmpshortlangcode : '').'/'.$tmppage->pageurl.'.php'));
2897 $url->appendChild($xhtmllink);
2898
2899 $alternatefound++;
2900 }
2901 }
2902 }
2903
2904 // Add "has translation pages"
2905 $sql = 'SELECT rowid as id, lang, pageurl from '.MAIN_DB_PREFIX.'website_page';
2906 $sql .= " WHERE status = ".((int) WebsitePage::STATUS_VALIDATED).' AND fk_page IN ('.$db->sanitize($objp->rowid.($translationof ? ", ".$translationof : "")).")";
2907 $resqlhastrans = $db->query($sql);
2908 if ($resqlhastrans) {
2909 $num_rows_hastrans = $db->num_rows($resqlhastrans);
2910 if ($num_rows_hastrans > 0) {
2911 while ($objhastrans = $db->fetch_object($resqlhastrans)) {
2912 $tmpshortlangcode = '';
2913 if ($objhastrans->lang) {
2914 $tmpshortlangcode = preg_replace('/[_-].*$/', '', $objhastrans->lang); // en_US or en-US -> en
2915 }
2916 if ($tmpshortlangcode != $shortlangcode) {
2917 $xhtmllink = $domtree->createElement('xhtml:link', '');
2918 $xhtmllink->setAttribute("rel", "alternate");
2919 $xhtmllink->setAttribute("hreflang", $tmpshortlangcode);
2920 $xhtmllink->setAttribute("href", $domainname.($objp->fk_default_home == $objhastrans->id ? '/' : (($tmpshortlangcode != substr($object->lang, 0, 2) ? '/'.$tmpshortlangcode : '')).'/'.$objhastrans->pageurl.'.php'));
2921 $url->appendChild($xhtmllink);
2922
2923 $alternatefound++;
2924 }
2925 }
2926 }
2927 } else {
2928 dol_print_error($db);
2929 }
2930
2931 if ($alternatefound) {
2932 // Add myself
2933 $xhtmllink = $domtree->createElement('xhtml:link', '');
2934 $xhtmllink->setAttribute("rel", "alternate");
2935 $xhtmllink->setAttribute("hreflang", $shortlangcode);
2936 $xhtmllink->setAttribute("href", $domainname.'/'.$pageurl);
2937 $url->appendChild($xhtmllink);
2938 }
2939 }
2940
2941 // Now add sitempas extension for news
2942 // TODO When adding and when not ?
2943 /*<news:news>
2944 <news:publication>
2945 <news:name>The Example Times</news:name>
2946 <news:language>en</news:language>
2947 </news:publication>
2948 <news:publication_date>2008-12-23</news:publication_date>
2949 <news:title>Companies A, B in Merger Talks</news:title>
2950 </news:news>
2951 */
2952
2953 $root->appendChild($url);
2954 $i++;
2955 }
2956
2957 // Adding a RSS feed into a sitemap should not be required. The RSS contains pages that are already included into
2958 // the sitemap and RSS feeds are not shown into index.
2959 if ($addrsswrapper && getDolGlobalInt('WEBSITE_ADD_RSS_FEED_INTO_SITEMAP')) {
2960 $url = $domtree->createElement('url');
2961
2962 $pageurl = 'wrapper.php?rss=1';
2963
2964 // URL of sitemaps must end with trailing slash if page is ''
2965 $loc = $domtree->createElement('loc', $domainname.'/'.$pageurl);
2966 $lastmod = $domtree->createElement('lastmod', dol_print_date(dol_now(), 'dayrfc', 'gmt'));
2967
2968 $url->appendChild($loc);
2969 $url->appendChild($lastmod);
2970 // Add suggested frequency for refresh
2971 if (getDolGlobalString('WEBSITE_SITEMAPS_ADD_WEEKLY_FREQ')) {
2972 $changefreq = $domtree->createElement('changefreq', 'weekly'); // TODO Manage other values
2973 $url->appendChild($changefreq);
2974 }
2975
2976 $root->appendChild($url);
2977 }
2978
2979 $domtree->appendChild($root);
2980
2981 if ($domtree->save($tempdir.$xmlname)) {
2982 dolChmod($tempdir.$xmlname);
2983 setEventMessages($langs->trans("SitemapGenerated", $xmlname), null, 'mesgs');
2984 } else {
2985 setEventMessages($object->error, $object->errors, 'errors');
2986 }
2987 }
2988 } else {
2989 dol_print_error($db);
2990 }
2991
2992 // Add the entry Sitemap: into the robot.txt file.
2993 $robotcontent = @file_get_contents($filerobot);
2994 $result = preg_replace('/<?php \/\/ BEGIN PHP[^?]END PHP ?>\n/ims', '', $robotcontent);
2995 if ($result) {
2996 $robotcontent = $result;
2997 }
2998 $robotsitemap = "Sitemap: ".$domainname."/".$xmlname;
2999 $result = strpos($robotcontent, 'Sitemap: ');
3000 if ($result) {
3001 $result = preg_replace('/Sitemap:.*/', $robotsitemap, $robotcontent);
3002 $robotcontent = $result ? $result : $robotcontent;
3003 } else {
3004 $robotcontent .= $robotsitemap."\n";
3005 }
3006 $result = dolSaveRobotFile($filerobot, $robotcontent);
3007 if (!$result) {
3008 $error++;
3009 setEventMessages('Failed to write file '.$filerobot, null, 'errors');
3010 }
3011 $action = 'preview';
3012}
3013
3014if ($action == 'removecspsource' && $usercanedit) {
3015 $db->begin();
3016 $sourcetype = "";
3017 $sourcecsp = explode("_", GETPOST("sourcecsp"));
3018 $directive = $sourcecsp[0];
3019 $sourcekey = isset($sourcecsp[1]) ? $sourcecsp[1] : null;
3020 $sourcedata = isset($sourcecsp[2]) ? $sourcecsp[2] : null;
3021 $forceCSPArr = websiteGetContentPolicyToArray($forceCSP);
3022 $directivesarray = websiteGetContentPolicyDirectives();
3023 $sourcesarray = websiteGetContentPolicySources();
3024 if (empty($directive)) {
3025 $error++;
3026 }
3027
3028 if (!empty($directivesarray[$directive])) {
3029 $directivetype = (string) $directivesarray[$directive]["data-directivetype"];
3030 if (isset($sourcekey)) {
3031 $sourcetype = $sourcesarray[$directivetype][$sourcekey]["data-sourcetype"];
3032 }
3033 }
3034
3035 $securityspstring = "";
3036 if (!$error && !empty($forceCSPArr)) {
3037 if (isset($sourcekey) && !empty($forceCSPArr[$directive][$sourcekey])) {
3038 unset($forceCSPArr[$directive][$sourcekey]);
3039 }
3040 if (count($forceCSPArr[$directive]) == 0) {
3041 unset($forceCSPArr[$directive]);
3042 }
3043 foreach ($forceCSPArr as $directive => $sourcekeys) {
3044 if ($securityspstring != "") {
3045 $securityspstring .= "; ";
3046 }
3047 $sourcestring = "";
3048 foreach ($sourcekeys as $key => $source) {
3049 $directivetype = $directivesarray[$directive]["data-directivetype"];
3050 $sourcetype = $sourcesarray[$directivetype][$source]["data-sourcetype"];
3051 if ($sourcetype == "quoted") {
3052 $sourcestring .= " '".$source."'";
3053 } else {
3054 $sourcestring .= " ".$source;
3055 }
3056 }
3057 $securityspstring .= $directive . $sourcestring;
3058 }
3059 $res = dolibarr_set_const($db, 'WEBSITE_'.$object->id.'_SECURITY_FORCECSP', $securityspstring, 'chaine', 0, '', $conf->entity);
3060 if ($res <= 0) {
3061 $error++;
3062 }
3063 }
3064
3065 if (!$error) {
3066 $db->commit();
3067 setEventMessages($langs->trans("SecurityPolicySucesfullyRemoved"), null, 'mesgs');
3068 } else {
3069 $db->rollback();
3070 setEventMessages($langs->trans("ErrorRemovingSecurityPolicy"), null, 'errors');
3071 }
3072
3073 header("Location: ".$_SERVER["PHP_SELF"].'?websiteid='.$websiteid."&action=editsecurity");
3074 exit();
3075}
3076
3077
3078/*
3079 * View
3080 */
3081
3082$form = new Form($db);
3083$formadmin = new FormAdmin($db);
3084$formwebsite = new FormWebsite($db);
3085$formother = new FormOther($db);
3086$formconfirm = "";
3087
3088// Confirm generation of website sitemaps
3089if ($action == 'confirmgeneratesitemaps') {
3090 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?website='.urlencode($website->ref), $langs->trans('ConfirmSitemapsCreation'), $langs->trans('ConfirmGenerateSitemaps', $object->ref), 'generatesitemaps', '', "yes", 1);
3091 $action = 'preview';
3092}
3093// Confirm to set page as home page
3094if ($action == 'confirmsetashome') {
3095 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?website='.urlencode($website->ref).'&pageid='.((int) $pageid), $langs->trans('SetAsHomePage'), $langs->trans('ConfirmSetAsHomePage', $objectpage->pageurl), 'setashome', '', "yes", 1);
3096 $action = 'preview';
3097}
3098$helpurl = 'EN:Module_Website|FR:Module_Website_FR|ES:M&oacute;dulo_Website';
3099
3100$arrayofjs = array(
3101 '/includes/ace/src/ace.js',
3102 '/includes/ace/src/ext-statusbar.js',
3103 '/includes/ace/src/ext-language_tools.js',
3104 //'/includes/ace/src/ext-chromevox.js'
3105);
3106$arrayofcss = array();
3107
3108if (!getDolGlobalString('MAIN_ECM_DISABLE_JS')) {
3109 $arrayofjs[] = "public/includes/jquery/plugins/jqueryFileTree/jqueryFileTree.js";
3110}
3111
3112llxHeader('', $langs->trans("Website").(empty($website->ref) ? '' : ' - '.$website->ref), $helpurl, '', 0, 0, $arrayofjs, $arrayofcss, '', 'mod-website page-index', '<!-- Begin div class="fiche" -->'."\n".'<div class="fichebutwithotherclass" spellcheck="false">');
3113
3114print "\n";
3115print '<!-- Open form common to all pages generated by website/index.php -->'."\n";
3116print '<form action="'.$_SERVER["PHP_SELF"].($action == 'file_manager' ? '?uploadform=1' : '').'" method="POST" enctype="multipart/form-data" class="websiteformtoolbar">'."\n";
3117print '<input type="hidden" name="token" value="'.newToken().'">';
3118print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
3119print '<input type="hidden" name="dol_openinpopup" value="'.$dol_openinpopup.'">';
3120
3121if ($action == 'createsite') {
3122 print '<input type="hidden" name="action" value="addsite">';
3123}
3124if ($action == 'createcontainer') {
3125 print '<input type="hidden" name="action" value="addcontainer">';
3126}
3127if ($action == 'editcss') {
3128 print '<input type="hidden" name="action" value="updatecss">';
3129}
3130if ($action == 'editmenu') {
3131 print '<input type="hidden" name="action" value="updatemenu">';
3132}
3133if ($action == 'setashome') {
3134 print '<input type="hidden" name="action" value="updateashome">';
3135}
3136if ($action == 'editmeta') {
3137 print '<input type="hidden" name="action" value="updatemeta">';
3138}
3139if ($action == 'editsource') {
3140 print '<input type="hidden" name="action" value="updatesource">';
3141}
3142if ($action == 'editcontent') {
3143 print '<input type="hidden" name="action" value="updatecontent">';
3144}
3145if ($action == 'edit') {
3146 print '<input type="hidden" name="action" value="update">';
3147}
3148if ($action == 'importsite') {
3149 print '<input type="hidden" name="action" value="importsiteconfirm">';
3150}
3151if ($action == 'file_manager') {
3152 print '<input type="hidden" name="action" value="file_manager">';
3153}
3154if ($mode) {
3155 print '<input type="hidden" name="mode" value="'.$mode.'">';
3156}
3157if ($action == 'editsecurity') {
3158 print '<input type="hidden" name="action" value="updatesecurity">';
3159}
3160
3161print '<div>'."\n";
3162
3163// Add a margin under toolbar ?
3164$style = '';
3165if ($action != 'preview' && $action != 'editcontent' && $action != 'editsource' && !GETPOST('createpagefromclone', 'alphanohtml')) {
3166 $style = ' margin-bottom: 5px;';
3167}
3168
3169
3170$websitepage = null;
3171$disabled = '';
3172if (!GETPOST('hide_websitemenu')) {
3173 if (!$user->hasRight('website', 'write')) {
3174 $disabled = ' disabled="disabled"';
3175 }
3176 $disabledexport = '';
3177 if (!$user->hasRight('website', 'export')) {
3178 $disabledexport = ' disabled="disabled"';
3179 }
3180
3181 if ($websitekey) {
3182 $virtualurl = '';
3183 $dataroot = DOL_DATA_ROOT.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.$websitekey;
3184 if (!empty($object->virtualhost)) {
3185 $virtualurl = $object->virtualhost;
3186 }
3187 }
3188
3189 $array = array();
3190 if ($object->id > 0) {
3191 $array = $objectpage->fetchAll($object->id, 'ASC,ASC', 'type_container,pageurl');
3192 $object->lines = $array;
3193 }
3194 if (!is_array($array) && $array < 0) {
3195 dol_print_error(null, $objectpage->error, $objectpage->errors);
3196 }
3197 $atleastonepage = (is_array($array) && count($array) > 0);
3198
3199 $websitepage = new WebsitePage($db);
3200 if ($pageid > 0) {
3201 $websitepage->fetch($pageid);
3202 }
3203
3204
3205 $disabled = '';
3206 $morecss = '';
3207 if (!$user->hasRight('website', 'write')) {
3208 $disabled = ' disabled="disabled"';
3209 $morecss = 'opacitymedium cursordefault';
3210 }
3211
3212 //var_dump($objectpage);exit;
3213 print '<div class="centpercent websitebar'.(GETPOST('dol_openinpopup', 'aZ09') ? ' hiddenforpopup' : '').'">'."\n";
3214
3215 //
3216 // Toolbar for websites
3217 //
3218
3219 print '<!-- Toolbar for website -->';
3220 if ($action != 'file_manager' && $action != 'editfile') {
3221 print '<div class="websiteselection hideonsmartphoneimp minwidth75 tdoverflowmax100 inline-block">';
3222 print $langs->trans("Website").': ';
3223 print '</div>';
3224
3225 // Button Add new website
3226 $urltocreatenewwebsite = $_SERVER["PHP_SELF"].'?action=createsite';
3227 if ($user->hasRight('website', 'write')) {
3228 print '<span class="websiteselection paddingrightonly">';
3229 print '<a href="'.$urltocreatenewwebsite.'" class=""'.$disabled.' title="'.dol_escape_htmltag($langs->trans("AddWebsite")).'"><span class="fa fa-plus-circle valignmiddle btnTitle-icon"><span></a>';
3230 print '</span>';
3231 }
3232
3233 // List of website
3234 print '<span class="websiteselection nopaddingrightimp">';
3235
3236 $out = '';
3237 $out .= '<select name="website" class="minwidth100 width200 maxwidth150onsmartphone" id="website">';
3238 if (empty($listofwebsites)) {
3239 $out .= '<option value="-1">&nbsp;</option>';
3240 }
3241
3242 // Loop on each sites
3243 $i = 0;
3244 foreach ($listofwebsites as $key => $valwebsite) {
3245 if (empty($websitekey)) {
3246 if ($action != 'createsite') {
3247 $websitekey = $valwebsite->ref;
3248 }
3249 }
3250
3251 $out .= '<option value="'.$valwebsite->ref.'"';
3252 if ($websitekey == $valwebsite->ref) {
3253 $out .= ' selected'; // To preselect a value
3254 }
3255 //$outoption = $valwebsite->getLibStatut(3).' '.$valwebsite->ref.' ';
3256 $outoption = (($valwebsite->status == $valwebsite::STATUS_DRAFT) ? '<span class="opacitymedium">' : '').$valwebsite->ref.(($valwebsite->status == $valwebsite::STATUS_DRAFT) ? '</span>' : '');
3257 $out .= ' data-html="'.dol_escape_htmltag($outoption).'"';
3258 $out .= '>';
3259 $out .= $valwebsite->ref;
3260 $out .= '</option>';
3261 $i++;
3262 }
3263 $out .= '</select>';
3264 $out .= ajax_combobox('website');
3265
3266 if (!empty($conf->use_javascript_ajax)) {
3267 $out .= '<script type="text/javascript">';
3268 $out .= 'jQuery(document).ready(function () {';
3269 $out .= ' jQuery("#website").change(function () {';
3270 $out .= ' console.log("We select "+jQuery("#website option:selected").val());';
3271 $out .= ' if (jQuery("#website option:selected").val() == \'-2\') {';
3272 $out .= ' window.location.href = \''.dol_escape_js($urltocreatenewwebsite).'\';';
3273 $out .= ' } else {';
3274 $out .= ' window.location.href = "'.$_SERVER["PHP_SELF"].'?website="+jQuery("#website option:selected").val();';
3275 $out .= ' }';
3276 $out .= ' });';
3277 $out .= '});';
3278 $out .= '</script>';
3279 }
3280 print $out;
3281
3282 print '</span>';
3283
3284 // Switch offline/onine
3285 if (!empty($conf->use_javascript_ajax)) {
3286 print '<span class="websiteselection">';
3287 // Do not use ajax, we need a refresh of full page when we change status of a website
3288 //print '<div class="inline-block marginrightonly">';
3289 //print ajax_object_onoff($object, 'status', 'status', 'Online', 'Offline', array(), 'valignmiddle inline-block', 'statuswebsite');
3290 //print '</div>';
3291 if ($website->status == $website::STATUS_DRAFT) {
3292 $text_off = 'Offline';
3293 print '<a href="'.$_SERVER["PHP_SELF"].'?action=setwebsiteonline&token='.newToken().'&website='.urlencode($website->ref).'&websitepage='.((int) $websitepage->id).'"'.$disabled.'>'.img_picto($langs->trans($text_off), 'switch_off', '', 0, 0, 0, '', $morecss).'</a>';
3294 } else {
3295 $text_off = 'Online';
3296 print '<a href="'.$_SERVER["PHP_SELF"].'?action=setwebsiteoffline&token='.newToken().'&website='.urlencode($website->ref).'&websitepage='.((int) $websitepage->id).'"'.$disabled.'>'.img_picto($langs->trans($text_off), 'switch_on', '', 0, 0, 0, '', $morecss).'</a>';
3297 }
3298 print '</span>';
3299 }
3300
3301 // Refresh / Reload web site (for non javascript browsers)
3302 if (empty($conf->use_javascript_ajax)) {
3303 print '<span class="websiteselection">';
3304 print '<input type="image" class="valignmiddle" src="'.img_picto('', 'refresh', '', 0, 1).'" name="refreshsite" value="'.$langs->trans("Load").'"'.$disabled.'>';
3305 print '</span>';
3306 }
3307
3308
3309 print '<span class="websiteselection">';
3310
3311 if ($websitekey && $websitekey != '-1' && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite')) {
3312 // Edit website properties
3313 print '<a href="'.$_SERVER["PHP_SELF"].'?website='.urlencode($object->ref).'&pageid='.((int) $pageid).'&action=editcss&token='.newToken().'" class="button bordertransp valignmiddle" title="'.dol_escape_htmltag($langs->trans("EditCss")).'"'.$disabled.'>';
3314 print img_picto('', 'setup');
3315 print '<span class="hideonsmartphone paddingleft">'.dol_escape_htmltag($langs->trans("EditCss")).'</span>';
3316 print '</a>';
3317
3318 // Import web site
3319 $importlabel = $langs->trans("ImportSite");
3320 $exportlabel = $langs->trans("ExportSite");
3321 if (!empty($conf->dol_optimize_smallscreen)) {
3322 $importlabel = $langs->trans("Import");
3323 $exportlabel = $langs->trans("Export");
3324 }
3325
3326 if ($atleastonepage) {
3327 print '<input type="submit" class="button bordertransp" disabled="disabled" value="'.dol_escape_htmltag($importlabel).'" name="importsite">';
3328 } else {
3329 print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($importlabel).'" name="importsite">';
3330 }
3331
3332 // // Export web site
3333 $extraCssClass = getDolGlobalString('WEBSITE_ALLOW_OVERWRITE_GIT_SOURCE') ? 'hideobject' : '';
3334 print '<input type="submit" class="button bordertransp ' . $extraCssClass . '" ' . $disabledexport . ' value="' . dol_escape_htmltag($exportlabel) . '" name="exportsite">';
3335
3336 if (getDolGlobalString('WEBSITE_ALLOW_OVERWRITE_GIT_SOURCE')) {
3337 // Overwrite template in sources
3338 $overwriteGitUrl = $_SERVER["PHP_SELF"] . '?action=overwritesite&website=' . urlencode($website->ref);
3339 print dolButtonToOpenExportDialog('exportpopup', $langs->trans('ExportOptions'), $langs->trans('ExportSite'), 'exportsite', $overwriteGitUrl, $website);
3340 //print '<a href="'.$_SERVER["PHP_SELF"].'?action=overwritesite&website='.urlencode($website->ref).'" class="button bordertransp hideobject" title="'.dol_escape_htmltag($langs->trans("ExportIntoGIT").". Directory ".getDolGlobalString('WEBSITE_ALLOW_OVERWRITE_GIT_SOURCE')).'">'.dol_escape_htmltag($langs->trans("ExportIntoGIT")).'</a>';
3341 }
3342
3343 // Clone web site
3344 print '<button type="submit" class="button bordertransp buttonpictoonly"'.$disabled.' value="1" name="createfromclone" title="'.dol_escape_htmltag($langs->trans("CloneSite")).'">'.img_picto('', 'clone_nocolor', 'class="fa-rotate-90"').'</button>';
3345
3346 // Delete website
3347 if (!$permissiontodelete) {
3348 $disabled = ' disabled="disabled"';
3349 $title = $langs->trans("NotEnoughPermissions");
3350 $url = '#';
3351 } else {
3352 if ($website->status == $website::STATUS_VALIDATED) {
3353 $disabled = ' disabled="disabled"';
3354 $title = $langs->trans("WebsiteMustBeDisabled", $langs->transnoentitiesnoconv($website->LibStatut(0, 0)));
3355 $url = '#';
3356 } else {
3357 $disabled = '';
3358 $title = $langs->trans("Delete");
3359 $url = $_SERVER["PHP_SELF"].'?action=deletesite&token='.newToken().'&website='.urlencode($website->ref);
3360 }
3361 }
3362 print '<a href="'.$url.'" class="button buttonpictoonly buttonDelete bordertransp'.($disabled ? ' disabled' : '').'"'.$disabled.' title="'.dol_escape_htmltag($title).'">'.img_picto('', 'delete', 'class=""').'</a>';
3363
3364 // Regenerate all pages
3365 print '<a href="'.$_SERVER["PHP_SELF"].'?action=regeneratesite&token='.newToken().'&website='.urlencode($website->ref).'" class="button buttonpictoonly bordertransp"'.$disabled.' title="'.dol_escape_htmltag($langs->trans("RegenerateWebsiteContent")).'"><span class="far fa-hdd"></span></a>';
3366
3367 // Generate site map
3368 print '<a href="'.$_SERVER["PHP_SELF"].'?action=confirmgeneratesitemaps&token='.newToken().'&website='.urlencode($website->ref).'" class="button buttonpictoonly bordertransp"'.$disabled.' title="'.dol_escape_htmltag($langs->trans("GenerateSitemaps")).'"><span class="fa fa-sitemap"></span></a>';
3369
3370 // Find / replace tool
3371 print '<a href="'.$_SERVER["PHP_SELF"].'?action=replacesite&token='.newToken().'&website='.urlencode($website->ref).'" class="button buttonpictoonly bordertransp"'.$disabled.' title="'.dol_escape_htmltag($langs->trans("ReplaceWebsiteContent")).'"><span class="fa fa-search"></span></a>';
3372 }
3373
3374 print '</span>';
3375
3376 if ($websitekey && $websitekey != '-1' && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite')) {
3377 print '<span class="websiteselection">';
3378
3379 print dolButtonToOpenUrlInDialogPopup('file_manager', $langs->transnoentitiesnoconv("MediaFiles"), '<span class="fa fa-image"></span>', '/website/index.php?action=file_manager&website='.urlencode($website->ref).'&section_dir='.urlencode('image/'.$website->ref.'/'), $disabled, 'classlink button bordertransp buttonpictoonly');
3380
3381 if (isModEnabled('category')) {
3382 //print '<a href="'.DOL_URL_ROOT.'/categories/categorie_list.php?leftmenu=website&dol_hide_leftmenu=1&nosearch=1&type=website_page&website='.$website->ref.'" class="button bordertransp"'.$disabled.' title="'.dol_escape_htmltag($langs->trans("Categories")).'"><span class="fa fa-tags"></span></a>';
3383 print dolButtonToOpenUrlInDialogPopup('categories', $langs->transnoentitiesnoconv("Categories"), '<span class="fa fa-tags"></span>', '/categories/categorie_list.php?leftmenu=website&nosearch=1&type='.urlencode(Categorie::TYPE_WEBSITE_PAGE).'&website='.urlencode($website->ref), $disabled, 'classlink button bordertransp buttonpictoonly');
3384 }
3385
3386 print '</span>';
3387 }
3388 } else {
3389 print '<input type="hidden" name="website" id="website" value="'.$websitekey.'">';
3390 }
3391
3392
3393 print '<span class="websitetools">';
3394
3395 if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite') {
3396 $urlext = $virtualurl;
3397 $urlint = $urlwithroot.'/public/website/index.php?website='.$websitekey;
3398
3399 print '<span class="websiteinputurl valignmiddle" id="websiteinputurl">';
3400 $linktotestonwebserver = '<a href="'.($virtualurl ? $virtualurl : '#').'" class="valignmiddle">';
3401 $linktotestonwebserver .= '<span class="hideonsmartphone paddingrightonly">'.$langs->trans("TestDeployOnWeb", $virtualurl).'</span>'.img_picto('', 'globe');
3402 $linktotestonwebserver .= '</a>';
3403
3404 $htmltext = '';
3405 if (empty($object->fk_default_home)) {
3406 $htmltext .= '<br><span class="error">'.$langs->trans("YouMustDefineTheHomePage").'</span><br><br>';
3407 } elseif (empty($virtualurl)) {
3408 //$htmltext .= '<br><span class="error">'.$langs->trans("VirtualHostUrlNotDefined").'</span><br><br>';
3409 } else {
3410 $htmltext .= '<br><center>'.$langs->trans("GoTo").' <a href="'.$virtualurl.'" target="_website">'.$virtualurl.' '.img_picto('', 'url').'</a></center><br>';
3411 }
3412 if (getDolGlobalString('WEBSITE_REPLACE_INFO_ABOUT_USAGE_WITH_WEBSERVER')) {
3413 $htmltext .= '<!-- Message defined translate key set into WEBSITE_REPLACE_INFO_ABOUT_USAGE_WITH_WEBSERVER -->';
3414 $htmltext .= '<br>'.$langs->trans(getDolGlobalString('WEBSITE_REPLACE_INFO_ABOUT_USAGE_WITH_WEBSERVER'));
3415 } else {
3416 $htmltext .= $langs->trans("ToDeployYourWebsiteOnLiveYouHave3Solutions").'<br><br>';
3417 $htmltext .= '<div class="titre inline-block">1</div> - '.$langs->trans("SetHereVirtualHost", $dataroot);
3418 $htmltext .= '<br>';
3419 $htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), DOL_DOCUMENT_ROOT);
3420 $htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("WritePerm"), '{s1}');
3421 $htmltext = str_replace('{s1}', DOL_DATA_ROOT.'/website<br>'.DOL_DATA_ROOT.'/medias', $htmltext);
3422
3423 $examplewithapache = "<VirtualHost *:80>\n";
3424 $examplewithapache .= '#php_admin_value open_basedir /tmp/:'.DOL_DOCUMENT_ROOT.':'.DOL_DATA_ROOT.':/dev/urandom'."\n";
3425 //$examplewithapache .= '#php_admin_value disable_functions "exec,passthru,shell_exec,system,popen,proc_open"'."\n"; This is not effective if not in php.ini
3426 $examplewithapache .= "\n";
3427 $examplewithapache .= 'DocumentRoot "'.DOL_DOCUMENT_ROOT.'"'."\n";
3428 $examplewithapache .= "\n";
3429 $examplewithapache .= '<Directory "'.DOL_DOCUMENT_ROOT.'">'."\n";
3430 $examplewithapache .= 'AllowOverride FileInfo Options
3431 Options -Indexes -MultiViews -FollowSymLinks -ExecCGI
3432 Require all granted
3433 </Directory>'."\n".'
3434 <Directory "'.DOL_DATA_ROOT.'/website">
3435 AllowOverride FileInfo Options
3436 Options -Indexes -MultiViews +FollowSymLinks -ExecCGI
3437 Require all granted
3438 </Directory>'."\n".'
3439 <Directory "'.DOL_DATA_ROOT.'/medias">
3440 AllowOverride FileInfo Options
3441 Options -Indexes -MultiViews -FollowSymLinks -ExecCGI
3442 Require all granted
3443 </Directory>'."\n";
3444
3445 $examplewithapache .= "\n";
3446 $examplewithapache .= "#ErrorLog /var/log/apache2/".$websitekey."_error_log\n";
3447 $examplewithapache .= "#TransferLog /var/log/apache2/".$websitekey."_access_log\n";
3448
3449 $examplewithapache .= "\n";
3450 $examplewithapache .= "# If you need include the payment page into a frame of the website,\n";
3451 $examplewithapache .= "# you need to make a proxy redirection of URLs required for the payment to your backoffice pages\n";
3452 $examplewithapache .= "#SSLProxyEngine On\n";
3453 $examplewithapache .= "#SSLProxyVerify none\n";
3454 $examplewithapache .= "#SSLProxyCheckPeerCN off\n";
3455 $examplewithapache .= "#SSLProxyCheckPeerName off\n";
3456 $examplewithapache .= "#ProxyPreserveHost Off\n";
3457 $examplewithapache .= '#ProxyPass "/public/payment/" "'.$urlwithroot.'/public/payment/'."\n";
3458 $examplewithapache .= '#ProxyPassReverse "/public/payment/" "'.$urlwithroot.'/public/payment/'."\n";
3459 $examplewithapache .= '#ProxyPass "/includes/" "'.$urlwithroot.'/includes/'."\n";
3460 $examplewithapache .= '#ProxyPassReverse "/includes/" "'.$urlwithroot.'/includes/'."\n";
3461 $examplewithapache .= '#ProxyPass "/theme/" "'.$urlwithroot.'/theme/'."\n";
3462 $examplewithapache .= '#ProxyPassReverse "/theme/" "'.$urlwithroot.'/theme/'."\n";
3463 $examplewithapache .= '#ProxyPass "/core/js/" "'.$urlwithroot.'/core/js/'."\n";
3464 $examplewithapache .= '#ProxyPassReverse "/core/js/" "'.$urlwithroot.'/core/js/'."\n";
3465 $examplewithapache .= "\n";
3466
3467 $examplewithapache .= "</VirtualHost>\n";
3468
3469 $htmltext .= '<br>'.$langs->trans("ExampleToUseInApacheVirtualHostConfig").':<br>';
3470 $htmltext .= '<div class="quatrevingtpercent exampleapachesetup wordbreak" spellcheck="false">'.dol_nl2br(dol_escape_htmltag($examplewithapache, 1, 1)).'</div>';
3471
3472 $htmltext .= '<br>';
3473 $htmltext .= '<div class="titre inline-block">2</div> - '.$langs->trans("YouCanAlsoTestWithPHPS");
3474 $htmltext .= '<br><div class="urllink"><input type="text" id="cliphpserver" spellcheck="false" class="quatrevingtpercent" value="php -S 0.0.0.0:8080 -t '.$dataroot.'"></div>';
3475 $htmltext .= ajax_autoselect("cliphpserver");
3476 $htmltext .= '<br>';
3477 $htmltext .= '<div class="titre inline-block">3</div> - '.$langs->trans("YouCanAlsoDeployToAnotherWHP");
3478 }
3479 print $form->textwithpicto($linktotestonwebserver, $htmltext, 1, 'none', 'valignmiddle', 0, 3, 'helpvirtualhost');
3480 print '</span>';
3481 }
3482
3483 if (in_array($action, array('editcss', 'editmenu', 'file_manager', 'editfile', 'replacesiteconfirm', 'editsecurity')) || in_array($mode, array('replacesite'))) {
3484 if (!$user->hasRight('website', 'write')) {
3485 $disabled = ' disabled';
3486 }
3487 if ($action == 'editcss' || $action == 'editsecurity') {
3488 print '<input type="submit" accesskey="s" title="'.dol_escape_htmltag($conf->browser->stringforfirstkey.' s').'" id="savefileandstay" class="button buttonforacesave hideonsmartphone small'.$disabled.'" value="'.dol_escape_htmltag($langs->trans("SaveAndStay")).'" name="updateandstay">';
3489 }
3490 if (preg_match('/^create/', $action) && $action != 'file_manager' && $action != 'replacesite' && $action != 'replacesiteconfirm') {
3491 print '<input type="submit" id="savefile" class="button buttonforacesave button-save small'.$disabled.'" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">';
3492 }
3493 if (preg_match('/^edit/', $action) && $action != 'file_manager' && $action != 'editfile' && $action != 'replacesite' && $action != 'replacesiteconfirm') {
3494 print '<input type="submit" id="savefile" class="button buttonforacesave button-save small'.$disabled.'" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">';
3495 }
3496 if ($action != 'preview') {
3497 print '<input type="submit" class="button button-cancel small" value="'.dol_escape_htmltag($langs->trans("Cancel")).'" name="cancel">';
3498 }
3499 }
3500
3501 print '</span>';
3502
3503 //
3504 // Toolbar for pages
3505 //
3506
3507 if ($websitekey && $websitekey != '-1' && (!in_array($action, array('editcss', 'editmenu', 'importsite', 'file_manager', 'editfile', 'replacesite', 'replacesiteconfirm', 'editsecurity'))) && (!in_array($mode, array('replacesite'))) && !$file_manager) {
3508 print '</div>'; // Close current websitebar to open a new one
3509
3510 print '<!-- Toolbar for websitepage -->';
3511 print '<div class="centpercent websitebar"'.($style ? ' style="'.$style.'"' : '').'>'."\n";
3512
3513 print '<div class="websiteselection hideonsmartphoneimp minwidth75 tdoverflowmax100 inline-block">';
3514 print $langs->trans("PageContainer").': ';
3515 print '</div>';
3516
3517 // Button Add new web page
3518 if ($user->hasRight('website', 'write')) {
3519 print '<span class="websiteselection paddingrightonly">';
3520 print '<a href="'.$_SERVER["PHP_SELF"].'?action=createcontainer&token='.newToken().'&website='.urlencode($website->ref).'" class=""'.$disabled.' title="'.dol_escape_htmltag($langs->trans("AddPage")).'"><span class="fa fa-plus-circle valignmiddle btnTitle-icon"></span></a>';
3521 print '</span>';
3522 }
3523
3524 $out = '';
3525
3526 $s = $formwebsite->selectContainer($website, 'pageid', $pageid, 0, $action, 'minwidth100 maxwidth200onsmartphone');
3527
3528 $out .= '<span class="websiteselection nopaddingrightimp">';
3529 $out .= $s;
3530 $out .= '</span>';
3531
3532 $urltocreatenewpage = $_SERVER["PHP_SELF"].'?action=createcontainer&token='.newToken().'&website='.urlencode($website->ref);
3533
3534 if (!empty($conf->use_javascript_ajax)) {
3535 $out .= '<script type="text/javascript">';
3536 $out .= 'jQuery(document).ready(function () {';
3537 $out .= ' jQuery("#pageid").change(function () {';
3538 $out .= ' console.log("We select "+jQuery("#pageid option:selected").val());';
3539 $out .= ' if (jQuery("#pageid option:selected").val() == \'-2\') {';
3540 $out .= ' window.location.href = "'.$urltocreatenewpage.'";';
3541 $out .= ' } else {';
3542 $out .= ' window.location.href = "'.$_SERVER["PHP_SELF"].'?website='.urlencode($website->ref).'&pageid="+jQuery("#pageid option:selected").val();';
3543 $out .= ' }';
3544 $out .= ' });';
3545 $out .= '});';
3546 $out .= '</script>';
3547 }
3548
3549 print $out;
3550
3551 // List of versions of page (the archived backup files saved each time the page content was saved)
3552 if ($pageid > 0 && $websitekey && $websitekey != '-1') {
3553 $listofpageversions = dol_dir_list($pathofwebsite, 'files', 0, '^page'.((int) $pageid).'\.tpl\.php\.v[0-9]+$', '', 'name', SORT_DESC);
3554
3555 $out = '';
3556
3557 $out .= '<span class="websiteselection nopaddingrightimp">';
3558 $out .= '<select name="pageversion" id="pageversion" class="minwidth100 maxwidth200onsmartphone" title="'.dol_escape_htmltag($langs->trans("ListOfPageVersions")).'">';
3559 $out .= '<option value="0"'.(empty($pageversion) ? ' selected' : '').' class="opacitymedium">';
3560 $out .= $langs->trans("CurrentPageVersion");
3561 $out .= '</option>';
3562 foreach ($listofpageversions as $key => $fileversion) {
3563 $versiontimestamp = (int) preg_replace('/^page'.((int) $pageid).'\.tpl\.php\.v/', '', $fileversion['name']);
3564 if (empty($versiontimestamp)) {
3565 continue;
3566 }
3567 $out .= '<option value="'.((int) $versiontimestamp).'"'.($pageversion == $versiontimestamp ? ' selected' : '').'>';
3568 $out .= dol_print_date($versiontimestamp, 'dayhour', 'tzuser');
3569 $out .= '</option>';
3570 }
3571 $out .= '</select>';
3572 $out .= ajax_combobox('pageversion');
3573
3574 if (!empty($conf->use_javascript_ajax)) {
3575 $out .= '<script type="text/javascript">';
3576 $out .= 'jQuery(document).ready(function () {';
3577 $out .= ' jQuery("#pageversion").change(function () {';
3578 $out .= ' console.log("We select version "+jQuery("#pageversion option:selected").val());';
3579 $out .= ' window.location.href = "'.$_SERVER["PHP_SELF"].'?website='.urlencode($website->ref).'&pageid='.((int) $pageid).'&pageversion="+jQuery("#pageversion option:selected").val();';
3580 $out .= ' });';
3581 $out .= '});';
3582 $out .= '</script>';
3583 }
3584
3585 $out .= '</span>';
3586
3587 print $out;
3588 }
3589
3590 // Button to switch status
3591 if (!empty($conf->use_javascript_ajax)) {
3592 print '<span class="websiteselection">';
3593 //print '<div class="inline-block marginrightonly">';
3594 if ($object->status == $object::STATUS_DRAFT) { // website is off, we do not allow to change status of page
3595 $text_off = 'SetWebsiteOnlineBefore';
3596 if ($websitepage->status == $websitepage::STATUS_DRAFT) { // page is off
3597 print '<span class="valignmiddle disabled opacitymedium">'.img_picto($langs->trans($text_off), 'switch_off', '', 0, 0, 0, '', $morecss).'</span>';
3598 } else {
3599 print '<span class="valignmiddle disabled opacitymedium">'.img_picto($langs->trans($text_off), 'switch_on', '', 0, 0, 0, '', $morecss).'</span>';
3600 }
3601 } else {
3602 if ($objectpage->type_container != 'setup') { // we do not allow to change status of setup pages
3603 print ajax_object_onoff($websitepage, 'status', 'status', 'Online', 'Offline', array(), 'valignmiddle inline-block'.((empty($websitepage->id) || !$user->hasRight('website', 'write')) ? ' opacitymedium disabled' : ''), 'statuswebsitepage', 1, 'website='.urlencode($website->ref).'&pageid='.((int) $websitepage->id), $user->hasRight('website', 'write') ? 0 : 1);
3604 }
3605 }
3606 //print '</div>';
3607 print '</span>';
3608 }
3609
3610 print '<span class="websiteselection">';
3611
3612 print '<input type="image" class="valignmiddle buttonwebsite hideonsmartphone" src="'.img_picto('', 'refresh', '', 0, 1).'" name="refreshpage" value="'.$langs->trans("Load").'"'.(($action != 'editsource') ? '' : ' disabled="disabled"').'>';
3613
3614 // Print nav arrows
3615 $pagepreviousid = 0;
3616 $pagenextid = 0;
3617 if ($pageid) {
3618 $sql = "SELECT MAX(rowid) as pagepreviousid FROM ".MAIN_DB_PREFIX."website_page WHERE rowid < ".((int) $pageid)." AND fk_website = ".((int) $object->id);
3619 $resql = $db->query($sql);
3620 if ($resql) {
3621 $obj = $db->fetch_object($resql);
3622 if ($obj) {
3623 $pagepreviousid = $obj->pagepreviousid;
3624 }
3625 } else {
3626 dol_print_error($db);
3627 }
3628 $sql = "SELECT MIN(rowid) as pagenextid FROM ".MAIN_DB_PREFIX."website_page WHERE rowid > ".((int) $pageid)." AND fk_website = ".((int) $object->id);
3629 $resql = $db->query($sql);
3630 if ($resql) {
3631 $obj = $db->fetch_object($resql);
3632 if ($obj) {
3633 $pagenextid = $obj->pagenextid;
3634 }
3635 } else {
3636 dol_print_error($db);
3637 }
3638 }
3639
3640 if ($pagepreviousid) {
3641 print '<a class="valignmiddle" href="'.$_SERVER['PHP_SELF'].'?website='.urlencode($object->ref).'&pageid='.((int) $pagepreviousid).'&action='.urlencode($action).'&token='.newToken().'">'.img_previous($langs->trans("PreviousContainer")).'</a>';
3642 } else {
3643 print '<span class="valignmiddle opacitymedium">'.img_previous($langs->trans("PreviousContainer")).'</span>';
3644 }
3645 if ($pagenextid) {
3646 print '<a class="valignmiddle" href="'.$_SERVER['PHP_SELF'].'?website='.urlencode($object->ref).'&pageid='.((int) $pagenextid).'&action='.urlencode($action).'&token='.newToken().'">'.img_next($langs->trans("NextContainer")).'</a>';
3647 } else {
3648 print '<span class="valignmiddle opacitymedium">'.img_next($langs->trans("NextContainer")).'</span>';
3649 }
3650
3651 print '</span>';
3652
3653 if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite') {
3654 $disabled = '';
3655 if (!$user->hasRight('website', 'write')) {
3656 $disabled = ' disabled="disabled"';
3657 }
3658
3659 // Confirmation delete site
3660 if ($action == 'deletesite') {
3661 // Create an array for form
3662 $formquestion = array(
3663 array('type' => 'checkbox', 'name' => 'delete_also_js', 'label' => $langs->trans("DeleteAlsoJs"), 'value' => 0),
3664 array('type' => 'checkbox', 'name' => 'delete_also_medias', 'label' => $langs->trans("DeleteAlsoMedias"), 'value' => 0),
3665 //array('type' => 'other','name' => 'newlang','label' => $langs->trans("Language"), 'value' => $formadmin->select_language(GETPOST('newlang', 'aZ09')?GETPOST('newlang', 'aZ09'):$langs->defaultlang, 'newlang', 0, null, '', 0, 0, 'minwidth200')),
3666 //array('type' => 'other','name' => 'newwebsite','label' => $langs->trans("WebSite"), 'value' => $formwebsite->selectWebsite($object->id, 'newwebsite', 0))
3667 );
3668
3669 if ($atleastonepage) {
3670 $langs->load("errors");
3671 $formquestion[] = array('type' => 'onecolumn', 'value' => '<div class="warning">'.$langs->trans("WarningPagesWillBeDeleted").'</div>');
3672 }
3673
3674 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteWebsite'), '', 'confirm_deletesite', $formquestion, 0, 1, 'auto', 580);
3675
3676 print $formconfirm;
3677 }
3678
3679 // Confirmation to clone
3680 if ($action == 'createfromclone') {
3681 // Create an array for form
3682 $formquestion = array(
3683 array('type' => 'text', 'name' => 'siteref', 'label' => $langs->trans("WebSite"), 'value' => 'copy_of_'.$object->ref)
3684 );
3685
3686 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('CloneSite'), '', 'confirm_createfromclone', $formquestion, 0, 1, 0);
3687
3688 print $formconfirm;
3689 }
3690
3691 if ($pageid > 0 && $atleastonepage) { // pageid can be set without pages, if homepage of site is set and all pages were removed
3692 // Confirmation to clone
3693 if ($action == 'createpagefromclone') {
3694 // Create an array for form
3695 $preselectedlanguage = GETPOST('newlang', 'aZ09') ? GETPOST('newlang', 'aZ09') : ($objectpage->lang ?: ''); // By default, we do not force any language on pages
3696 $onlylang = array();
3697 if ($website->otherlang) {
3698 if (!empty($website->lang)) {
3699 $onlylang[$website->lang] = $website->lang.' ('.$langs->trans("Default").')';
3700 }
3701 foreach (explode(',', $website->otherlang) as $langkey) {
3702 if (empty(trim($langkey))) {
3703 continue;
3704 }
3705 $onlylang[$langkey] = $langkey;
3706 }
3707 $textifempty = $langs->trans("Default");
3708 } else {
3709 $onlylang['none'] = 'none';
3710 $textifempty = $langs->trans("Default");
3711 }
3712
3713 $formquestion = array(
3714 array('type' => 'hidden', 'name' => 'sourcepageurl', 'value' => $objectpage->pageurl),
3715 array('type' => 'other', 'tdclass' => 'fieldrequired', 'name' => 'newwebsite', 'label' => $langs->trans("WebSite"), 'value' => $formwebsite->selectWebsite((string) $object->id, 'newwebsite', 0)),
3716 array('type' => 'text', 'tdclass' => 'maxwidth200 fieldrequired', 'moreattr' => 'autofocus="autofocus"', 'name' => 'newtitle', 'label' => $langs->trans("WEBSITE_TITLE"), 'value' => $langs->trans("CopyOf").' '.$objectpage->title),
3717 array('type' => 'text', 'tdclass' => 'maxwidth200', 'name' => 'newpageurl', 'label' => $langs->trans("WEBSITE_PAGENAME"), 'value' => '')
3718 );
3719 if (count($onlylang) > 1) {
3720 $formquestion[] = array('type' => 'checkbox', 'tdclass' => 'maxwidth200', 'name' => 'is_a_translation', 'label' => $langs->trans("PageIsANewTranslation"), 'value' => 0,
3721 'morecss' => 'margintoponly',
3722 'moreattr' => 'onclick="console.log(\'Click on is_a_translation\'); jQuery(\'#newlang\').val(-1).trigger(\'change\');"'
3723 );
3724 }
3725
3726 $value = $formadmin->select_language($preselectedlanguage, 'newlang', 0, array(), $textifempty, 0, 0, 'minwidth200', 1, 0, 0, $onlylang, 1);
3727 $formquestion[] = array('type' => 'other', 'name' => 'newlang', 'label' => $form->textwithpicto($langs->trans("Language"), $langs->trans("DefineListOfAltLanguagesInWebsiteProperties")), 'value' => $value);
3728
3729 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$pageid, $langs->trans('ClonePage'), '', 'confirm_createpagefromclone', $formquestion, 0, 1, 0, 550);
3730
3731 print $formconfirm;
3732 }
3733
3734 print '<span class="websiteselection">';
3735
3736 // Edit web page properties
3737 print '<a href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$pageid.'&action=editmeta&token='.newToken().'" class="button bordertransp valignmiddle" title="'.dol_escape_htmltag($langs->trans("EditPageMeta")).'"'.$disabled.'>';
3738 print img_picto('', 'setup');
3739 print '<span class="hideonsmartphone paddingleft">'.dol_escape_htmltag($langs->trans("EditPageMeta")).'</span>';
3740 print '</a>';
3741
3742 // Edit HTML content
3743 print '<a href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$pageid.($pageversion > 0 ? '&pageversion='.((int) $pageversion) : '').'&action=editsource&token='.newToken().'" class="button bordertransp"'.$disabled.'>';
3744 print img_picto('', 'code');
3745 print '<span class="hideonsmartphone paddingleft">'.dol_escape_htmltag($langs->trans($conf->dol_optimize_smallscreen ? "HTML" : "EditHTMLSource")).'</span>';
3746 print '</a>';
3747
3748 // Edit CKEditor
3749 if (getDolGlobalInt('WEBSITE_ALLOW_CKEDITOR')) {
3750 print '<a href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$pageid.'&action=editcontent&token='.newToken().'" class="button bordertransp"'.$disabled.'>'.dol_escape_htmltag("CKEditor").'</a>';
3751 } else {
3752 print '<!-- Add option WEBSITE_ALLOW_CKEDITOR to allow ckeditor -->';
3753 }
3754
3755 print '</span>';
3756
3757
3758 // Switch include dynamic content / edit inline
3759 print '<!-- button EditInLine and ShowSubcontainers -->'."\n";
3760 print '<div class="websiteselectionsection inline-block">';
3761
3762 // Force to show subcontainers if we are in setup mode
3763 if ($objectpage->type_container == 'setup') {
3764 dolibarr_set_const($db, 'WEBSITE_SUBCONTAINERSINLINE', 1);
3765 }
3766
3767 if ($objectpage->type_container != 'setup') {
3768 print '<div class="inline-block marginrightonly">'; // Button includes dynamic content
3769 print $langs->trans("ShowSubcontainers");
3770 if (!getDolGlobalString('WEBSITE_SUBCONTAINERSINLINE')) {
3771 print '<a class="nobordertransp nohoverborder marginleftonlyshort valignmiddle"'.$disabled.' href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$websitepage->id.'&action=setshowsubcontainers&token='.newToken().'">'.img_picto($langs->trans("ShowSubContainersOnOff", $langs->transnoentitiesnoconv("Off")), 'switch_off', '', 0, 0, 0, '', 'nomarginleft').'</a>';
3772 } else {
3773 print '<a class="nobordertransp nohoverborder marginleftonlyshort valignmiddle"'.$disabled.' href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$websitepage->id.'&action=unsetshowsubcontainers&token='.newToken().'">'.img_picto($langs->trans("ShowSubContainersOnOff", $langs->transnoentitiesnoconv("On")), 'switch_on', '', 0, 0, 0, '', 'nomarginleft').'</a>';
3774 }
3775 print '</div>';
3776 }
3777
3778 print '<div class="inline-block marginrightonly">'; // Button edit inline
3779
3780 print '<span id="switchckeditorinline">';
3781 print $langs->trans("EditInLine");
3782 print '</span>';
3783
3784 // Enable edit inline of the elements with contenteditable="true" and an id. Which elements can be edited and how
3785 // is found from the source of the page (no php code, only text or formatting tags, ...), see dolWebsiteGetEditInlineElements().
3786 // Elements with formatting tags are edited with CKEditor, elements with only text inside that CKEditor can't edit
3787 // (span, a, li...) are edited as plain text. The content is checked again when it is saved.
3788 if (getDolGlobalString('WEBSITE_EDITINLINE') && empty($filetplversion) && $usercanedit) {
3789 $editinlineelements = array();
3790 foreach (dolWebsiteGetEditInlineElements($websitepage->content) as $id => $element) {
3791 $editinlineelements[$id] = array(
3792 'mode' => $element['mode'],
3793 'blocks' => $element['blocks'],
3794 'error' => ($element['error'] ? $langs->transnoentitiesnoconv($element['error'], $id) : '')
3795 );
3796 }
3797
3798 // Close the warning that explains which elements can be edited after 10 seconds
3799 print '<script>
3800 $(document).ready(function() {
3801 setTimeout(function() {
3802 $(".jnotify-notification").has(".editinlineallowedareas").fadeOut(500, function() { $(this).remove(); });
3803 }, 10000);
3804 });
3805 </script>'."\n";
3806
3807 print '<!-- Code to enable edit inline of elements with contenteditable="true" -->'."\n";
3808 print '<style>
3809 .bodywebsite .dol-edit-text, .bodywebsite .dol-edit-html { outline: 1px dashed #888; outline-offset: 2px; cursor: text; }
3810 .bodywebsite .dol-edit-text:focus, .bodywebsite .dol-edit-html:focus { outline: 2px solid #4a90d9; }
3811 .bodywebsite .dol-edit-refused { outline: 1px dashed #c66; outline-offset: 2px; cursor: not-allowed; }
3812 </style>'."\n";
3813 print '<script>
3814 $(document).ready(function() {
3815 var editInlineElements = '.json_encode($editinlineelements, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT).';
3816
3817 // Save the new content of an element with ajax
3818 function saveEditInline(element, data, callback) {
3819 console.log("Element "+element.id+" was modified, we send new content for update with ajax");
3820 data.page_id = '.((int) $websitepage->id).';
3821 data.element_id = element.id;
3822 data.token = \''.dol_escape_js(newToken()).'\';
3823 $.ajax({
3824 type: "POST",
3825 url: \''.dol_escape_js(DOL_URL_ROOT.'/core/ajax/editinline.php').'\',
3826 dataType: "json",
3827 data: data
3828 }).done(function(response) {
3829 callback(response);
3830 $.jnotify(response.message, "ok");
3831 }).fail(function(xhr) {
3832 $.jnotify((xhr.responseJSON && xhr.responseJSON.error) ? xhr.responseJSON.error : \''.dol_escape_js($langs->trans("Error")).' \'+xhr.status, "error", true);
3833 });
3834 }
3835
3836 function refuseEditInline(element, message) {
3837 console.warn(message);
3838 element.contentEditable = "false";
3839 $(element).addClass("dol-edit-refused").attr("title", message);
3840 }
3841
3842 $("#websitecontentundertopmenu [contenteditable=\"true\"]").each(function() {
3843 var element = this;
3844 var tag = element.tagName.toLowerCase();
3845 if (!element.id) {
3846 refuseEditInline(element, \''.dol_escape_js($langs->transnoentitiesnoconv("ErrorEditInlineElementNoId")).'\');
3847 return;
3848 }
3849 if (!Object.prototype.hasOwnProperty.call(editInlineElements, element.id)) {
3850 // Element not found into the source of the page (it may come from an included container)
3851 refuseEditInline(element, \''.dol_escape_js($langs->transnoentitiesnoconv("ErrorEditInlineElementNotFound", "__ID__")).'\'.replace("__ID__", element.id));
3852 return;
3853 }
3854 var info = editInlineElements[element.id];
3855 if (!info.mode) {
3856 refuseEditInline(element, info.error);
3857 return;
3858 }
3859
3860 if (typeof CKEDITOR !== "undefined" && CKEDITOR.dtd.$editable[tag]) {
3861 // Edit with CKEditor. Allow only the tags accepted when saving, see dolWebsiteCheckEditInlineHtml().
3862 var allowedcontent = "a[!href,target,rel,title]{*}(*); b i u s em strong sub sup span[title]{*}(*); br";
3863 var toolbar = [
3864 ["Undo", "Redo"],
3865 ["Bold", "Italic", "Underline", "Strike", "Subscript", "Superscript", "-", "RemoveFormat"],
3866 ["Link", "Unlink"],
3867 ["Font", "FontSize"],
3868 ["TextColor", "BGColor"]
3869 ];
3870 if (info.blocks) {
3871 allowedcontent += "; p h1 h2 h3 h4 h5 h6 ul ol li blockquote div[title]{*}(*)";
3872 toolbar.splice(2, 0, ["NumberedList", "BulletedList", "-", "Blockquote"], ["JustifyLeft", "JustifyCenter", "JustifyRight", "JustifyBlock"]);
3873 toolbar.splice(5, 1, ["Format", "Font", "FontSize"]);
3874 }
3875 var editor = CKEDITOR.inline(element, {
3876 allowedContent: allowedcontent,
3877 entities: false,
3878 format_tags: "p;h1;h2;h3;h4;h5;h6",
3879 removePlugins: "flash,stylescombo,exportpdf,scayt,wsc,pagebreak,iframe,smiley",
3880 toolbar: toolbar
3881 });
3882 $(element).addClass("dol-edit-html");
3883 editor.on("blur", function() {
3884 if (!editor.checkDirty()) {
3885 return;
3886 }
3887 saveEditInline(element, {action: "updateElementHtml", content: editor.getData()}, function() {
3888 editor.resetDirty();
3889 });
3890 });
3891 } else if (info.mode == "text") {
3892 // Edit as plain text. Replace the content with the text as it is rendered, because the line feeds
3893 // and spaces of the source are no more collapsed once the element is editable as plain text.
3894 element.innerText = element.innerText;
3895 try {
3896 element.contentEditable = "plaintext-only";
3897 } catch (e) {
3898 // Browser without support of plaintext-only: keep "true", paste is converted into text below
3899 }
3900 $(element).addClass("dol-edit-text").data("dolEditText", element.innerText);
3901 } else {
3902 refuseEditInline(element, \''.dol_escape_js($langs->transnoentitiesnoconv("ErrorEditInlineElementNotPlainText", "__ID__")).'\'.replace("__ID__", element.id));
3903 }
3904 });
3905
3906 $("#websitecontentundertopmenu").on("paste", ".dol-edit-text", function(e) {
3907 e.preventDefault();
3908 document.execCommand("insertText", false, e.originalEvent.clipboardData.getData("text/plain"));
3909 });
3910
3911 $("#websitecontentundertopmenu").on("keydown", ".dol-edit-text", function(e) {
3912 if (e.key === "Escape") { // Cancel the changes
3913 this.innerText = $(this).data("dolEditText");
3914 this.blur();
3915 }
3916 });
3917
3918 $("#websitecontentundertopmenu").on("blur", ".dol-edit-text", function() {
3919 var element = this;
3920 var text = element.innerText;
3921 if (text === $(element).data("dolEditText")) {
3922 return;
3923 }
3924 saveEditInline(element, {action: "updateElementText", text: text}, function(response) {
3925 $(element).data("dolEditText", response.text);
3926 if (response.text !== text && document.activeElement !== element) {
3927 element.innerText = response.text;
3928 }
3929 });
3930 });
3931 });
3932 </script>'."\n";
3933 }
3934
3935 //$disableeditinline = $websitepage->grabbed_from;
3936 $disableeditinline = 0;
3937 if ($disableeditinline) {
3938 //print '<input type="submit" class="button bordertransp" disabled="disabled" title="'.dol_escape_htmltag($langs->trans("OnlyEditionOfSourceForGrabbedContent")).'" value="'.dol_escape_htmltag($langs->trans("EditWithEditor")).'" name="editcontent">';
3939 print '<a class="nobordertransp opacitymedium nohoverborder marginleftonlyshort"'.$disabled.' href="#" disabled="disabled" title="'.dol_escape_htmltag($langs->trans("OnlyEditionOfSourceForGrabbedContent")).'">'.img_picto($langs->trans("OnlyEditionOfSourceForGrabbedContent"), 'switch_off', '', 0, 0, 0, '', 'nomarginleft').'</a>';
3940 } else {
3941 //print '<input type="submit" class="button nobordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("EditWithEditor")).'" name="editcontent">';
3942 if (!getDolGlobalString('WEBSITE_EDITINLINE')) {
3943 print '<a class="nobordertransp nohoverborder marginleftonlyshort valignmiddle"'.$disabled.' href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$websitepage->id.'&action=seteditinline&token='.newToken().'">'.img_picto($langs->trans("EditInLineOnOff", $langs->transnoentitiesnoconv("Off")), 'switch_off', '', 0, 0, 0, '', 'nomarginleft').'</a>';
3944 } else {
3945 print '<a class="nobordertransp nohoverborder marginleftonlyshort valignmiddle"'.$disabled.' href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$websitepage->id.'&action=unseteditinline&token='.newToken().'">'.img_picto($langs->trans("EditInLineOnOff", $langs->transnoentitiesnoconv("On")), 'switch_on', '', 0, 0, 0, '', 'nomarginleft').'</a>';
3946 }
3947 }
3948
3949 print '</div>';
3950
3951 print '</div>';
3952
3953 // Set page as homepage
3954 print '<span class="websiteselection">';
3955 if ($object->fk_default_home > 0 && $pageid == $object->fk_default_home) {
3956 //$disabled=' disabled="disabled"';
3957 //print '<span class="button bordertransp disabled"'.$disabled.' title="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'"><span class="fas fa-home"></span></span>';
3958 //print '<input type="submit" class="button bordertransp" disabled="disabled" value="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'" name="setashome">';
3959 print '<a href="#" class="button buttonpictoonly bordertransp disabled" disabled="disabled" title="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'"><span class="fas fa-home valignmiddle btnTitle-icon"></span></a>';
3960 } else {
3961 //$disabled='';
3962 //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'" name="setashome">';
3963 print '<a href="'.$_SERVER["PHP_SELF"].'?action=confirmsetashome&token='.newToken().'&website='.urlencode($website->ref).'&pageid='.((int) $pageid).'" class="button buttonpictoonly bordertransp"'.$disabled.' title="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'"><span class="fas fa-home valignmiddle btnTitle-icon"></span></a>';
3964 }
3965 print '<button type="submit" class="button bordertransp buttonpictoonly"'.$disabled.' value="1" name="createpagefromclone" title="'.dol_escape_htmltag($langs->trans("ClonePage")).'">'.img_picto('', 'clone_nocolor', 'class="fa-rotate-90"').'</button>';
3966
3967 // Delete
3968 if (!$permissiontodelete) {
3969 $disabled = ' disabled="disabled"';
3970 $title = $langs->trans("NotEnoughPermissions");
3971 $url = '#';
3972 } elseif ($websitepage->status != $websitepage::STATUS_DRAFT) {
3973 $disabled = ' disabled="disabled"';
3974 $title = $langs->trans("WebpageMustBeDisabled", $langs->transnoentitiesnoconv($websitepage->LibStatut(0, 0)));
3975 $url = '#';
3976 } else {
3977 $disabled = '';
3978 $title = $langs->trans("Delete");
3979 $url = $_SERVER["PHP_SELF"].'?action=delete&token='.newToken().'&pageid='.((int) $websitepage->id).'&website='.urlencode($website->ref); // action=delete for webpage, deletesite for website
3980 }
3981 print '<a href="'.$url.'" class="button buttonpictoonly buttonDelete bordertransp'.($disabled ? ' disabled' : '').'"'.$disabled.' title="'.dol_escape_htmltag($title).'">'.img_picto('', 'delete', 'class=""').'</a>';
3982 print '</span>';
3983 }
3984 }
3985
3986 //print '</span>'; // end website selection
3987
3988 print '<span class="websitetools">';
3989
3990 if (($pageid > 0 && $atleastonepage) && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite')) {
3991 $realpage = $urlwithroot.'/public/website/index.php?website='.$websitekey.'&pageref='.$websitepage->pageurl;
3992 $pagealias = $websitepage->pageurl;
3993
3994 $htmltext = $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage, $langs->transnoentitiesnoconv("TestDeployOnWeb"));
3995 //$htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), '{s1}');
3996 //$htmltext = str_replace('{s1}', $dataroot.'<br>'.DOL_DATA_ROOT.'/medias<br>'.DOL_DOCUMENT_ROOT, $htmltext);
3997 //$htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("WritePerm"), '{s1}');
3998 //$htmltext = str_replace('{s1}', DOL_DATA_ROOT.'/medias', $htmltext);
3999
4000 print '<div class="websiteinputurl inline-block paddingright">';
4001 print '<a class="websitebuttonsitepreview inline-block" id="previewpage" href="'.$realpage.'&nocache='.dol_now().'" class="button" target="tab'.$websitekey.'" alt="'.dol_escape_htmltag($htmltext).'">';
4002 print $form->textwithpicto('', $htmltext, 1, 'preview');
4003 print '</a>'; // View page in new Tab
4004 print '</div>';
4005
4006 /*print '<div class="websiteinputurl inline-block" id="websiteinputpage">';
4007 print '<input type="text" id="previewpageurl" class="minwidth200imp" name="previewsite" value="'.$pagealias.'" disabled="disabled">';
4008 $htmltext = $langs->trans("PageNameAliasHelp", $langs->transnoentitiesnoconv("EditPageMeta"));
4009 print $form->textwithpicto('', $htmltext, 1, 'help', '', 0, 2, 'helppagealias');
4010 print '</div>';*/
4011
4012 /*
4013 $urlext = $virtualurl.'/'.$pagealias.'.php';
4014 $urlint = $urlwithroot.'/public/website/index.php?website='.$websitekey;
4015
4016 $htmltext = $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $virtualurl ? $urlext : '<span class="error">'.$langs->trans("VirtualHostUrlNotDefined").'</span>');
4017
4018 print '<a class="websitebuttonsitepreview'.($virtualurl ? '' : ' websitebuttonsitepreviewdisabled cursornotallowed').'" id="previewpageext" href="'.$urlext.'" target="tab'.$websitekey.'ext" alt="'.dol_escape_htmltag($htmltext).'">';
4019 print $form->textwithpicto('', $htmltext, 1, 'preview_ext');
4020 print '</a>';
4021 */
4022 //print '<input type="submit" class="button" name="previewpage" target="tab'.$websitekey.'"value="'.$langs->trans("ViewPageInNewTab").'">';
4023
4024 // TODO Add js to save alias like we save virtual host name and use dynamic virtual host for url of id=previewpageext
4025 }
4026 if (!in_array($mode, array('replacesite')) && !in_array($action, array('editcss', 'editmenu', 'file_manager', 'editfile', 'replacesiteconfirm', 'createsite', 'createcontainer', 'createfromclone', 'createpagefromclone', 'deletesite', 'editsecurity'))) {
4027 if (!$user->hasRight('website', 'write')) {
4028 $disabled = ' disabled';
4029 }
4030 if ($action == 'editsource' || $action == 'editmeta') {
4031 print '<input type="submit" accesskey="s" title="'.dol_escape_htmltag($conf->browser->stringforfirstkey.' s').'" id="savefileandstay" class="button buttonforacesave hideonsmartphone small'.$disabled.'" value="'.dol_escape_htmltag($langs->trans("SaveAndStay")).'" name="updateandstay">';
4032 }
4033 if (preg_match('/^create/', $action)) {
4034 print '<input type="submit" id="savefile" class="button buttonforacesave button-save small'.$disabled.'" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">';
4035 }
4036 if (preg_match('/^edit/', $action)) {
4037 print '<input type="submit" id="savefile" class="button buttonforacesave button-save small'.$disabled.'" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">';
4038 }
4039 if ($action != 'preview') {
4040 print '<input type="submit" class="button button-cancel small" value="'.dol_escape_htmltag($langs->trans("Cancel")).'" name="cancel">';
4041 }
4042 }
4043
4044 print '</span>'; // end websitetools
4045
4046 print '<span class="websitehelp">';
4047 if ($action == 'editsource' || $action == 'editcontent' || GETPOST('editsource', 'alpha') || GETPOST('editcontent', 'alpha')) {
4048 $url = 'https://wiki.dolibarr.org/index.php/Module_Website';
4049
4050 $htmltext = '<small>';
4051 $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSource", $url);
4052 $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSourceb", $url);
4053 $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSourcec", $url);
4054 $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSourced", $url);
4055 $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSource1", $url);
4056 $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSource2", $url);
4057 $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSource3", $url);
4058 $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSource4", $url);
4059 $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSource5", $url);
4060 $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSourceMore", $url);
4061 $htmltext .= '<br>';
4062 $htmltext .= '</small>';
4063 if ($conf->browser->layout == 'phone') {
4064 print $form->textwithpicto('', $htmltext, 1, 'help', 'inline-block', 1, 2, 'tooltipsubstitution');
4065 } else {
4066 //img_help(($tooltiptrigger != '' ? 2 : 1), $alt)
4067 print $form->textwithpicto($langs->trans("SyntaxHelp").' '.img_help(2, $langs->trans("SyntaxHelp")), $htmltext, 1, 'none', 'inline-block', 1, 2, 'tooltipsubstitution');
4068 }
4069 }
4070 print '</span>'; // end websitehelp
4071
4072
4073 if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') {
4074 // Adding jquery code to change on the fly url of preview ext
4075 if (!empty($conf->use_javascript_ajax)) {
4076 print '<script type="text/javascript">
4077 jQuery(document).ready(function() {
4078 jQuery("#websiteinputurl").keyup(function() {
4079 console.log("Website external url modified "+jQuery("#previewsiteurl").val());
4080 if (jQuery("#previewsiteurl").val() != "" && jQuery("#previewsiteurl").val().startsWith("http"))
4081 {
4082 jQuery("a.websitebuttonsitepreviewdisabled img").css({ opacity: 1 });
4083 }
4084 else jQuery("a.websitebuttonsitepreviewdisabled img").css({ opacity: 0.2 });
4085 ';
4086 print '
4087 });
4088 jQuery("#previewsiteext,#previewpageext").click(function() {
4089
4090 newurl=jQuery("#previewsiteurl").val();
4091 if (! newurl.startsWith("http"))
4092 {
4093 alert(\''.dol_escape_js($langs->trans("ErrorURLMustStartWithHttp")).'\');
4094 return false;
4095 }
4096
4097 newpage=jQuery("#previewsiteurl").val() + "/" + jQuery("#previewpageurl").val() + ".php";
4098 console.log("Open url "+newurl);
4099 /* Save url */
4100 jQuery.ajax({
4101 method: "POST",
4102 url: "'.DOL_URL_ROOT.'/core/ajax/saveinplace.php",
4103 data: {
4104 token: \''.currentToken().'\',
4105 field: \'editval_virtualhost\',
4106 element: \'website\',
4107 table_element: \'website\',
4108 fk_element: '.((int) $object->id).',
4109 value: newurl,
4110 },
4111 context: document.body
4112 });
4113
4114 jQuery("#previewsiteext").attr("href",newurl);
4115 jQuery("#previewpageext").attr("href",newpage);
4116 });
4117 });
4118 </script>';
4119 }
4120 }
4121 }
4122
4123 print '</div>'."\n"; // end current websitebar
4124}
4125
4126
4127$head = array();
4128
4129
4130/*
4131 * Edit Site HTML header and CSS
4132 */
4133
4134if ($action == 'editcss') {
4135 print '<div class="fiche">';
4136
4137 print '<br>';
4138
4139 if (!GETPOSTISSET('WEBSITE_CSS_INLINE')) {
4140 $csscontent = @file_get_contents($filecss);
4141 // Clean the php css file to remove php code and get only css part
4142 $csscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP( \?>)?\n*/ims', '', $csscontent);
4143 } else {
4144 $csscontent = GETPOST('WEBSITE_CSS_INLINE', 'none');
4145 }
4146 if (!trim($csscontent)) {
4147 $csscontent = '/* CSS content (all pages) */'."\nbody.bodywebsite { margin: 0; font-family: 'Open Sans', sans-serif; }\n.bodywebsite h1 { margin-top: 0; margin-bottom: 0; padding: 10px;}";
4148 }
4149
4150 if (!GETPOSTISSET('WEBSITE_JS_INLINE')) {
4151 $jscontent = @file_get_contents($filejs);
4152 // Clean the php js file to remove php code and get only js part
4153 $jscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP( \?>)?\n*/ims', '', $jscontent);
4154 } else {
4155 $jscontent = GETPOST('WEBSITE_JS_INLINE', 'none');
4156 }
4157 if (!trim($jscontent)) {
4158 $jscontent = '/* JS content (all pages) */'."\n";
4159 }
4160
4161 if (!GETPOSTISSET('WEBSITE_HTML_HEADER')) {
4162 $htmlheadercontent = @file_get_contents($filehtmlheader);
4163 // Clean the php htmlheader file to remove php code and get only html part
4164 $htmlheadercontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP( \?>)?\n*/ims', '', $htmlheadercontent);
4165 } else {
4166 $htmlheadercontent = GETPOST('WEBSITE_HTML_HEADER', 'none'); // Must accept tags like '<script>' and '<link>'
4167 }
4168 if (!trim($htmlheadercontent)) {
4169 $htmlheadercontent = "<html>\n";
4170 $htmlheadercontent .= $htmlheadercontentdefault;
4171 $htmlheadercontent .= "</html>";
4172 } else {
4173 $htmlheadercontent = preg_replace('/^\s*<html>/ims', '', $htmlheadercontent);
4174 $htmlheadercontent = preg_replace('/<\/html>\s*$/ims', '', $htmlheadercontent);
4175 $htmlheadercontent = '<html>'."\n".trim($htmlheadercontent)."\n".'</html>';
4176 }
4177
4178 if (!GETPOSTISSET('WEBSITE_ROBOT')) {
4179 $robotcontent = @file_get_contents($filerobot);
4180 // Clean the php htmlheader file to remove php code and get only html part
4181 $robotcontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP( \?>)?\n*/ims', '', $robotcontent);
4182 } else {
4183 $robotcontent = GETPOST('WEBSITE_ROBOT', 'nohtml'); // We must use 'nohtml' and not 'alphanohtml' because we must accept "
4184 }
4185 if (!trim($robotcontent)) {
4186 $robotcontent .= "# Robot file. Generated with ".DOL_APPLICATION_TITLE."\n";
4187 $robotcontent .= "User-agent: *\n";
4188 $robotcontent .= "Allow: /public/\n";
4189 $robotcontent .= "Disallow: /administrator/\n";
4190 }
4191
4192 if (!GETPOSTISSET('WEBSITE_HTACCESS')) {
4193 $htaccesscontent = @file_get_contents($filehtaccess);
4194 // Clean the php htaccesscontent file to remove php code and get only html part
4195 $htaccesscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP( \?>)?\n*/ims', '', $htaccesscontent);
4196 } else {
4197 $htaccesscontent = GETPOST('WEBSITE_HTACCESS', 'nohtml'); // We must use 'nohtml' and not 'alphanohtml' because we must accept "
4198 }
4199
4200 if (!GETPOSTISSET('WEBSITE_MANIFEST_JSON')) {
4201 $manifestjsoncontent = @file_get_contents($filemanifestjson);
4202 // Clean the manifestjson file to remove php code and get only html part
4203 $manifestjsoncontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP( \?>)?\n*/ims', '', $manifestjsoncontent);
4204 } else {
4205 $manifestjsoncontent = trim(GETPOST('WEBSITE_MANIFEST_JSON', 'restricthtmlallowunvalid'));
4206 $manifestjsoncontent = str_replace('<?=', '<?php', $manifestjsoncontent);
4207 }
4208
4209 //if (!trim($manifestjsoncontent)) {
4210 //$manifestjsoncontent.="";
4211 //}
4212
4213 if (!GETPOSTISSET('WEBSITE_README')) {
4214 $readmecontent = @file_get_contents($filereadme);
4215 // Clean the readme file to remove php code and get only html part
4216 $readmecontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP( \?>)?\n*/ims', '', $readmecontent);
4217 } else {
4218 $readmecontent = GETPOST('WEBSITE_README', 'restricthtmlallowunvalid');
4219 }
4220 //if (!trim($readmecontent)) {
4221 //$readmecontent.="";
4222 //}
4223
4224 if (!GETPOSTISSET('WEBSITE_LICENSE')) {
4225 $licensecontent = @file_get_contents($filelicense);
4226 // Clean the readme file to remove php code and get only html part
4227 $licensecontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP( \?>)?\n*/ims', '', $licensecontent);
4228 } else {
4229 $licensecontent = GETPOST('WEBSITE_LICENSE', 'restricthtmlallowunvalid');
4230 }
4231 //if (!trim($licensecontent)) {
4232 //$readmecontent.="";
4233 //}
4234
4235 $head = websiteconfigPrepareHead($object);
4236 print dol_get_fiche_head($head, 'general', $langs->trans("General"), 0, 'website');
4237
4238 print '<!-- Edit Website properties (CSS, Language, ...) -->'."\n";
4239 print '<table class="border centpercent">';
4240
4241 // Website
4242 print '<tr><td class="titlefieldcreate fieldrequired">';
4243 print $langs->trans('WebSite');
4244 print '</td><td>';
4245 print $websitekey;
4246 print '</td></tr>';
4247
4248 // Status of web site
4249 if ($action != 'createcontainer') {
4250 if (empty($conf->use_javascript_ajax)) {
4251 print '<!-- Status of web site page -->'."\n";
4252 print '<tr><td class="fieldrequired">';
4253 print $langs->trans('Status');
4254 print '</td><td>';
4255 print $form->selectyesno('status', $object->status);
4256 print '</td></tr>';
4257 }
4258 }
4259
4260 // Main language
4261 print '<tr><td class="tdtop fieldrequired">';
4262 $htmltext = '';
4263 print $form->textwithpicto($langs->trans('MainLanguage'), $htmltext, 1, 'help', '', 0, 2, 'WEBSITE_LANG');
4264 print '</td><td>';
4265 print img_picto('', 'language', 'class="pictofixedwidth"');
4266 print $formadmin->select_language((GETPOSTISSET('WEBSITE_LANG') ? GETPOST('WEBSITE_LANG', 'aZ09comma') : ($object->lang ? $object->lang : '0')), 'WEBSITE_LANG', 0, array(), 1, 0, 0, 'minwidth300', 2, 0, 0, array(), 1);
4267 print '</td>';
4268 print '</tr>';
4269
4270 // Other languages
4271 print '<tr><td class="tdtop">';
4272 $htmltext = $langs->trans("Example").': fr,de,sv,it,pt';
4273 print $form->textwithpicto($langs->trans('OtherLanguages'), $htmltext, 1, 'help', '', 0, 2);
4274 print '</td><td>';
4275 print img_picto('', 'language', 'class="pictofixedwidth"');
4276 print '<input type="text" class="flat maxwidth200" value="'.(GETPOSTISSET('WEBSITE_OTHERLANG') ? GETPOST('WEBSITE_OTHERLANG', 'alpha') : $object->otherlang).'" name="WEBSITE_OTHERLANG">';
4277 print '</td>';
4278 print '</tr>';
4279
4280 // VirtualHost
4281 print '<tr><td class="tdtop">';
4282
4283 $htmltext = $langs->trans("VirtualhostDesc");
4284 print $form->textwithpicto($langs->trans('Virtualhost'), $htmltext, 1, 'help', '', 0, 2, 'virtualhosttooltip');
4285 print '</td><td>';
4286 print '<input type="text" class="flat minwidth300" value="'.(GETPOSTISSET('virtualhost') ? GETPOST('virtualhost', 'alpha') : $virtualurl).'" name="virtualhost">';
4287 print '</td>';
4288 print '</tr>';
4289
4290 // Favicon
4291 print '<tr><td>';
4292 print $form->textwithpicto($langs->trans('ImportFavicon'), $langs->trans('FaviconTooltip'));
4293 print '</td><td>';
4294 $maxfilesizearray = getMaxFileSizeArray();
4295 $maxmin = $maxfilesizearray['maxmin'];
4296 if ($maxmin > 0) {
4297 print '<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
4298 }
4299 print '<input type="file" class="flat minwidth300" name="addedfile" id="addedfile"/>';
4300
4301 $uploadfolder = $conf->website->dir_output.'/'.$websitekey;
4302 if (dol_is_file($uploadfolder.'/favicon.png')) {
4303 print '<div class="inline-block valignmiddle marginrightonly">';
4304 print '<img style="max-height: 80px" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=website&file='.$websitekey.'/favicon.png">';
4305 print '</div>';
4306 }
4307 print '</tr></td>';
4308
4309 // CSS file
4310 print '<tr><td class="tdtop">';
4311 $htmlhelp = $langs->trans("CSSContentTooltipHelp");
4312 print $form->textwithpicto($langs->trans('WEBSITE_CSS_INLINE'), $htmlhelp, 1, 'help', '', 0, 2, 'csstooltip');
4313 print '</td><td>';
4314
4315 $poscursor = array('x' => GETPOST('WEBSITE_CSS_INLINE_x'), 'y' => GETPOST('WEBSITE_CSS_INLINE_y'));
4316 $doleditor = new DolEditor('WEBSITE_CSS_INLINE', $csscontent, '', 220, 'ace', 'In', true, false, 'ace', 0, '100%', 0, $poscursor);
4317 print $doleditor->Create(1, '', true, 'CSS', 'css');
4318
4319 print '</td></tr>';
4320
4321 // JS file
4322 print '<tr><td class="tdtop">';
4323 $textwithhelp = $langs->trans('WEBSITE_JS_INLINE');
4324 $htmlhelp2 = $langs->trans("LinkAndScriptsHereAreNotLoadedInEditor").'<br>';
4325 print $form->textwithpicto($textwithhelp, $htmlhelp2, 1, 'warning', '', 0, 2, 'htmljstooltip2');
4326
4327 print '</td><td>';
4328
4329 $poscursor = array('x' => GETPOST('WEBSITE_JS_INLINE_x'), 'y' => GETPOST('WEBSITE_JS_INLINE_y'));
4330 $doleditor = new DolEditor('WEBSITE_JS_INLINE', $jscontent, '', 220, 'ace', 'In', true, false, 'ace', 0, '100%', 0, $poscursor);
4331 print $doleditor->Create(1, '', true, 'JS', 'javascript');
4332
4333 print '</td></tr>';
4334
4335 // Common HTML header
4336 print '<tr><td class="tdtop">';
4337 print $langs->trans('WEBSITE_HTML_HEADER');
4338 $htmlhelp = $langs->trans("Example").' :<br>';
4339 $htmlhelp .= dol_nl2br(dol_htmlentities($htmlheadercontentdefault)); // do not use dol_htmlentitiesbr here, $htmlheadercontentdefault is HTML with content like <link> and <script> that we want to be html encode as they must be show as doc content not executable instruction.
4340 $textwithhelp = $form->textwithpicto('', $htmlhelp, 1, 'help', '', 0, 2, 'htmlheadertooltip');
4341 $htmlhelp2 = $langs->trans("LinkAndScriptsHereAreNotLoadedInEditor").'<br>';
4342 print $form->textwithpicto($textwithhelp, $htmlhelp2, 1, 'warning', '', 0, 2, 'htmlheadertooltip2');
4343 print '</td><td>';
4344
4345 $poscursor = array('x' => GETPOST('WEBSITE_HTML_HEADER_x'), 'y' => GETPOST('WEBSITE_HTML_HEADER_y'));
4346 $doleditor = new DolEditor('WEBSITE_HTML_HEADER', $htmlheadercontent, '', 220, 'ace', 'In', true, false, 'ace', 0, '100%', 0, $poscursor);
4347 print $doleditor->Create(1, '', true, 'HTML Header', 'html');
4348
4349 print '</td></tr>';
4350
4351 // Robot file
4352 print '<tr><td class="tdtop">';
4353 print $langs->trans('WEBSITE_ROBOT');
4354 print '</td><td>';
4355
4356 $poscursor = array('x' => GETPOST('WEBSITE_ROBOT_x'), 'y' => GETPOST('WEBSITE_ROBOT_y'));
4357 $doleditor = new DolEditor('WEBSITE_ROBOT', $robotcontent, '', 220, 'ace', 'In', true, false, 'ace', 0, '100%', 0, $poscursor);
4358 print $doleditor->Create(1, '', true, 'Robot file', 'text');
4359
4360 print '</td></tr>';
4361
4362 // .htaccess
4363 print '<tr><td class="tdtop">';
4364
4365 $textwithhelp3 = $langs->trans("Example").' :';
4366 $textwithhelp3 .= "<br># Order allow,deny\n";
4367 $textwithhelp3 .= "<br># Deny from all\n";
4368 $textwithhelp3 .= "<br># Require all granted\n";
4369
4370 print $form->textwithpicto($langs->trans('WEBSITE_HTACCESS'), $textwithhelp3, 1, 'help', '', 0, 2, 'htmlheadertooltip3');
4371 print '</td><td>';
4372
4373 $poscursor = array('x' => GETPOST('WEBSITE_HTACCESS_x'), 'y' => GETPOST('WEBSITE_HTACCESS_y'));
4374 $doleditor = new DolEditor('WEBSITE_HTACCESS', $htaccesscontent, '', 220, 'ace', 'In', true, false, 'ace', 0, '100%', 0, $poscursor);
4375 print $doleditor->Create(1, '', true, $langs->trans("File").' .htaccess', 'text');
4376
4377 print '</td></tr>';
4378
4379 // Manifest.json
4380 print '<tr><td class="tdtop">';
4381 $htmlhelp = $langs->trans("Example").' :<br>';
4382 $htmlhelp .= '<small>'.dol_htmlentitiesbr($manifestjsoncontentdefault).'</small>';
4383 print $form->textwithpicto($langs->trans('WEBSITE_MANIFEST_JSON'), $htmlhelp, 1, 'help', '', 0, 2, 'manifestjsontooltip');
4384 print '</td><td>';
4385 print $langs->trans("UseManifest").': '.$form->selectyesno('use_manifest', $website->use_manifest, 1).'<br>';
4386
4387 $poscursor = array('x' => GETPOST('WEBSITE_MANIFEST_JSON_x'), 'y' => GETPOST('WEBSITE_MANIFEST_JSON_y'));
4388 $doleditor = new DolEditor('WEBSITE_MANIFEST_JSON', $manifestjsoncontent, '', 220, 'ace', 'In', true, false, 'ace', 0, '100%', 0, $poscursor);
4389 print $doleditor->Create(1, '', true, $langs->trans("File").' manifest.json', 'text');
4390 print '</td></tr>';
4391
4392 // README.md
4393 print '<tr><td class="tdtop">';
4394 $htmlhelp = $langs->trans("EnterHereReadmeInformation");
4395 print $form->textwithpicto($langs->trans("File").' README.md', $htmlhelp, 1, 'help', '', 0, 2, 'readmetooltip');
4396 print '</td><td>';
4397
4398 $poscursor = array('x' => GETPOST('WEBSITE_README_x'), 'y' => GETPOST('WEBSITE_README_y'));
4399 $doleditor = new DolEditor('WEBSITE_README', $readmecontent, '', 220, 'ace', 'In', true, false, 'ace', 0, '100%', 0, $poscursor);
4400 print $doleditor->Create(1, '', true, $langs->trans("File").' README.md', 'text');
4401
4402 print '</td></tr>';
4403
4404 // LICENSE
4405 print '<tr><td class="tdtop">';
4406 $htmlhelp = $langs->trans("EnterHereLicenseInformation");
4407 print $form->textwithpicto($langs->trans("File").' LICENSE', $htmlhelp, 1, 'help', '', 0, 2, 'licensetooltip');
4408 print '</td><td>';
4409
4410 $poscursor = array('x' => GETPOST('WEBSITE_LICENSE_x'), 'y' => GETPOST('WEBSITE_LICENSE_y'));
4411 $doleditor = new DolEditor('WEBSITE_LICENSE', $licensecontent, '', 220, 'ace', 'In', true, false, 'ace', 0, '100%', 0, $poscursor);
4412 print $doleditor->Create(1, '', true, $langs->trans("File").' LICENSE', 'text');
4413
4414 print '</td></tr>';
4415
4416 // RSS
4417 print '<tr><td class="tdtop">';
4418 $htmlhelp = $langs->trans('RSSFeedDesc');
4419 print $form->textwithpicto($langs->trans('RSSFeed'), $htmlhelp, 1, 'help', '', 0, 2, '');
4420 print '</td><td>';
4421 print '/wrapper.php?rss=1[&l=XX][&limit=99][&cachedelay=99]';
4422 print '</td></tr>';
4423
4424 print '</table>';
4425
4426 print dol_get_fiche_end();
4427
4428 print '</div>';
4429
4430 print '<br>';
4431}
4432
4433if ($action == 'editsecurity') {
4434 $selectarrayCSPDirectives = websiteGetContentPolicyDirectives();
4435 $selectarrayCSPSources = websiteGetContentPolicySources();
4436 $forceCSPArr = websiteGetContentPolicyToArray($forceCSP);
4437 print '<div class="fiche">';
4438 print '<br>';
4439
4440 $head = websiteconfigPrepareHead($object);
4441 print dol_get_fiche_head($head, 'security', $langs->trans("General"), -1, 'website');
4442
4443 print '<span class="opacitymedium">'.$langs->trans("HTTPHeaderEditor").'. '.$langs->trans("ReservedToAdvancedUsers").'.</span><br><br>';
4444
4445 print '<div class="div-table-responsive-no-min">';
4446 print '<table class="noborder centpercent">';
4447 print '<tr class="liste_titre">';
4448 print '<td>'.$langs->trans("HTTPHeader").'</td>';
4449 print '<td></td>'."\n";
4450 print '</tr>';
4451
4452 // Force RP
4453 print '<tr class="oddeven">';
4454 print '<td>'.$form->textwithpicto($langs->trans('WebsiteSecurityForceRP'), 'HTTP Header Referer-Policy<br><br>'.$langs->trans("Recommended").':<br>strict-origin-when-cross-origin <span class="opacitymedium">'.$langs->trans("or").'</span> same-origin"=more secured', 1, 'help', 'valignmiddle', 0, 3, 'WEBSITE_'.$object->id.'_SECURITY_FORCERP').'</td>';
4455 print '<td><input class="minwidth500" name="WEBSITE_'.$object->id.'_SECURITY_FORCERP" id="WEBSITE_'.$object->id.'_SECURITY_FORCERP" value="'.getDolGlobalString("WEBSITE_".$object->id."_SECURITY_FORCERP").'"></td>';
4456 print '</tr>';
4457 // Force STS
4458 print '<tr class="oddeven">';
4459 print '<td>'.$form->textwithpicto($langs->trans('WebsiteSecurityForceSTS'), 'HTTP Header Strict-Transport-Security<br><br>'.$langs->trans("Example").':<br>max-age=31536000; includeSubDomains', 1, 'help', 'valignmiddle', 0, 3, 'WEBSITE_'.$object->id.'_SECURITY_FORCESTS').'</td>';
4460 print '<td><input class="minwidth500" name="WEBSITE_'.$object->id.'_SECURITY_FORCESTS" id="WEBSITE_'.$object->id.'_SECURITY_FORCESTS" value="'.getDolGlobalString("WEBSITE_".$object->id."_SECURITY_FORCESTS").'"></td>';
4461 print '</tr>';
4462 // Force PP
4463 print '<tr class="oddeven">';
4464 print '<td>'.$form->textwithpicto($langs->trans('WebsiteSecurityForcePP'), 'HTTP Header Permissions-Policy<br><br>'.$langs->trans("Example").':<br>camera=*, microphone=(), geolocation=*', 1, 'help', 'valignmiddle', 0, 3, 'WEBSITE_'.$object->id.'_SECURITY_FORCEPP').'</td>';
4465 print '<td><input class="minwidth500" name="WEBSITE_'.$object->id.'_SECURITY_FORCEPP" id="WEBSITE_'.$object->id.'_SECURITY_FORCEPP" value="'.getDolGlobalString("WEBSITE_".$object->id."_SECURITY_FORCEPP").'"></td>';
4466 print '</tr>';
4467
4468 $examplecsprule = "frame-ancestors 'self'; img-src * data:; font-src *; default-src 'self' 'unsafe-inline' 'unsafe-eval' *.paypal.com *.stripe.com *.google.com *.googleapis.com *.google-analytics.com *.googletagmanager.com;";
4469
4470 // Force CSP - Content Security Policy
4471 print '<tr class="oddeven nohover">';
4472 print '<td class="tdtop">'.$form->textwithpicto($langs->trans('ContentSecurityPolicy'), 'HTTP Header Content-Security-Policy<br><br>'.$langs->trans("Example").":<br>".$examplecsprule, 1, 'help', 'valignmiddle', 0, 3, 'WEBSITE_'.$object->id.'_SECURITY_FORCECSP').'</td>';
4473 print '<td>';
4474
4475 print '<div class="div-table-responsive-no-min">';
4476
4477 print '<input class="minwidth500 quatrevingtpercent" name="WEBSITE_'.$object->id.'_SECURITY_FORCECSP" id="WEBSITE_'.$object->id.'_SECURITY_FORCECSP" value="'.$forceCSP.'"> <a href="#" id="btnaddcontentsecuritypolicy">'.img_picto('', 'add').'</a><br>';
4478
4479 print '<br class="selectaddcontentsecuritypolicy hidden">';
4480
4481 print '<div id="selectaddcontentsecuritypolicy" class="hidden selectaddcontentsecuritypolicy">';
4482 print $form->selectarray("select_identifier_WEBSITE_SECURITY_FORCECSP", $selectarrayCSPDirectives, "select_identifier_WEBSITE_SECURITY_FORCECSP", $langs->trans("FillCSPDirective"), 0, 0, '', 0, 0, 0, '', 'minwidth200 maxwidth350 inline-block');
4483 print ' ';
4484 print '<input type="hidden" id="select_source_WEBSITE_SECURITY_FORCECSP" name="select_source_WEBSITE_SECURITY_FORCECSP">';
4485 foreach ($selectarrayCSPSources as $key => $values) {
4486 print '<div class="div_WEBSITE_SECURITY_FORCECSP hidden inline-block maxwidth350" id="div_'.$key.'_WEBSITE_SECURITY_FORCECSP">';
4487 print $form->selectarray("select_".$key."_WEBSITE_SECURITY_FORCECSP", $values, "select_".$key."_WEBSITE_SECURITY_FORCECSP", $langs->trans("FillCSPSource"), 0, 0, '', 0, 0, 0, '', 'minwidth200 maxwidth300 inline-block select_WEBSITE_SECURITY_FORCECSP');
4488 print '</div>';
4489 }
4490 print ' ';
4491 print '<div class="div_input_data_WEBSITE_SECURITY_FORCECSP hidden inline-block maxwidth200"><input id="input_data_WEBSITE_SECURITY_FORCECSP" name="input_data_WEBSITE_SECURITY_FORCECSP"></div>';
4492 print ' ';
4493 print '<div class="div_btn_class_WEBSITE_SECURITY_FORCECSP inline-block maxwidth200"><input type="submit" id="btn_WEBSITE_SECURITY_FORCECSP" name="btn_WEBSITE_SECURITY_FORCECSP" class="butAction small smallpaddingimp" value="'.$langs->trans("Add").'" disabled></div>';
4494 print '<br><br>';
4495 print '</div>';
4496
4497 if (!empty($forceCSP)) {
4498 // Content Security Policy list of selected rules
4499 print '<br>';
4500 print '<div class="div-table-responsive-no-min">';
4501 print img_picto('', 'graph', 'class="pictofixedwidth"').$langs->trans("HierarchicView").'<br>';
4502 print '<ul>';
4503 foreach ($forceCSPArr as $directive => $sources) {
4504 print '<li>';
4505 if (in_array($directive, array_keys($selectarrayCSPDirectives))) {
4506 print '<span>'.$directive.'</span>';
4507 } else {
4508 print $form->textwithpicto($directive, $langs->trans("UnknowContentSecurityPolicyDirective"), 1, 'warning');
4509 }
4510 if (!empty($sources)) {
4511 print '<ul>';
4512 foreach ($sources as $key => $source) {
4513 print '<li><span>'.$source.'</span>&nbsp;<a href="'.$_SERVER["PHP_SELF"].'?websiteid='.$websiteid.'&action=removecspsource&sourcecsp='.$directive.'_'.$key.'&token='.newToken().'">'.img_delete().'</a></li>';
4514 }
4515 print '</ul>';
4516 } else {
4517 print '&nbsp;<a href="'.$_SERVER["PHP_SELF"].'?websiteid='.$websiteid.'&action=removecspsource&sourcecsp='.$directive.'&token='.newToken().'">'.img_delete().'</a>';
4518 }
4519 print '</li>';
4520 }
4521 print '</ul>';
4522 print '</div>';
4523 }
4524 print '</div>';
4525
4526 print '</td>';
4527 print '</tr>';
4528
4529 // Force CSPRO
4530 if (getDolGlobalString("WEBSITE_".$object->id."_SECURITY_FORCECSPRO")) {
4531 print '<tr class="oddeven">';
4532 print '<td>'.$form->textwithpicto($langs->trans('WebsiteSecurityForceCSPRO'), 'HTTP Header Content-Security-Policy-Report-Only<br><br>'.$langs->trans("Example").":<br>".$examplecsprule, 1, 'help', 'valignmiddle', 0, 3, 'WEBSITE_'.$object->id.'_SECURITY_FORCECSPRO').'</td>';
4533 print '<td><input class="minwidth500" name="WEBSITE_'.$object->id.'_SECURITY_FORCECSPRO" id="WEBSITE_'.$object->id.'_SECURITY_FORCECSPRO" value="'.getDolGlobalString("WEBSITE_".$object->id."_SECURITY_FORCECSPRO").'"></td>';
4534 print '</tr>';
4535 }
4536
4537 print '</table>';
4538 print '</div>';
4539
4540
4541 print '<div class="center">';
4542
4543 print '<input type="submit" class="button small" name="updateandstay" value="'.$langs->trans("Save").'">';
4544 print '<input class="button button-cancel small" type="submit" name="preview" value="'.$langs->trans("Cancel").'">';
4545
4546 print '</div>';
4547
4548
4549 print '<script>
4550 $(document).ready(function() {
4551 $("#btnaddcontentsecuritypolicy").on("click", function(){
4552 if($("#selectaddcontentsecuritypolicy").is(":visible")){
4553 console.log("We hide select to add Content Security Policy");
4554 $(".selectaddcontentsecuritypolicy").hide();
4555 } else {
4556 console.log("We show select to add Content Security Policy");
4557 $(".selectaddcontentsecuritypolicy").show();
4558 }
4559 });
4560
4561 $("#select_identifier_WEBSITE_SECURITY_FORCECSP").on("change", function() {
4562 key = $(this).find(":selected").data("directivetype");
4563 console.log("We hide all select div");
4564 $(".div_WEBSITE_SECURITY_FORCECSP").hide();
4565 $(".select_WEBSITE_SECURITY_FORCECSP").val(null).trigger("change");
4566 $(".div_input_data_WEBSITE_SECURITY_FORCECSP").hide();
4567 $("#btn_WEBSITE_SECURITY_FORCECSP").prop("disabled",true);
4568 if (key == "none"){
4569 $("#btn_WEBSITE_SECURITY_FORCECSP").prop("disabled",false);
4570 } else {
4571 console.log("We show div select with key "+key);
4572 $("#div_"+key+"_WEBSITE_SECURITY_FORCECSP").css("display", "inline-block");
4573 }
4574 });
4575
4576 $(".select_WEBSITE_SECURITY_FORCECSP").on("change", function() {
4577 keysource = $(this).find(":selected").data("sourcetype");
4578 $("#select_source_WEBSITE_SECURITY_FORCECSP").val($(this).val());
4579 console.log("We hide and show fields");
4580 if (keysource == "data" || keysource == "input") {
4581 $(".div_input_data_WEBSITE_SECURITY_FORCECSP").css("display", "inline-block");
4582 $("#btn_WEBSITE_SECURITY_FORCECSP").prop("disabled",true);
4583 } else {
4584 $("#input_data_WEBSITE_SECURITY_FORCECSP").val("");
4585 $(".div_input_data_WEBSITE_SECURITY_FORCECSP").hide();
4586 if (keysource != undefined) {
4587 $("#btn_WEBSITE_SECURITY_FORCECSP").prop("disabled",false);
4588 } else {
4589 $("#btn_WEBSITE_SECURITY_FORCECSP").prop("disabled",true);
4590 }
4591 }
4592 });
4593
4594 $("#input_data_WEBSITE_SECURITY_FORCECSP").on("change keyup", function(){
4595 if ($(this).val() != "") {
4596 console.log("We show add button");
4597 $("#btn_WEBSITE_SECURITY_FORCECSP").prop("disabled",false);
4598 } else {
4599 console.log("We hide add button");
4600 $("#btn_WEBSITE_SECURITY_FORCECSP").prop("disabled",true);
4601 }
4602 });
4603 });
4604 </script>';
4605
4606 print dol_get_fiche_end();
4607 print '</div>';
4608}
4609
4610
4611if ($action == 'createsite') {
4612 print '<div class="fiche">';
4613
4614 print '<br>';
4615
4616 /*$h = 0;
4617 $head = array();
4618
4619 $head[$h][0] = dol_buildpath('/website/index.php',1).'?id='.$object->id;
4620 $head[$h][1] = $langs->trans("AddWebsite");
4621 $head[$h][2] = 'card';
4622 $h++;
4623
4624 print dol_get_fiche_head($head, 'card', '', -1, 'website');
4625 */
4626 if ($action == 'createcontainer') {
4627 print load_fiche_titre($langs->trans("AddWebsite"));
4628 }
4629
4630 print '<!-- Add site -->'."\n";
4631 print '<div class="tabBar tabBarWithBottom">';
4632
4633 print '<table class="border centpercent">';
4634
4635 $siteref = $sitedesc = $sitelang = $siteotherlang = '';
4636 if (GETPOST('WEBSITE_REF')) {
4637 $siteref = GETPOST('WEBSITE_REF', 'aZ09');
4638 }
4639 if (GETPOST('WEBSITE_DESCRIPTION')) {
4640 $sitedesc = GETPOST('WEBSITE_DESCRIPTION', 'alpha');
4641 }
4642 if (GETPOST('WEBSITE_LANG')) {
4643 $sitelang = GETPOST('WEBSITE_LANG', 'aZ09');
4644 }
4645 if (GETPOST('WEBSITE_OTHERLANG')) {
4646 $siteotherlang = GETPOST('WEBSITE_OTHERLANG', 'aZ09comma');
4647 }
4648
4649 print '<tr><td class="titlefieldcreate fieldrequired">';
4650 print $form->textwithpicto($langs->trans('WebsiteName'), $langs->trans("Example").': MyPortal, www.mywebsite.com, ...');
4651 print '</td><td>';
4652 print '<input type="text" class="flat maxwidth300" name="WEBSITE_REF" value="'.dol_escape_htmltag($siteref).'" autofocus>';
4653 print '</td></tr>';
4654
4655 print '<tr><td class="fieldrequired">';
4656 print $langs->trans('MainLanguage');
4657 print '</td><td>';
4658 $shortlangcode = preg_replace('/[_-].*$/', '', trim($langs->defaultlang));
4659 print img_picto('', 'language', 'class="pictofixedwidth"');
4660 print $formadmin->select_language((GETPOSTISSET('WEBSITE_LANG') ? GETPOST('WEBSITE_LANG', 'aZ09comma') : $shortlangcode), 'WEBSITE_LANG', 0, array(), 1, 0, 0, 'minwidth300', 2, 0, 0, array(), 1);
4661 print '</td></tr>';
4662
4663 print '<tr><td>';
4664 $htmltext = $langs->trans("Example").': fr,de,sv,it,pt';
4665 print $form->textwithpicto($langs->trans('OtherLanguages'), $htmltext, 1, 'help', '', 0, 2);
4666 print '</td><td>';
4667 print img_picto('', 'language', 'class="pictofixedwidth"');
4668 print '<input type="text" class="flat minwidth300" name="WEBSITE_OTHERLANG" value="'.dol_escape_htmltag($siteotherlang).'">';
4669 print '</td></tr>';
4670
4671 print '<tr><td>';
4672 print $langs->trans('Description');
4673 print '</td><td>';
4674 print '<input type="text" class="flat minwidth500" name="WEBSITE_DESCRIPTION" value="'.dol_escape_htmltag($sitedesc).'">';
4675 print '</td></tr>';
4676
4677 print '<tr><td>';
4678
4679 $htmltext = $langs->trans("VirtualhostDesc");
4680 /*$htmltext = str_replace('{s1}', DOL_DATA_ROOT.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/<i>websiteref</i>', $htmltext);
4681 $htmltext .= '<br>';
4682 $htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), DOL_DOCUMENT_ROOT);
4683 $htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("WritePerm"), '{s1}');
4684 $htmltext = str_replace('{s1}', DOL_DATA_ROOT.'/website<br>'.DOL_DATA_ROOT.'/medias', $htmltext);*/
4685
4686
4687 print $form->textwithpicto($langs->trans('Virtualhost'), $htmltext, 1, 'help', '', 0, 2, '');
4688 print '</td><td>';
4689 print '<input type="text" class="flat minwidth300" name="virtualhost" value="'.dol_escape_htmltag(GETPOST('virtualhost', 'alpha')).'">';
4690 print '</td></tr>';
4691
4692 print '</table>';
4693 print '</div>';
4694
4695 if ($action == 'createsite') {
4696 print '<div class="center">';
4697
4698 print '<input type="submit" class="button small" name="addcontainer" value="'.$langs->trans("Create").'">';
4699 print '<input class="button button-cancel small" type="submit" name="preview" value="'.$langs->trans("Cancel").'">';
4700
4701 print '</div>';
4702 }
4703
4704
4705 //print '</div>';
4706
4707 //print dol_get_fiche_end();
4708
4709 print '</div>';
4710
4711 print '<br>';
4712}
4713
4714// Page view to import a website template
4715if ($action == 'importsite') {
4716 print '<!-- action=importsite -->';
4717 print '<div class="fiche">';
4718
4719 print '<br>';
4720
4721 print load_fiche_titre($langs->trans("ImportSite"));
4722
4723 print dol_get_fiche_head(array(), '0', '', -1);
4724
4725 print '<span class="opacitymedium">'.$langs->trans("ZipOfWebsitePackageToImport").'</span><br><br>';
4726
4727
4728 $dolibarrdataroot = preg_replace('/([\\/]+)$/i', '', DOL_DATA_ROOT);
4729 $allowimportsite = true;
4730 if (dol_is_file($dolibarrdataroot.'/installmodules.lock')) {
4731 $allowimportsite = false;
4732 }
4733
4734 if ($allowimportsite) {
4735 $maxfilesizearray = getMaxFileSizeArray();
4736 $maxmin = $maxfilesizearray['maxmin'];
4737 if ($maxmin > 0) {
4738 print '<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
4739 }
4740 print '<input class="flat minwidth400" type="file" name="userfile[]" accept=".zip">';
4741 print '<input type="submit" class="button small" name="buttonsubmitimportfile" value="'.dol_escape_htmltag($langs->trans("Upload")).'">';
4742 print '<input type="submit" class="button button-cancel small" name="preview" value="'.dol_escape_htmltag($langs->trans("Cancel")).'">';
4743 print '<br><br><br>';
4744 } else {
4745 if (getDolGlobalString('MAIN_MESSAGE_INSTALL_MODULES_DISABLED_CONTACT_US')) {
4746 // Show clean corporate message
4747 $message = $langs->trans('InstallModuleFromWebHasBeenDisabledContactUs');
4748 } else {
4749 // Show technical generic message
4750 $message = $langs->trans("InstallModuleFromWebHasBeenDisabledByFile", $dolibarrdataroot.'/installmodules.lock');
4751 }
4752 print info_admin($message).'<br><br>';
4753 }
4754
4755
4756 print '<span class="opacitymedium">'.$langs->trans("ZipOfWebsitePackageToLoad").'</span><br><br>';
4757
4758 // This will scan the dir /doctemplates/websites and show all templates.
4759 showWebsiteTemplates($website, GETPOSTINT('importsite') == 2 ? 1 : 0);
4760
4761 print dol_get_fiche_end();
4762
4763 print '</div>';
4764
4765 print '<br>';
4766}
4767
4768if ($action == 'editmeta' || $action == 'createcontainer') { // Edit properties of a web site OR properties of a web page
4769 print '<div class="fiche">';
4770
4771 print '<br>';
4772
4773 /*$h = 0;
4774 $head = array();
4775
4776 $head[$h][0] = dol_buildpath('/website/index.php',1).'?id='.$object->id;
4777 $head[$h][1] = $langs->trans("AddPage");
4778 $head[$h][2] = 'card';
4779 $h++;
4780
4781 print dol_get_fiche_head($head, 'card', '', -1, 'website');
4782 */
4783 if ($action == 'createcontainer') {
4784 print load_fiche_titre($langs->trans("AddPage"));
4785 }
4786
4787 print '<!-- Edit or create page/container -->'."\n";
4788 //print '<div class="fichecenter">';
4789
4790 $hiddenfromfetchingafterload = ' hideobject';
4791 $hiddenmanuallyafterload = ' hideobject';
4792 if (GETPOST('radiocreatefrom') == 'checkboxcreatefromfetching') {
4793 $hiddenfromfetchingafterload = '';
4794 }
4795 if (GETPOST('radiocreatefrom') == 'checkboxcreatemanually') {
4796 $hiddenmanuallyafterload = '';
4797 }
4798
4799 if ($action == 'editmeta' || empty($conf->use_javascript_ajax)) { // No autohide/show in such case
4800 $hiddenfromfetchingafterload = '';
4801 $hiddenmanuallyafterload = '';
4802 }
4803
4804 if ($action == 'createcontainer') {
4805 print '<br>';
4806
4807 if (!empty($conf->use_javascript_ajax)) {
4808 print '<input type="radio" name="radiocreatefrom" id="checkboxcreatemanually" value="checkboxcreatemanually"'.(GETPOST('radiocreatefrom') == 'checkboxcreatemanually' ? ' checked' : '').'> ';
4809 }
4810 print '<label for="checkboxcreatemanually"><span class="opacitymediumxx">'.$langs->trans("OrEnterPageInfoManually").'</span></label><br>';
4811 print '<hr class="tablecheckboxcreatemanually'.$hiddenmanuallyafterload.'">';
4812 }
4813
4814
4815
4816 print '<table class="border tableforfield nobackground centpercent tablecheckboxcreatemanually'.$hiddenmanuallyafterload.'">';
4817
4818 if ($action != 'createcontainer') {
4819 print '<tr><td class="titlefield fieldrequired">';
4820 print $langs->trans('IDOfPage').' - '.$langs->trans('InternalURLOfPage');
4821 print '</td><td>';
4822 print $pageid;
4823 //print '</td></tr>';
4824
4825 //print '<tr><td class="titlefield fieldrequired">';
4826 //print $langs->trans('InternalURLOfPage');
4827 //print '</td><td>';
4828 print ' &nbsp; - &nbsp; ';
4829 print '/public/website/index.php?website='.urlencode((string) $websitekey).'&pageid='.urlencode((string) $pageid);
4830 //if ($objectpage->grabbed_from) print ' - <span class="opacitymedium">'.$langs->trans('InitiallyGrabbedFrom').' '.$objectpage->grabbed_from.'</span>';
4831 print '</td></tr>';
4832
4833 $type_container = $objectpage->type_container;
4834 $pageurl = $objectpage->pageurl;
4835 $pagealiasalt = $objectpage->aliasalt;
4836 $pagetitle = $objectpage->title;
4837 $pagedescription = $objectpage->description;
4838 $pageimage = $objectpage->image;
4839 $pagekeywords = $objectpage->keywords;
4840 $pagelang = $objectpage->lang;
4841 $pageallowedinframes = $objectpage->allowed_in_frames;
4842 $pagehtmlheader = $objectpage->htmlheader;
4843 $pagedatecreation = (string) $objectpage->date_creation;
4844 $pagedatemodification = $objectpage->date_modification;
4845 $pageauthorid = $objectpage->fk_user_creat;
4846 $pageusermodifid = $objectpage->fk_user_modif;
4847 $pageauthoralias = $objectpage->author_alias;
4848 $pagestatus = $objectpage->status;
4849 $pagekeephistory = (strlen((string) $objectpage->keep_history) ? $objectpage->keep_history : 5);
4850 } else { // $action = 'createcontainer'
4851 $type_container = 'page';
4852 $pageurl = '';
4853 $pagealiasalt = '';
4854 $pagetitle = '';
4855 $pagedescription = '';
4856 $pageimage = '';
4857 $pagekeywords = '';
4858 $pagelang = '';
4859 $pageallowedinframes = 0;
4860 $pagehtmlheader = '';
4861 $pagedatecreation = dol_now();
4862 $pagedatemodification = '';
4863 $pageauthorid = $user->id;
4864 $pageusermodifid = 0;
4865 $pageauthoralias = '';
4866 $pagestatus = 1;
4867 $pagekeephistory = 5;
4868 }
4869 if (GETPOST('WEBSITE_TITLE', 'alpha')) {
4870 $pagetitle = str_replace(array('<', '>'), '', GETPOST('WEBSITE_TITLE', 'alphanohtml'));
4871 }
4872 if (GETPOST('WEBSITE_PAGENAME', 'alpha')) {
4873 $pageurl = GETPOST('WEBSITE_PAGENAME', 'alpha');
4874 }
4875 if (GETPOST('WEBSITE_ALIASALT', 'alpha')) {
4876 $pagealiasalt = str_replace(array('<', '>'), '', GETPOST('WEBSITE_ALIASALT', 'alphanohtml'));
4877 }
4878 if (GETPOST('WEBSITE_DESCRIPTION', 'alpha')) {
4879 $pagedescription = str_replace(array('<', '>'), '', GETPOST('WEBSITE_DESCRIPTION', 'alphanohtml'));
4880 }
4881 if (GETPOST('WEBSITE_IMAGE', 'alpha')) {
4882 $pageimage = GETPOST('WEBSITE_IMAGE', 'alpha');
4883 }
4884 if (GETPOST('WEBSITE_KEYWORDS', 'alpha')) {
4885 $pagekeywords = str_replace(array('<', '>'), '', GETPOST('WEBSITE_KEYWORDS', 'alphanohtml'));
4886 }
4887 if (GETPOST('WEBSITE_LANG', 'aZ09')) {
4888 $pagelang = GETPOST('WEBSITE_LANG', 'aZ09');
4889 }
4890 if (GETPOST('WEBSITE_ALLOWED_IN_FRAMES', 'aZ09')) {
4891 $pageallowedinframes = 1;
4892 }
4893 if (GETPOSTISSET('WEBSITE_KEEP_HISTORY')) {
4894 $pagekeephistory = GETPOSTINT('WEBSITE_KEEP_HISTORY');
4895 }
4896 if (GETPOST('htmlheader', 'restricthtmlallowlinkscript')) { // Must accept tags like '<script>' and '<link>'
4897 $pagehtmlheader = GETPOST('htmlheader', 'restricthtmlallowlinkscript');
4898 }
4899
4900 if ($action != 'createcontainer') {
4901 if (empty($conf->use_javascript_ajax)) {
4902 print '<!-- Status of web site page -->'."\n";
4903 print '<tr><td class="fieldrequired">';
4904 print $langs->trans('Status');
4905 print '</td><td>';
4906 print $form->selectyesno('status', $objectpage->status);
4907 print '</td></tr>';
4908 }
4909 }
4910
4911 // Type of container
4912 print '<tr><td class="titlefield fieldrequired">';
4913 print $langs->trans('WEBSITE_TYPE_CONTAINER');
4914 print '</td><td>';
4915 print img_picto('', 'object_technic', 'class="paddingrightonly"').' ';
4916 print $formwebsite->selectTypeOfContainer('WEBSITE_TYPE_CONTAINER', (GETPOST('WEBSITE_TYPE_CONTAINER', 'alpha') ? GETPOST('WEBSITE_TYPE_CONTAINER', 'alpha') : $type_container), 0, '', 1, 'minwidth300');
4917 print '</td></tr>';
4918
4919 print '<script type="text/javascript">
4920 jQuery(document).ready(function() {
4921 jQuery("#selectWEBSITE_TYPE_CONTAINER").change(function() {
4922 console.log("We change type of page : "+jQuery("#selectWEBSITE_TYPE_CONTAINER").val());
4923 if (jQuery("#selectWEBSITE_TYPE_CONTAINER").val() == \'blogpost\') {
4924 jQuery(".trpublicauthor").show();
4925 } else {
4926 jQuery(".trpublicauthor").hide();
4927 }
4928 if (jQuery("#selectWEBSITE_TYPE_CONTAINER").val() == \'service\' || jQuery("#selectWEBSITE_TYPE_CONTAINER").val() == \'library\') {
4929 $(".spanprefix").html("_" + $("#selectWEBSITE_TYPE_CONTAINER").val() + "_");
4930 jQuery(".spanprefix").show();
4931 } else {
4932 jQuery(".spanprefix").hide();
4933 }
4934 });
4935
4936 // Force at init execution a first time of the handler change
4937 jQuery("#selectWEBSITE_TYPE_CONTAINER").trigger(\'change\');
4938 });
4939 </script>
4940 ';
4941
4942 // Title
4943 print '<tr><td class="fieldrequired">';
4944 print $langs->trans('WEBSITE_TITLE');
4945 print '</td><td>';
4946 print '<input type="text" class="flat quatrevingtpercent" name="WEBSITE_TITLE" id="WEBSITE_TITLE" value="'.dol_escape_htmltag($pagetitle).'" autofocus>';
4947 print '</td></tr>';
4948
4949 // Alias page
4950 print '<tr><td class="titlefieldcreate fieldrequired">';
4951 print $langs->trans('WEBSITE_PAGENAME');
4952 print '</td><td>';
4953 print '<span class="opacitymedium spanprefix hidden"></span> ';
4954 print '<input type="text" class="flat minwidth300" name="WEBSITE_PAGENAME" id="WEBSITE_PAGENAME" value="'.dol_escape_htmltag((string) preg_replace('/^_[a-z]+_/', '', (string) $pageurl)).'">';
4955 print '</td></tr>';
4956
4957 print '<script type="text/javascript">
4958 $(document).ready(function() {
4959 console.log("Manage prefix for service or library");
4960 if ($("#selectWEBSITE_TYPE_CONTAINER").val() == "service" || $("#selectWEBSITE_TYPE_CONTAINER").val() == "library") {
4961 $(".spanprefix").html("_" + $("#selectWEBSITE_TYPE_CONTAINER").val() + "_");
4962 $(".spanprefix").show();
4963 }
4964 $(".websiteformtoolbar").on("submit", function(event) {
4965 if ($("#selectWEBSITE_TYPE_CONTAINER").val() == "service" || $("#selectWEBSITE_TYPE_CONTAINER").val() == "library") {
4966 var prefix = "_" + $("#selectWEBSITE_TYPE_CONTAINER").val() + "_";
4967 var userInput = $("#WEBSITE_PAGENAME").val();
4968 var $inputField = $("#WEBSITE_PAGENAME");
4969 if (userInput.indexOf(prefix) !== 0) {
4970 $inputField.val(prefix + userInput);
4971 }
4972 }
4973 });
4974 });
4975 </script>
4976 ';
4977
4978 print '<tr><td class="titlefieldcreate">';
4979 $htmlhelp = $langs->trans("WEBSITE_ALIASALTDesc");
4980 print $form->textwithpicto($langs->trans('WEBSITE_ALIASALT'), $htmlhelp, 1, 'help', '', 0, 2, 'aliastooltip');
4981 print '</td><td>';
4982 print '<input type="text" class="flat minwidth500" name="WEBSITE_ALIASALT" value="'.dol_escape_htmltag($pagealiasalt).'">';
4983 print '</td></tr>';
4984
4985 print '<tr><td>';
4986 print $langs->trans('WEBSITE_DESCRIPTION');
4987 print '</td><td>';
4988 print '<input type="text" class="flat quatrevingtpercent" name="WEBSITE_DESCRIPTION" value="'.dol_escape_htmltag($pagedescription).'">';
4989 print '</td></tr>';
4990
4991 // Deprecated. Image for RSS or Thumbs are now taken from the content.
4992 if (getDolGlobalInt('WEBSITE_MANAGE_IMAGE_FOR_PAGES')) {
4993 print '<tr class="trimageforpage hidden"><td>';
4994 $htmlhelp = $langs->trans("WEBSITE_IMAGEDesc");
4995 print $form->textwithpicto($langs->trans('WEBSITE_IMAGE'), $htmlhelp, 1, 'help', '', 0, 2, 'imagetooltip');
4996 print '</td><td>';
4997 print '<input type="text" class="flat quatrevingtpercent" name="WEBSITE_IMAGE" value="'.dol_escape_htmltag($pageimage).'">';
4998 print '</td></tr>';
4999
5000 print '<script type="text/javascript">
5001 jQuery(document).ready(function() {
5002 jQuery("#selectWEBSITE_TYPE_CONTAINER").change(function() {
5003 console.log("We change type of page : "+jQuery("#selectWEBSITE_TYPE_CONTAINER").val());
5004 if (jQuery("#selectWEBSITE_TYPE_CONTAINER").val() == \'blogpost\') {
5005 jQuery(".trimageforpage").show();
5006 } else {
5007 jQuery(".trimageforpage").hide();
5008 }
5009 });
5010 });
5011 </script>
5012 ';
5013 }
5014
5015 // Keywords
5016 print '<tr><td>';
5017 $htmlhelp = $langs->trans("WEBSITE_KEYWORDSDesc");
5018 print $form->textwithpicto($langs->trans('WEBSITE_KEYWORDS'), $htmlhelp, 1, 'help', '', 0, 2, 'keywordtooltip');
5019 print '</td><td>';
5020 print '<input type="text" class="flat quatrevingtpercent" name="WEBSITE_KEYWORDS" value="'.dol_escape_htmltag($pagekeywords).'">';
5021 print '</td></tr>';
5022
5023 print '<tr><td>';
5024 print $langs->trans('Language');
5025 print '</td><td>';
5026 $onlykeys = array();
5027 if ($object->lang) {
5028 $onlykeys[$object->lang] = $object->lang;
5029 } else {
5030 $onlykeys[$langs->defaultlang] = $langs->defaultlang;
5031 }
5032 if ($object->otherlang) {
5033 $tmparray = explode(',', $object->otherlang);
5034 foreach ($tmparray as $key) {
5035 $tmpkey = trim($key);
5036 if (strlen($key) == 2) {
5037 $tmpkey = strtolower($key);
5038 }
5039 $onlykeys[$tmpkey] = $tmpkey;
5040 }
5041 }
5042 if (empty($object->lang) && empty($object->otherlang)) {
5043 $onlykeys = array(); // We keep full list of languages
5044 }
5045 print img_picto('', 'language', 'class="pictofixedwidth"').$formadmin->select_language($pagelang ? $pagelang : '', 'WEBSITE_LANG', 0, array(), '1', 0, 0, 'minwidth200', 0, 0, 0, $onlykeys, 1);
5046 $htmltext = $langs->trans("AvailableLanguagesAreDefinedIntoWebsiteProperties");
5047 print $form->textwithpicto('', $htmltext);
5048 print '</td></tr>';
5049
5050 // Translation of
5051 $translationof = 0;
5052 $translatedby = 0;
5053 print '<!-- Translation of --><tr><td>';
5054 print $langs->trans('TranslationLinks');
5055 print '</td><td>';
5056 if ($action != 'createcontainer') {
5057 // Has translation pages
5058 $sql = "SELECT rowid, lang from ".MAIN_DB_PREFIX."website_page where fk_page = ".((int) $objectpage->id);
5059 $resql = $db->query($sql);
5060 if ($resql) {
5061 $num_rows = $db->num_rows($resql);
5062 if ($num_rows > 0) {
5063 print '<span class="opacitymedium">'.$langs->trans('ThisPageHasTranslationPages').':</span>';
5064 $i = 0;
5065 $tmppage = new WebsitePage($db);
5066 $tmpstring = '';
5067 while ($obj = $db->fetch_object($resql)) {
5068 $result = $tmppage->fetch($obj->rowid);
5069 if ($result > 0) {
5070 if ($i > 0) {
5071 $tmpstring .= '<br>';
5072 }
5073 $tmpstring .= $tmppage->getNomUrl(1).' '.picto_from_langcode($tmppage->lang).' '.$tmppage->lang;
5074 // Button unlink
5075 $tmpstring .= ' <a class="paddingleft" href="'.$_SERVER["PHP_SELF"].'?website='.urlencode($object->ref).'&pageid='.((int) $objectpage->id).'&action=deletelang&token='.newToken().'&deletelangforid='.((int) $tmppage->id).'">'.img_picto($langs->trans("Remove"), 'unlink').'</a>';
5076 $translatedby++;
5077 $i++;
5078 }
5079 }
5080 if ($i > 1) {
5081 print '<br>';
5082 } else {
5083 print ' ';
5084 }
5085 print $tmpstring;
5086 }
5087 } else {
5088 dol_print_error($db);
5089 }
5090 }
5091 if ((empty($translatedby) || ($objectpage->lang != $object->lang)) && ($action == 'editmeta' || $action == 'createcontainer' || $objectpage->fk_page > 0)) {
5092 $sourcepage = new WebsitePage($db);
5093 $result = 1;
5094 if ($objectpage->fk_page > 0) {
5095 $result = $sourcepage->fetch($objectpage->fk_page);
5096 if ($result == 0) {
5097 // not found, we can reset value to clean database
5098 // TODO
5099 }
5100 }
5101 if ($result >= 0) {
5102 if ($translatedby) {
5103 print '<br>';
5104 }
5105 $translationof = $objectpage->fk_page;
5106 print '<span class="opacitymedium">'.$langs->trans('ThisPageIsTranslationOf').'</span> ';
5107 print $sourcepage->getNomUrl(2).' '.$formwebsite->selectContainer($website, 'pageidfortranslation', ($translationof ? $translationof : -1), 1, $action, 'minwidth300', array($objectpage->id));
5108 if ($translationof > 0 && $sourcepage->lang) {
5109 print picto_from_langcode($sourcepage->lang).' '.$sourcepage->lang;
5110 // Button unlink
5111 print ' <a class="paddingleft" href="'.$_SERVER["PHP_SELF"].'?website='.urlencode($object->ref).'&pageid='.((int) $objectpage->id).'&action=deletelang&token='.newToken().'&deletelangforid='.((int) $objectpage->id).'">'.img_picto($langs->trans("Remove"), 'unlink').'</a>';
5112 }
5113 }
5114 }
5115 print '</td></tr>';
5116
5117 // Categories
5118 if (isModEnabled('category') && $user->hasRight('categorie', 'lire')) {
5119 $disabled = '';
5120 $langs->load('categories');
5121
5122 print '<tr><td class="toptd">'.$form->editfieldkey('Categories', 'categories', '', $objectpage, 0).'</td><td>';
5123 print $form->selectCategories(Categorie::TYPE_WEBSITE_PAGE, 'categories', $objectpage);
5124 //print dolButtonToOpenUrlInDialogPopup('categories', $langs->transnoentitiesnoconv("Categories"), img_picto('', 'add'), '/categories/categorie_list.php?leftmenu=website&nosearch=1&type='.urlencode(Categorie::TYPE_WEBSITE_PAGE).'&website='.urlencode($website->ref), $disabled);
5125 print "</td></tr>";
5126 }
5127
5128 if (getDolGlobalString('WEBSITE_PAGE_SHOW_INTERNAL_LINKS_TO_OBJECT')) { // TODO Replace this with link into element_element ?
5129 print '<tr><td class="titlefieldcreate">';
5130 print 'ObjectClass';
5131 print '</td><td>';
5132 print '<input type="text" class="flat minwidth300" name="WEBSITE_OBJECTCLASS" placeholder="ClassName::/path/class/ObjectClass.class.php" >';
5133 print '</td></tr>';
5134
5135 print '<tr><td class="titlefieldcreate">';
5136 print 'ObjectID';
5137 print '</td><td>';
5138 print '<input type="text" class="flat minwidth300" name="WEBSITE_OBJECTID" >';
5139 print '</td></tr>';
5140 }
5141
5142 $fuser = new User($db);
5143
5144 // Date last modification
5145 if ($action != 'createcontainer') {
5146 print '<tr><td>';
5147 print $langs->trans('DateLastModification');
5148 print '</td><td>';
5149 print dol_print_date($pagedatemodification, 'dayhour', 'tzuser');
5150 print '</td></tr>';
5151
5152 print '<tr><td>';
5153 print $langs->trans('UserModification');
5154 print '</td><td>';
5155 if ($pageusermodifid > 0) {
5156 $fuser->fetch($pageusermodifid);
5157 print $fuser->getNomUrl(-1);
5158 } else {
5159 print '<span class="opacitymedium">'.$langs->trans("Unknown").'</span>';
5160 }
5161 print '</td></tr>';
5162 }
5163
5164 // Content - Example/templates of page
5165 $url = 'https://wiki.dolibarr.org/index.php/Module_Website';
5166 $htmltext = '<small>';
5167 $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSource", $url);
5168 $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSource1", $url);
5169 $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSource2", $url);
5170 $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSource3", $url);
5171 $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSource4", $url);
5172 $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSource5", $url);
5173 $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSourceMore", $url);
5174 $htmltext .= '<br>';
5175 $htmltext .= '</small>';
5176
5177 $formmail = new FormMail($db);
5178 $formmail->withaiprompt = 'html';
5179 $formmail->withlayout = 'websitepage';
5180 $showlinktolayout = $formmail->withlayout;
5181 $showlinktoai = ($formmail->withaiprompt && isModEnabled('ai')) ? 'textgenerationwebpage' : '';
5182 if (($action == 'createcontainer' && $showlinktolayout) || ($action == 'createcontainer' && $showlinktoai)) {
5183 print '<tr><td class="titlefield tdtop">';
5184 if ($conf->browser->layout == 'phone') {
5185 print $form->textwithpicto('', $htmltext, 1, 'help', 'inline-block', 1, 2, 'tooltipsubstitution');
5186 } else {
5187 //img_help(($tooltiptrigger != '' ? 2 : 1), $alt)
5188 print $form->textwithpicto($langs->trans("PreviewPageContent").' '.img_help(2, $langs->trans("PreviewPageContent")), $htmltext, 1, 'none', 'inline-block', 1, 2, 'tooltipsubstitution');
5189 }
5190 print '</td><td class="tdtop">';
5191
5192 $out = '';
5193
5194 $showlinktolayoutlabel = $langs->trans("FillPageWithALayout");
5195 $showlinktoailabel = $langs->trans("FillPageWithAIContent");
5196 $htmlname = 'content';
5197 // Fill $out
5198 include DOL_DOCUMENT_ROOT.'/core/tpl/formlayoutai.tpl.php';
5199
5200 print $out;
5201 print '</td></tr>';
5202 }
5203
5204 if ($action == 'createcontainer') {
5205 print '<tr id="pageContent"><td class="tdtop">';
5206 if (!$showlinktolayout || !$showlinktoai) {
5207 if ($conf->browser->layout == 'phone') {
5208 print $form->textwithpicto('', $htmltext, 1, 'help', 'inline-block', 1, 2, 'tooltipsubstitution');
5209 } else {
5210 //img_help(($tooltiptrigger != '' ? 2 : 1), $alt)
5211 print $form->textwithpicto($showlinktolayout ? '' : ($langs->trans("PreviewPageContent").' '.img_help(2, $langs->trans("PreviewPageContent"))), $htmltext, 1, 'none', 'inline-block', 1, 2, 'tooltipsubstitution');
5212 }
5213 }
5214 print '</td><td>';
5215 //$doleditor = new DolEditor('content', GETPOST('content', 'restricthtmlallowunvalid'), '', 200, 'dolibarr_mailings', 'In', true, true, true, 40, '90%');
5216 $doleditor = new DolEditor('content', GETPOST('content', 'none'), '', 200, 'dolibarr_mailings', 'In', true, true, true, 40, '90%');
5217 $doleditor->Create();
5218 print '</div>';
5219 print '</td></tr>';
5220 }
5221
5222 // Date creation
5223 print '<tr><td>';
5224 print $langs->trans('DateCreation');
5225 print '</td><td>';
5226 print $form->selectDate($pagedatecreation, 'datecreation', 1, 1, 0, '', 1, 1);
5227 //print dol_print_date($pagedatecreation, 'dayhour');
5228 print '</td></tr>';
5229
5230 // Author
5231 print '<tr><td>';
5232 print $langs->trans('Author');
5233 print '</td><td>';
5234 if ($pageauthorid > 0) {
5235 $fuser->fetch($pageauthorid);
5236 print $fuser->getNomUrl(-1);
5237 } else {
5238 print '<span class="opacitymedium">'.$langs->trans("Unknown").'</span>';
5239 }
5240 print '</td></tr>';
5241
5242 // Author - public alias
5243 print '<tr class="trpublicauthor hidden"><td>';
5244 print $langs->trans('PublicAuthorAlias');
5245 print '</td><td>';
5246 print '<input type="text" class="flat minwidth300" name="WEBSITE_AUTHORALIAS" value="'.dol_escape_htmltag($pageauthoralias).'" placeholder="'.dol_escape_htmltag($langs->trans("Anonymous")).'">';
5247 print '</td></tr>';
5248
5249 // Web page header
5250 print '<tr><td class="tdhtmlheader tdtop">';
5251 $htmlhelp = $langs->trans("EditTheWebSiteForACommonHeader").'<br><br>';
5252 $htmlhelp .= $langs->trans("Examples").' :<br>';
5253 $htmlhelp .= '<span class="small">';
5254 $htmlhelp .= dol_nl2br(dol_htmlentities($htmlheadercontentdefault)); // do not use dol_htmlentitiesbr here, $htmlheadercontentdefault is HTML with content like <link> and <script> that we want to be html encode as they must be show as doc content not executable instruction.
5255 $htmlhelp .= '</span>';
5256 print $form->textwithpicto($langs->transnoentitiesnoconv('HtmlHeaderPage'), $htmlhelp, 1, 'help', '', 0, 2, 'htmlheadertooltip');
5257 print '</td><td>';
5258 $poscursor = array('x' => GETPOST('htmlheader_x'), 'y' => GETPOST('htmlheader_y'));
5259 $doleditor = new DolEditor('htmlheader', $pagehtmlheader, '', 160, 'ace', 'In', true, false, 'ace', ROWS_4, '100%', 0, $poscursor);
5260 print $doleditor->Create(1, '', true, 'HTML Header', 'html');
5261 print '</td></tr>';
5262
5263 // Allowed in frames
5264 print '<tr><td>';
5265 print $langs->trans('AllowedInFrames');
5266 //$htmlhelp = $langs->trans("AllowedInFramesDesc");
5267 //print $form->textwithpicto($langs->trans('AllowedInFrames'), $htmlhelp, 1, 'help', '', 0, 2, 'allowedinframestooltip');
5268 print '</td><td>';
5269 print '<input type="checkbox" class="flat" name="WEBSITE_ALLOWED_IN_FRAMES" value="1"'.($pageallowedinframes ? 'checked="checked"' : '').'>';
5270 print '</td></tr>';
5271
5272 // Number of versions to keep in history
5273 if ($action != 'createcontainer') {
5274 print '<tr><td>';
5275 $htmlhelp = $langs->trans("NumberOfVersionsToKeepInHistoryHelp");
5276 print $form->textwithpicto($langs->trans('NumberOfVersionsToKeepInHistory'), $htmlhelp, 1, 'help', '', 0, 2, 'keephistorytooltip');
5277 print '</td><td>';
5278 print '<input type="text" class="flat maxwidth50" name="WEBSITE_KEEP_HISTORY" value="'.dol_escape_htmltag((string) $pagekeephistory).'">';
5279 print '</td></tr>';
5280 }
5281
5282 print '</table>';
5283
5284
5285 if ($action == 'createcontainer') {
5286 $langs->load("website");
5287
5288 print '<div class="center tablecheckboxcreatemanually'.$hiddenmanuallyafterload.'">';
5289
5290 print '<input type="submit" class="button small buttonforacesave" name="addcontainer" value="'.$langs->trans("Create").'">';
5291 print '<input class="button button-cancel small" type="submit" name="preview" value="'.$langs->trans("Cancel").'">';
5292
5293 print '</div>';
5294
5295 print '<br>';
5296
5297 if (!empty($conf->use_javascript_ajax)) {
5298 print '<input type="radio" name="radiocreatefrom" id="checkboxcreatefromfetching" value="checkboxcreatefromfetching"'.(GETPOST('radiocreatefrom') == 'checkboxcreatefromfetching' ? ' checked' : '').'> ';
5299 }
5300 print '<label for="checkboxcreatefromfetching"><span class="opacitymediumxx">'.$langs->trans("CreateByFetchingExternalPage").'</span> <span class="small opacitymedium">('.$langs->trans("ForAdvancedWebmastersOnly").')</small></label><br>';
5301 print '<hr class="tablecheckboxcreatefromfetching'.$hiddenfromfetchingafterload.'">';
5302
5303 print info_admin($langs->trans("OnlyEditionOfSourceForGrabbedContentFuture"), 0, 0, 'warning tablecheckboxcreatefromfetching'.$hiddenfromfetchingafterload);
5304 print '<br>';
5305
5306 print '<table class="tableforfield centpercent tablecheckboxcreatefromfetching'.$hiddenfromfetchingafterload.'">';
5307 print '<tr><td class="titlefield tdtop">';
5308 print $langs->trans("URL");
5309 print '</td><td>';
5310 print '<input class="flat minwidth500 marginbottomonly" type="text" name="externalurl" value="'.dol_escape_htmltag(GETPOST('externalurl', 'alpha')).'" placeholder="https://externalsite/pagetofetch"> ';
5311 print '<br>';
5312 print '<div class="paddingtop">';
5313 print '<input class="flat paddingtop paddingright" type="checkbox" name="grabimages" value="1" checked="checked">';
5314 print '<span class="valignmiddle">'.$langs->trans("GrabImagesInto");
5315 print ' ';
5316 print $langs->trans("ImagesShouldBeSavedInto").' ';
5317 print '</span>';
5318 $arraygrabimagesinto = array('root' => $langs->trans("WebsiteRootOfImages"), 'subpage' => $langs->trans("SubdirOfPage"));
5319 print $form->selectarray('grabimagesinto', $arraygrabimagesinto, GETPOSTISSET('grabimagesinto') ? GETPOST('grabimagesinto') : 'root', 0, 0, 0, '', 0, 0, 0, '', 'minwidth75 valignmiddle', 1);
5320 print '</div>';
5321
5322 print '<input class="button small" style="margin-top: 5px" type="submit" name="fetchexternalurl" value="'.dol_escape_htmltag($langs->trans("FetchAndCreate")).'">';
5323 print '<input class="button button-cancel small" type="submit" name="preview" value="'.$langs->trans("Cancel").'">';
5324
5325 print '</td></tr>';
5326 print '</table>';
5327 }
5328
5329 if ($action == 'createcontainer') {
5330 print '<script type="text/javascript">
5331 jQuery(document).ready(function() {
5332 var disableautofillofalias = 0;
5333 var selectedm = \'\';
5334 var selectedf = \'\';
5335
5336 jQuery("#WEBSITE_TITLE").keyup(function() {
5337 if (disableautofillofalias == 0) {
5338 var valnospecial = jQuery("#WEBSITE_TITLE").val();
5339 valnospecial = valnospecial.replace(/[éèê]/g, \'e\').replace(/[à]/g, \'a\').replace(/[ù]/g, \'u\').replace(/[î]/g, \'i\');
5340 valnospecial = valnospecial.replace(/[ç]/g, \'c\').replace(/[ö]/g, \'o\');
5341 valnospecial = valnospecial.replace(/[^\w]/gi, \'-\').toLowerCase();
5342 valnospecial = valnospecial.replace(/\-+/g, \'-\').replace(/\-$/, \'\');
5343 console.log("disableautofillofalias=0 so we replace WEBSITE_TITLE with "+valnospecial);
5344 jQuery("#WEBSITE_PAGENAME").val(valnospecial);
5345 }
5346 });
5347 jQuery("#WEBSITE_PAGENAME").keyup(function() {
5348 if (jQuery("#WEBSITE_PAGENAME").val() == \'\') {
5349 disableautofillofalias = 0;
5350 } else {
5351 disableautofillofalias = 1;
5352 }
5353 });
5354 jQuery("#WEBSITE_PAGENAME").blur(function() {
5355 if (jQuery("#WEBSITE_PAGENAME").val() == \'\') {
5356 disableautofillofalias = 0;
5357 jQuery("#WEBSITE_TITLE").trigger(\'keyup\');
5358 }
5359 });
5360
5361 jQuery("#checkboxcreatefromfetching,#checkboxcreatemanually").click(function() {
5362 console.log("we select a method to create a new container "+jQuery("#checkboxcreatefromfetching:checked").val())
5363 jQuery(".tablecheckboxcreatefromfetching").hide();
5364 jQuery(".tablecheckboxcreatemanually").hide();
5365 if (typeof(jQuery("#checkboxcreatefromfetching:checked").val()) != \'undefined\') {
5366 console.log("show create from spider form");
5367 if (selectedf != \'createfromfetching\') {
5368 jQuery(".tablecheckboxcreatefromfetching").show();
5369 selectedf = \'createfromfetching\';
5370 selectedm = \'\';
5371 } else {
5372 jQuery(".tablecheckboxcreatefromfetching").hide();
5373 selectedf = \'\';
5374 }
5375 }
5376 if (typeof(jQuery("#checkboxcreatemanually:checked").val()) != \'undefined\') {
5377 console.log("show create from scratch or template form");
5378 if (selectedm != \'createmanually\') {
5379 jQuery(".tablecheckboxcreatemanually").show();
5380 selectedm = \'createmanually\';
5381 selectedf = \'\';
5382 } else {
5383 jQuery(".tablecheckboxcreatemanually").hide();
5384 selectedm = \'\';
5385 }
5386 }
5387 });
5388 });
5389 </script>';
5390 }
5391
5392 print '</div>';
5393
5394 print '<br>';
5395}
5396
5397
5398// Print formconfirm
5399if ($action == 'preview') {
5400 print $formconfirm;
5401}
5402
5403if ($action == 'editfile' || $action == 'file_manager' || $action == 'convertimgwebp' || $action == 'confirmconvertimgwebp') {
5404 print '<!-- Edit Media -->'."\n";
5405 print '<div class="fichenopadding" style="padding-right: 20px">'.($dol_openinpopup ? '' : '<br>');
5406
5407 $module = 'medias';
5408 $formalreadyopen = 2; // So the form to submit a new file will not be open another time inside the core/tpl/filemanager.tpl.php
5409 if (empty($url)) {
5410 $url = DOL_URL_ROOT.'/website/index.php'; // Must be an url without param
5411 }
5412 include DOL_DOCUMENT_ROOT.'/core/tpl/filemanager.tpl.php';
5413
5414 print '</div>';
5415}
5416
5417if ($action == 'editmenu') {
5418 print '<!-- Edit Menu -->'."\n";
5419 print '<div class="center">'.$langs->trans("FeatureNotYetAvailable").'</center>';
5420}
5421
5422if ($action == 'editsource') {
5423 // Editing with source editor
5424
5425 $contentforedit = '';
5426 //$contentforedit.='<style scoped>'."\n"; // "scoped" means "apply to parent element only". Not yet supported by browsers
5427 //$contentforedit.=$csscontent;
5428 //$contentforedit.='</style>'."\n";
5429 $contentforedit .= $objectpage->content;
5430
5431 // If an archived version of the page is selected, we load its content into the editor,
5432 // so saving the page will restore this old version as the current one
5433 if (!empty($filetplversion)) {
5434 $contentoffile = @file_get_contents($filetplversion);
5435 if ($contentoffile) {
5436 // Extract the body of the generated page to get the page content of the archived version
5437 if (preg_match('/<body[^>]*>(.*)<\/body>/ims', $contentoffile, $reg)) {
5438 $contentforedit = $reg[1];
5439 }
5440 }
5441 }
5442
5443 // We set maxheightwin in px. We take the height of screen in px and we remove a part for the top banner and more
5444 $maxheightwin = 480;
5445 if (isset($_SESSION["dol_screenheight"])) {
5446 if ($_SESSION["dol_screenheight"] > 680) {
5447 $maxheightwin = (int) $_SESSION["dol_screenheight"] - 300; // We remove a height for header
5448 }
5449 if ($_SESSION["dol_screenheight"] > 800) {
5450 $maxheightwin = (int) $_SESSION["dol_screenheight"] - 250; // We remove a height for header (on large width, risk to have header on 2 lines is lower)
5451 }
5452 }
5453
5454 $poscursor = array('x' => GETPOST('PAGE_CONTENT_x'), 'y' => GETPOST('PAGE_CONTENT_y'));
5455 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5456 $titlecontent = 'HTML Source';
5457
5458 // Add the link to the AI feature into the status bar of the ACE editor
5459 if (isModEnabled('ai')) {
5460 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
5461 $formmail = new FormMail($db);
5462 $formmail->withaiprompt = 'html';
5463 $showlinktolayout = '';
5464 $showlinktoai = 'textgenerationwebpage';
5465 $showlinktoailabel = $langs->trans("FillPageWithAIContent");
5466 $htmlname = 'PAGE_CONTENT';
5467 $out = '';
5468 // Fill $out
5469 include DOL_DOCUMENT_ROOT.'/core/tpl/formlayoutai.tpl.php';
5470
5471 $titlecontent .= ' &nbsp; '.$out;
5472 }
5473
5474 $doleditor = new DolEditor('PAGE_CONTENT', $contentforedit, '', $maxheightwin, 'Full', '', true, true, 'ace', ROWS_5, '40%', 0, $poscursor);
5475 $doleditor->Create(0, '', false, $titlecontent, 'php');
5476}
5477
5478if ($action == 'editcontent') {
5479 // Editing with default ckeditor
5480
5481 $contentforedit = '';
5482 //$contentforedit.='<style scoped>'."\n"; // "scoped" means "apply to parent element only". Not yet supported by browsers
5483 //$contentforedit.=$csscontent;
5484 //$contentforedit.='</style>'."\n";
5485 $contentforedit .= $objectpage->content;
5486
5487 $nbrep = array();
5488 // If contentforedit has a string <img src="xxx", we replace the xxx with /viewimage.php?modulepart=medias&file=xxx except if xxx starts
5489 // with http, /viewimage.php or DOL_URL_ROOT./viewimage.phps
5490 $contentforedit = preg_replace('/(<img.*\ssrc=")(?!http|\/viewimage\.php|'.preg_quote(DOL_URL_ROOT, '/').'\/viewimage\.php)/', '\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $contentforedit, -1, $nbrep);
5491
5492 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5493 $poscursor = array('x' => GETPOST('PAGE_CONTENT_x'), 'y' => GETPOST('PAGE_CONTENT_y'));
5494 $doleditor = new DolEditor('PAGE_CONTENT', $contentforedit, '', 500, 'Full', '', true, true, true, ROWS_5, '90%', 0, $poscursor);
5495 $doleditor->Create(0, '', false);
5496}
5497
5498print "</div>\n";
5499print "</form>\n";
5500print '<!-- Now, output content of page ID='.($websitepage->id??'NULL').', mode= '.$mode.' WEBSITE_SUBCONTAINERSINLINE='.getDolGlobalString('WEBSITE_SUBCONTAINERSINLINE').' WEBSITE_EDITINLINE='.getDolGlobalString('WEBSITE_EDITINLINE').' -->'."\n";
5501
5502
5503if ($mode == 'replacesite' || $massaction == 'replace') {
5504 print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
5505 print '<input type="hidden" name="token" value="'.newToken().'">';
5506 print '<input type="hidden" name="action" value="replacesiteconfirm">';
5507 print '<input type="hidden" name="mode" value="replacesite">';
5508 print '<input type="hidden" name="website" value="'.$website->ref.'">';
5509
5510
5511 print '<!-- Search page and replace string -->'."\n";
5512 print '<div class="fiche"><br>';
5513
5514 print load_fiche_titre($langs->trans("ReplaceWebsiteContent"), '', 'search');
5515
5516 print '<div class="neutral">';
5517
5518 print '<div class="display-flex"><div class="flex-item">';
5519
5520 print '<div class="tagtable">';
5521
5522 print '<div class="tagtr">';
5523 print '<div class="tagtd paddingrightonly opacitymedium">';
5524 print $langs->trans("SearchReplaceInto");
5525 print '</div>';
5526 print '<div class="tagtd">';
5527 print '<input type="checkbox" class="marginleftonly" id="checkboxoptionpcontent" name="optionpcontent" value="content"'.((!GETPOSTISSET('buttonreplacesitesearch') || GETPOST('optionpcontent', 'aZ09')) ? ' checked' : '').'> <label for="checkboxoptionpcontent" class="tdoverflowmax150onsmartphone inline-block valignmiddle">'.$langs->trans("Content").'</label><br>';
5528 print '<input type="checkbox" class="marginleftonly" id="checkboxoptionmeta" name="optionmeta" value="meta"'.(GETPOST('optionmeta', 'aZ09') ? ' checked' : '').'> <label for="checkboxoptionmeta" class="tdoverflowmax150onsmartphone inline-block valignmiddle">'.$langs->trans("WEBSITE_PAGENAME").' | '.$langs->trans("Title").' | '.$langs->trans("Description").' | '.$langs->trans("Keywords").'</label><br>';
5529 print '<input type="checkbox" class="marginleftonly" id="checkboxoptionsitefiles" name="optionsitefiles" value="sitefiles"'.(GETPOST('optionsitefiles', 'aZ09') ? ' checked' : '').'> <label for="checkboxoptionsitefiles" class="tdoverflowmax150onsmartphone inline-block valignmiddle">'.$langs->trans("GlobalCSSorJS").'</label><br>';
5530 print '</div>';
5531 print '</div>';
5532
5533 print '<div class="tagtr">';
5534 print '<div class="tagtd paddingrightonly opacitymedium" style="padding-right: 10px !important">';
5535 print $langs->trans("SearchString");
5536 print '</div>';
5537 print '<div class="tagtd">';
5538 print '<input type="text" name="searchstring" value="'.dol_escape_htmltag($searchkey, 0, 0, '', 1).'" autofocus>';
5539 print '</div>';
5540 print '</div>';
5541
5542 print '</div>';
5543
5544 print '</div><div class="flex-item">';
5545
5546 print '<div class="tagtable">';
5547
5548 print '<div class="tagtr">';
5549 print '<div class="tagtd paddingrightonly opacitymedium tdoverflowmax100onsmartphone" style="padding-right: 10px !important">';
5550 print $langs->trans("WEBSITE_TYPE_CONTAINER");
5551 print '</div>';
5552 print '<div class="tagtd">';
5553 print img_picto('', 'object_technic', 'class="pictofixedwidth"').' ';
5554 print $formwebsite->selectTypeOfContainer('optioncontainertype', (GETPOST('optioncontainertype', 'alpha') ? GETPOST('optioncontainertype', 'alpha') : ''), 1, '', 1, 'minwidth125 maxwidth400 widthcentpercentminusx');
5555 print '</div>';
5556 print '</div>';
5557
5558 print '<div class="tagtr">';
5559 print '<div class="tagtd paddingrightonly opacitymedium tdoverflowmax100onsmartphone" style="padding-right: 10px !important">';
5560 print $langs->trans("Language");
5561 print '</div>';
5562 print '<div class="tagtd">';
5563 print img_picto('', 'language', 'class="pictofixedwidth"').' '.$formadmin->select_language(GETPOSTISSET('optionlanguage') ? GETPOST('optionlanguage') : '', 'optionlanguage', 0, array(), '1', 0, 0, 'minwidth125 maxwidth400 widthcentpercentminusx', 2, 0, 0, array(), 1);
5564 print '</div>';
5565 print '</div>';
5566
5567 // Categories
5568 if (isModEnabled('category') && $user->hasRight('categorie', 'lire')) {
5569 print '<div class="tagtr">';
5570 print '<div class="tagtd paddingrightonly marginrightonly opacitymedium tdoverflowmax100onsmartphone" style="padding-right: 10px !important">';
5571 print $langs->trans("Category");
5572 print '</div>';
5573 print '<div class="tagtd">';
5574 //print $form->selectCategories(Categorie::TYPE_WEBSITE_PAGE, 'optioncategory', $object);
5575 print img_picto('', 'category', 'class="pictofixedwidth"').' '.$form->select_all_categories(Categorie::TYPE_WEBSITE_PAGE, GETPOSTISSET('optioncategory') ? GETPOST('optioncategory') : '', 'optioncategory', 0, 0, 0, 0, 'minwidth125 maxwidth400 widthcentpercentminusx');
5576 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
5577 print ajax_combobox('optioncategory');
5578 print '</div>';
5579 print '</div>';
5580 }
5581
5582 print '</div>';
5583
5584 print '</div></div>';
5585
5586 print '<center>';
5587 print '<input type="submit" class="button margintoponly" name="buttonreplacesitesearch" value="'.dol_escape_htmltag($langs->trans("Search")).'">';
5588 print '</center>';
5589
5590 print '</div>';
5591
5592
5593 if ($mode == 'replacesite') {
5594 print '<!-- List of search result -->'."\n";
5595 print '<div class="rowsearchresult clearboth">';
5596
5597 print '<br>';
5598 print '<br>';
5599
5600 if ($listofpages['code'] == 'OK') {
5601 $arrayofselected = is_array($toselect) ? $toselect : array();
5602 $param = '';
5603 $nbtotalofrecords = count($listofpages['list']);
5604 $num = $limit;
5605 $permissiontodelete = $user->hasRight('website', 'delete');
5606
5607 // List of mass actions available
5608 $arrayofmassactions = array();
5609 if ($user->hasRight('website', 'writephp') && $searchkey) {
5610 $arrayofmassactions['replace'] = img_picto('', 'replacement', 'class="pictofixedwidth"').$langs->trans("Replace");
5611 }
5612 if ($user->hasRight('website', 'write')) {
5613 $langs->load("categories");
5614 $arrayofmassactions['setcategory'] = img_picto('', 'category', 'class="pictofixedwidth"').$langs->trans("ClassifyInCategory");
5615 }
5616 if ($user->hasRight('website', 'write')) {
5617 $langs->load("categories");
5618 $arrayofmassactions['delcategory'] = img_picto('', 'category', 'class="pictofixedwidth"').$langs->trans("RemoveCategory");
5619 }
5620 if ($permissiontodelete) {
5621 $arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete");
5622 }
5623 if (GETPOSTINT('nomassaction') || in_array($massaction, array('presend', 'predelete'))) {
5624 $arrayofmassactions = array();
5625 }
5626
5627 $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
5628 $massactionbutton .= '<div class="massactionother massactionreplace hidden">';
5629 $massactionbutton .= $langs->trans("ReplaceString");
5630 $massactionbutton .= ' <input type="text" name="replacestring" value="'.dol_escape_htmltag(GETPOST('replacestring', 'none')).'">';
5631 $massactionbutton .= '</div>';
5632 $massactionbutton .= '<div class="massactionother massactionsetcategory massactiondelcategory hidden">';
5633 $massactionbutton .= img_picto('', 'category', 'class="pictofixedwidth"');
5634 $massactionbutton .= $form->select_all_categories(Categorie::TYPE_WEBSITE_PAGE, GETPOSTISSET('setcategory') ? GETPOST('setcategory') : '', 'setcategory', 64, 0, 0, 0, 'minwidth300 alignstart');
5635 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
5636 $massactionbutton .= ajax_combobox('setcategory');
5637 $massactionbutton .= '</div>';
5638
5639 $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
5640
5641 //$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage, $conf->main_checkbox_left_column); // This also change content of $arrayfields
5642 $selectedfields = '';
5643 $selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : '');
5644
5645 print_barre_liste($langs->trans("Results"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'generic', 0, '', '', $limit, 1, 1, 1);
5646
5647 $topicmail = "WebsitePageRef";
5648 $modelmail = "websitepage_send";
5649 $objecttmp = new WebsitePage($db);
5650 $trackid = 'wsp'.$object->id;
5651 include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
5652
5653 $param = 'mode=replacesite&website='.urlencode($website->ref);
5654 $param .= '&searchstring='.urlencode($searchkey);
5655 if (GETPOST('optionpcontent')) {
5656 $param .= '&optionpcontent=content';
5657 }
5658 if (GETPOST('optionmeta')) {
5659 $param .= '&optionmeta=meta';
5660 }
5661 if (GETPOST('optionsitefiles')) {
5662 $param .= '&optionsitefiles=optionsitefiles';
5663 }
5664 if (GETPOST('optioncontainertype')) {
5665 $param .= '&optioncontainertype='.GETPOST('optioncontainertype', 'aZ09');
5666 }
5667 if (GETPOST('optionlanguage')) {
5668 $param .= '&optionlanguage='.GETPOST('optionlanguage', 'aZ09');
5669 }
5670 if (GETPOST('optioncategory')) {
5671 $param .= '&optioncategory='.GETPOST('optioncategory', 'aZ09');
5672 }
5673
5674 print '<div class="div-table-responsive-no-min">';
5675 print '<table class="noborder centpercent">';
5676 print '<tr class="liste_titre">';
5677 // Action column
5678 if ($conf->main_checkbox_left_column) {
5679 print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n";
5680 }
5681 print getTitleFieldOfList("Type", 0, $_SERVER['PHP_SELF'], 'type_container', '', $param, '', $sortfield, $sortorder, '')."\n";
5682 print getTitleFieldOfList("Page", 0, $_SERVER['PHP_SELF'], 'pageurl', '', $param, '', $sortfield, $sortorder, '')."\n";
5683 print getTitleFieldOfList("Language", 0, $_SERVER['PHP_SELF'], 'lang', '', $param, '', $sortfield, $sortorder, 'center ')."\n";
5684 print getTitleFieldOfList("Categories", 0, $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'center ')."\n";
5685 print getTitleFieldOfList("", 0, $_SERVER['PHP_SELF']);
5686 print getTitleFieldOfList("UserCreation", 0, $_SERVER['PHP_SELF'], 'fk_user_creat', '', $param, '', $sortfield, $sortorder, '')."\n";
5687 print getTitleFieldOfList("DateCreation", 0, $_SERVER['PHP_SELF'], 'date_creation', '', $param, '', $sortfield, $sortorder, 'center ')."\n"; // Date creation
5688 print getTitleFieldOfList("DateLastModification", 0, $_SERVER['PHP_SELF'], 'tms', '', $param, '', $sortfield, $sortorder, 'center ')."\n"; // Date last modif
5689 print getTitleFieldOfList("", 0, $_SERVER['PHP_SELF']);
5690 // Action column
5691 if (!$conf->main_checkbox_left_column) {
5692 print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n";
5693 }
5694 print '</tr>';
5695
5696 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5697 $c = new Categorie($db);
5698
5699 $totalnbwords = 0;
5700
5701 foreach ($listofpages['list'] as $answerrecord) {
5702 if (is_object($answerrecord) && get_class($answerrecord) == 'WebsitePage') {
5703 $param = '?mode=replacesite';
5704 $param .= '&websiteid='.$website->id;
5705 $param .= '&optionpcontent='.GETPOST('optionpcontent', 'aZ09');
5706 $param .= '&optionmeta='.GETPOST('optionmeta', 'aZ09');
5707 $param .= '&optionsitefiles='.GETPOST('optionsitefiles', 'aZ09');
5708 $param .= '&optioncontainertype='.GETPOST('optioncontainertype', 'aZ09');
5709 $param .= '&optionlanguage='.GETPOST('optionlanguage', 'aZ09');
5710 $param .= '&optioncategory='.GETPOST('optioncategory', 'aZ09');
5711 $param .= '&searchstring='.urlencode($searchkey);
5712
5713 print '<tr>';
5714
5715 // Action column
5716 if ($conf->main_checkbox_left_column) {
5717 print '<td class="nowrap center">';
5718
5719 print '<!-- Status of page -->'."\n";
5720 if ($massactionbutton || $massaction) {
5721 $selected = 0;
5722 if (in_array($answerrecord->id, $arrayofselected)) {
5723 $selected = 1;
5724 }
5725 print '<input id="'.$answerrecord->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$answerrecord->id.'"'.($selected ? ' checked="checked"' : '').'>';
5726 }
5727 print '</td>';
5728 }
5729
5730 // Type of container
5731 print '<td class="nowraponall">';
5732 //print $langs->trans("Container").'<br>';
5733 if (!empty($conf->cache['type_of_container'][$answerrecord->type_container])) {
5734 print $langs->trans($conf->cache['type_of_container'][$answerrecord->type_container]);
5735 } else {
5736 print $langs->trans($answerrecord->type_container);
5737 }
5738 print '</td>';
5739
5740 // Container url and label
5741 $titleofpage = ($answerrecord->title ? $answerrecord->title : $langs->trans("NoTitle"));
5742 print '<td class="tdoverflowmax300" title="'.dol_escape_htmltag($titleofpage).'">';
5743 print $answerrecord->getNomUrl(1);
5744 print ' <span class="opacitymedium">('.dol_escape_htmltag($titleofpage).')</span>';
5745 //print '</td>';
5746 //print '<td class="tdoverflow100">';
5747 print '<br>';
5748 print '<span class="opacitymedium">'.dol_escape_htmltag($answerrecord->description ? $answerrecord->description : $langs->trans("NoDescription")).'</span>';
5749 print '</td>';
5750
5751 // Language
5752 print '<td class="center">';
5753 print picto_from_langcode($answerrecord->lang, $answerrecord->lang);
5754 print '</td>';
5755
5756 // Categories - Tags
5757 print '<td class="center">';
5758 if (isModEnabled('category') && $user->hasRight('categorie', 'lire')) {
5759 // Get current categories
5760 $existing = $c->containing($answerrecord->id, Categorie::TYPE_WEBSITE_PAGE, 'object');
5761 if (is_array($existing)) {
5762 foreach ($existing as $tmpcategory) {
5763 //var_dump($tmpcategory);
5764 print img_object($langs->trans("Category").' : '.$tmpcategory->label, 'category', 'style="padding-left: 2px; padding-right: 2px; color: #'.($tmpcategory->color != '' ? $tmpcategory->color : '888').'"');
5765 }
5766 }
5767 }
5768 //var_dump($existing);
5769 print '</td>';
5770
5771 // Number of words
5772 print '<td class="center nowraponall">';
5773 $textwithouthtml = dol_string_nohtmltag(dolStripPhpCode($answerrecord->content));
5774 $characterMap = 'áàéèëíóúüñùç0123456789';
5775 $nbofwords = str_word_count($textwithouthtml, 0, $characterMap);
5776 if ($nbofwords) {
5777 print $nbofwords.' '.$langs->trans("words");
5778 $totalnbwords += $nbofwords;
5779 }
5780 print '</td>';
5781
5782 // Author
5783 print '<td class="tdoverflowmax125">';
5784 if (!empty($answerrecord->fk_user_creat)) {
5785 if (empty($conf->cache['user'][$answerrecord->fk_user_creat])) {
5786 $tmpuser = new User($db);
5787 $tmpuser->fetch($answerrecord->fk_user_creat);
5788 $conf->cache['user'][$answerrecord->fk_user_creat] = $tmpuser;
5789 } else {
5790 $tmpuser = $conf->cache['user'][$answerrecord->fk_user_creat];
5791 }
5792 print $tmpuser->getNomUrl(-1, '', 0, 0, 0, 0, 'login');
5793 }
5794 print '</td>';
5795
5796 // Date creation
5797 print '<td class="center nowraponall">';
5798 print dol_print_date($answerrecord->date_creation, 'dayhour');
5799 print '</td>';
5800
5801 // Date last modification
5802 print '<td class="center nowraponall">';
5803 print dol_print_date($answerrecord->date_modification, 'dayhour');
5804 print '</td>';
5805
5806 // Edit properties, HTML sources, status
5807 print '<td class="tdwebsitesearchresult right nowraponall">';
5808 $disabled = '';
5809 $urltoedithtmlsource = $_SERVER["PHP_SELF"].'?action=editmeta&token='.newToken().'&websiteid='.$website->id.'&pageid='.$answerrecord->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].$param);
5810 if (!$user->hasRight('website', 'write')) {
5811 $disabled = ' disabled';
5812 $urltoedithtmlsource = '';
5813 }
5814 print '<a class="editfielda marginleftonly marginrightonly '.$disabled.'" href="'.$urltoedithtmlsource.'" title="'.$langs->trans("EditPageMeta").'">'.img_picto($langs->trans("EditPageMeta"), 'pencil-ruler').'</a>';
5815
5816 $disabled = '';
5817 $urltoedithtmlsource = $_SERVER["PHP_SELF"].'?action=editsource&token='.newToken().'&websiteid='.$website->id.'&pageid='.$answerrecord->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].$param);
5818 if (!$user->hasRight('website', 'write')) {
5819 $disabled = ' disabled';
5820 $urltoedithtmlsource = '';
5821 }
5822 print '<a class="editfielda marginleftonly marginrightonly '.$disabled.'" href="'.$urltoedithtmlsource.'" title="'.$langs->trans("EditHTMLSource").'">'.img_picto($langs->trans("EditHTMLSource"), 'edit').'</a>';
5823
5824 print '<span class="marginleftonly marginrightonly"></span>';
5825 print ajax_object_onoff($answerrecord, 'status', 'status', 'Enabled', 'Disabled', array(), 'valignmiddle inline-block');
5826
5827 print '</td>';
5828
5829 // Action column
5830 if (!$conf->main_checkbox_left_column) {
5831 print '<td class="nowrap center">';
5832
5833 print '<!-- Status of page -->'."\n";
5834 if ($massactionbutton || $massaction) {
5835 $selected = 0;
5836 if (in_array($answerrecord->id, $arrayofselected)) {
5837 $selected = 1;
5838 }
5839 print '<input id="'.$answerrecord->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$answerrecord->id.'"'.($selected ? ' checked="checked"' : '').'>';
5840 }
5841 print '</td>';
5842 }
5843
5844 print '</tr>';
5845 } else {
5846 // $answerrecord is not list of WebsitePage
5847 '@phan-var-force array{type:string} $answerrecord';
5848 $param = '?mode=replacesite';
5849 $param .= '&websiteid='.$website->id;
5850 $param .= '&optionpcontent='.GETPOST('optionpcontent', 'aZ09');
5851 $param .= '&optionmeta='.GETPOST('optionmeta', 'aZ09');
5852 $param .= '&optionsitefiles='.GETPOST('optionsitefiles', 'aZ09');
5853 $param .= '&optioncontainertype='.GETPOST('optioncontainertype', 'aZ09');
5854 $param .= '&optionlanguage='.GETPOST('optionlanguage', 'aZ09');
5855 $param .= '&optioncategory='.GETPOST('optioncategory', 'aZ09');
5856 $param .= '&searchstring='.urlencode($searchkey);
5857
5858 print '<tr>';
5859
5860 // Action column
5861 if ($conf->main_checkbox_left_column) {
5862 print '<td class="nowrap center">';
5863 print '</td>';
5864 }
5865
5866 // Type of container
5867 print '<td>';
5868 $translateofrecordtype = array(
5869 'website_csscontent' => 'WEBSITE_CSS_INLINE',
5870 'website_jscontent' => 'WEBSITE_JS_INLINE',
5871 'website_robotcontent' => 'WEBSITE_ROBOT',
5872 'website_htmlheadercontent' => 'WEBSITE_HTML_HEADER',
5873 'website_htaccess' => 'WEBSITE_HTACCESS',
5874 'website_readme' => 'WEBSITE_README',
5875 'website_manifestjson' => 'WEBSITE_MANIFEST_JSON'
5876 );
5877 print '<span class="opacitymedium">';
5878 if (!empty($translateofrecordtype[$answerrecord['type']])) {
5879 print $langs->trans($translateofrecordtype[$answerrecord['type']]);
5880 } else {
5881 print $answerrecord['type'];
5882 }
5883 print '</span>';
5884 print '</td>';
5885
5886 // Container url and label
5887 print '<td>';
5888 $backtopageurl = $_SERVER["PHP_SELF"].$param;
5889 print '<a href="'.$_SERVER["PHP_SELF"].'?action=editcss&token='.newToken().'&website='.urlencode($website->ref).'&backtopage='.urlencode($backtopageurl).'">'.$langs->trans("EditCss").'</a>';
5890 print '</td>';
5891
5892 // Language
5893 print '<td>';
5894 print '</td>';
5895
5896 // Categories - Tags
5897 print '<td>';
5898 print '</td>';
5899
5900 // Nb of words
5901 print '<td>';
5902 print '</td>';
5903
5904 print '<td>';
5905 print '</td>';
5906
5907 print '<td>';
5908 print '</td>';
5909
5910 // Date last modification
5911 print '<td class="center nowraponall">';
5912 //print dol_print_date(filemtime());
5913 print '</td>';
5914
5915 // Edit properties, HTML sources, status
5916 print '<td>';
5917 print '</td>';
5918
5919 // Action column
5920 if (!$conf->main_checkbox_left_column) {
5921 print '<td class="nowrap center">';
5922 print '</td>';
5923 }
5924
5925 print '</tr>';
5926 }
5927 }
5928
5929 if (count($listofpages['list']) >= 2) {
5930 // Total
5931 print '<tr class="lite_titre">';
5932
5933 // Action column
5934 if ($conf->main_checkbox_left_column) {
5935 print '<td class="nowrap center">';
5936 print '</td>';
5937 }
5938
5939 // Type of container
5940 print '<td>';
5941 print $langs->trans("Total");
5942 print '</td>';
5943
5944 // Container url and label
5945 print '<td>';
5946 print '</td>';
5947
5948 // Language
5949 print '<td>';
5950 print '</td>';
5951
5952 // Categories - Tags
5953 print '<td>';
5954 print '</td>';
5955
5956 // Nb of words
5957 print '<td class="center nowraponall">';
5958 print $totalnbwords.' '.$langs->trans("words");
5959 print '</td>';
5960
5961 print '<td>';
5962 print '</td>';
5963
5964 print '<td>';
5965 print '</td>';
5966
5967 // Date last modification
5968 print '<td>';
5969 print '</td>';
5970
5971 // Edit properties, HTML sources, status
5972 print '<td>';
5973 print '</td>';
5974
5975 // Action column
5976 if (!$conf->main_checkbox_left_column) {
5977 print '<td class="nowrap center">';
5978 print '</td>';
5979 }
5980
5981 print '</tr>';
5982 }
5983
5984 print '</table>';
5985 print '</div>';
5986 print '<br>';
5987 } else {
5988 print '<div class="warning">'.$listofpages['message'].'</div>';
5989 }
5990
5991 print '</div>';
5992 }
5993
5994 print '</form>';
5995}
5996
5997if ((empty($action) || $action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') && !in_array($mode, array('replacesite'))) {
5998 if ($pageid > 0 && $atleastonepage) {
5999 // $filejs
6000 // $filecss
6001 // $filephp
6002
6003 // Output page under the Dolibarr top menu
6004 $objectpage->fetch($pageid);
6005
6006 $jscontent = @file_get_contents($filejs);
6007
6008 $out = '<!-- Page content '.$filetpl.' : Div with (Htmlheader/Style of page from database + CSS Of website from file + Page content from database or by include if WEBSITE_SUBCONTAINERSINLINE is on) -->'."\n";
6009
6010 // Include a html so we can benefit of the header of page.
6011 // Note: We can't use iframe as it can be used to include another external html file
6012 // Note: We can't use frame as it is deprecated.
6013 /*if ($includepageintoaframeoradiv == 'iframe')
6014 {
6015 $out .= "<iframe><body></html>";
6016 }*/
6017 $out .= "\n<html><head>\n";
6018 $out .= "<!-- htmlheader/style of page from database -->\n";
6019 $out .= dolWebsiteReplacementOfLinks($object, $objectpage->htmlheader, 1, 'htmlheader');
6020
6021 $out .= "<!-- htmlheader/style of website from files -->\n";
6022 // TODO Keep only the <link> or the <script> tags
6023 /*
6024 $htmlheadercontent = @file_get_contents($filehtmlheader);
6025 $dom = new DOMDocument;
6026 @$dom->loadHTML($htmlheadercontent);
6027 $styles = $dom->getElementsByTagName('link');
6028 $scripts = $dom->getElementsByTagName('script');
6029 foreach($styles as $stylescursor)
6030 {
6031 $out.=$stylescursor;
6032 }
6033 foreach($scripts as $scriptscursor)
6034 {
6035 $out.=$scriptscursor;
6036 }
6037 */
6038
6039 $out .= "</head>\n";
6040 $out .= "\n";
6041 $out .= "<body>\n";
6042
6043
6044 $out .= '<div id="websitecontentundertopmenu" class="websitecontentundertopmenu boostrap-iso">'."\n";
6045
6046 // REPLACEMENT OF LINKS When page called by website editor
6047
6048 $out .= '<!-- style of website from file -->'."\n";
6049 $out .= '<style scoped>'."\n"; // "scoped" means "apply to parent element only and not grand parent". No more supported by browsers, snif !
6050 $tmpout = '';
6051 $tmpout .= '/* Include website CSS file */'."\n";
6052 //$csscontent = @file_get_contents($filecss);
6053 if (dol_is_file($filecss)) {
6054 ob_start();
6055 include $filecss;
6056 $csscontent = ob_get_contents();
6057 ob_end_clean();
6058 } else {
6059 $csscontent = '';
6060 }
6061 $tmpout .= dolWebsiteReplacementOfLinks($object, $csscontent, 1, 'css');
6062 $tmpout .= '/* Include style from the HTML header of page */'."\n";
6063 // Clean the html header of page to get only <style> content
6064 $tmp = preg_split('(<style[^>]*>|</style>)', $objectpage->htmlheader);
6065 $tmpstyleinheader = '';
6066 $i = 0;
6067 foreach ($tmp as $valtmp) {
6068 $i++;
6069 if ($i % 2 == 0) {
6070 $tmpstyleinheader .= $valtmp."\n";
6071 }
6072 }
6073 $tmpout .= $tmpstyleinheader."\n";
6074 // Clean style that may affect global style of Dolibarr
6075 $tmpout = preg_replace('/}[\s\n]*body\s*{[^}]+}/ims', '}', $tmpout);
6076 $out .= $tmpout;
6077 $out .= '</style>'."\n";
6078
6079 // Note: <div>, <section>, ... with contenteditable="true" inside this can be edited with inline ckeditor
6080
6081 // Do not enable the contenteditable when page was grabbed, ckeditor is removing span and adding borders,
6082 // so editable will be available only from container created from scratch
6083 //$out.='<div id="bodywebsite" class="bodywebsite"'.($objectpage->grabbed_from ? ' contenteditable="true"' : '').'>'."\n";
6084 $out .= '<div id="divbodywebsite" class="bodywebsite bodywebpage-'.$objectpage->ref.'">'."\n";
6085
6086 $newcontent = $objectpage->content;
6087
6088 // If mode WEBSITE_SUBCONTAINERSINLINE is on, or if we want to see an archived version of page
6089 if (getDolGlobalString('WEBSITE_SUBCONTAINERSINLINE') || !empty($filetplversion)) {
6090 // TODO Check file $filephp exists, if not create it.
6091
6092 //var_dump($filetpl);
6093 $filephp = $filetpl;
6094 if (!empty($filetplversion)) {
6095 $filephp = $filetplversion;
6096 }
6097
6098 // Get session info and obfuscate session cookie
6099 $savsessionname = session_name();
6100 $savsessionid = $_COOKIE[$savsessionname];
6101 $_COOKIE[$savsessionname] = 'obfuscatedcookie';
6102
6103 ob_start();
6104 try {
6105 $res = include $filephp; // Note that if file contains a fatal error (Example: declaration of a function that already exists), this may break code here
6106 if (empty($res)) {
6107 print "ERROR: Failed to include file '".$filephp."'. Try to edit and re-save page with this ID.";
6108 }
6109 } catch (Exception $e) {
6110 print $e->getMessage();
6111 }
6112 $newcontent = ob_get_contents();
6113 ob_end_clean();
6114
6115
6116 // Restore data
6117 $_COOKIE[$savsessionname] = $savsessionid;
6118 }
6119
6120 // Change the contenteditable to "true" or "false" when mode Edit Inline is on or off
6121 // Note: We always remove the contenteditable when an archived version of page is displayed to avoid
6122 // editing the current page from an old version.
6123 if (!getDolGlobalString('WEBSITE_EDITINLINE') || !empty($filetplversion)) {
6124 // Remove the contenteditable="true"
6125 $newcontent = preg_replace('/(<[a-z][a-z0-9]*\s[^>]*)contenteditable="true"/i', '\1', $newcontent);
6126 } else {
6127 // Keep the contenteditable="true" when mode Edit Inline is on
6128 }
6129 $out .= dolWebsiteReplacementOfLinks($object, $newcontent, 0, 'html', $objectpage->id)."\n";
6130 //$out.=$newcontent;
6131
6132 $out .= '</div>'."\n";
6133
6134 $out .= '</div> <!-- End div id=websitecontentundertopmenu -->'."\n";
6135
6136 /*if ($includepageintoaframeoradiv == 'iframe')
6137 {
6138 $out .= "</body></html></iframe>";
6139 }*/
6140 $out .= "\n</body></html>\n";
6141
6142 $out .= "\n".'<!-- End page content '.$filetpl.' -->'."\n\n";
6143
6144 print $out;
6145
6146 /*
6147 file_put_contents($filetpl, $out);
6148 dolChmod($filetpl);
6149
6150 // Output file on browser
6151 dol_syslog("index.php include $filetpl $filename content-type=$type");
6152 $original_file_osencoded=dol_osencode($filetpl); // New file name encoded in OS encoding charset
6153
6154 // This test if file exists should be useless. We keep it to find bug more easily
6155 if (! file_exists($original_file_osencoded))
6156 {
6157 dol_print_error(0,$langs->trans("ErrorFileDoesNotExists",$original_file));
6158 exit;
6159 }
6160
6161 //include_once $original_file_osencoded;
6162 */
6163
6164 /*print '<iframe class="websiteiframenoborder centpercent" src="'.DOL_URL_ROOT.'/public/website/index.php?website='.$websitekey.'&pageid='.$pageid.'"/>';
6165 print '</iframe>';*/
6166 } else {
6167 if (empty($websitekey) || $websitekey == '-1') {
6168 print '<br><br><div class="center previewnotyetavailable"><span class="">'.$langs->trans("NoWebSiteCreateOneFirst").'</span></div><br><br><br>';
6169 print '<div class="center"><div class="logo_setup"></div></div>';
6170 } else {
6171 print '<br><br><div class="center previewnotyetavailable"><span class="">'.$langs->trans("PreviewOfSiteNotYetAvailable", $object->ref).'</span></div><br><br><br>';
6172 print '<div class="center"><div class="logo_setup"></div></div>';
6173 }
6174 }
6175}
6176
6177// End of page
6178llxFooter();
6179$db->close();
write(string $newInnerBlock)
Replace the whole permissions block, markers included, in a single write.
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
global $dolibarr_main_url_root
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
dolibarr_set_const($db, $name, $value, $type='chaine', $visible=0, $note='', $entity=1)
Insert a parameter (key,value) into database (delete old key then insert it again).
dolibarr_del_const($db, $name, $entity=1)
Delete a constant.
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='', $placeholder='')
Convert a html select field into an ajax combobox.
Definition ajax.lib.php:488
ajax_object_onoff($object, $code, $field, $text_on, $text_off, $input=array(), $morecss='', $htmlname='', $forcenojs=0, $moreparam='', $readonly=0)
On/off button to change a property status of an object This uses the ajax service objectonoff....
Definition ajax.lib.php:827
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
$c
Definition line.php:353
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage categories.
Class to manage a WYSIWYG editor.
Class to generate html code for admin pages.
Class to manage generation of HTML components Only common components must be here.
Class to manage a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
Class to help generate other html components Only common components are here.
Class to manage component html for module website.
The LESS compiler and parser.
Class to manage Dolibarr users.
Class Website.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
if(! $sortfield) if(! $sortorder) $module
Definition list.php:193
getAllImages($object, $objectpage, $urltograb, &$tmp, &$action, $modifylinks=0, $grabimages=1, $grabimagesinto='subpage')
Download all images found into an external URL.
dolStripPhpCode($str, $replacewith='')
Remove PHP code part from a string.
dolWebsiteReplacementOfLinks($website, $content, $removephppart=0, $contenttype='html', $containerid=0)
Convert a page content to have correct links (based on DOL_URL_ROOT) into an html content.
dolWebsiteGetEditInlineElements($content)
Return the elements with contenteditable="true" and an id found into the source of a page,...
dolKeepOnlyPhpCode($str)
Keep only PHP code part from a HTML string page.
dol_add_file_process($upload_dir, $allowoverwrite=0, $updatesessionordb=0, $keyforsourcefile='addedfile', $savingdocmask='', $link=null, $trackid='', $generatethumbs=1, $object=null, $forceFullTextIndexation='', $mode=0)
Get and save an upload file (for example after submitting a new file in a mail form).
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_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
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_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dol_nl2br($stringtoencode, $nl2brmode=0, $forxml=false)
Replace CRLF in string with a HTML BR tag.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dolChmod($filepath, $newmask='')
Change mod of a file.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into JavaScript code.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_htmlentities($string, $flags=ENT_QUOTES|ENT_SUBSTITUTE, $encoding='UTF-8', $double_encode=false)
Replace htmlentities functions.
dol_sanitizeUrl($stringtoclean, $type=1)
Clean a string to use it as an URL (into a href or src attribute, or into a js string that is a locat...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
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).
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
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)
getDomainFromURL($url, $mode=0)
Function get second level domain name.
getRootURLFromURL($url)
Function root url from a long url For example: https://www.abc.mydomain.com/dir/page....
removeHtmlComment($content)
Function to remove comments into HTML content.
getURLContent($url, $postorget='GET', $param='', $followlocation=1, $addheaders=array(), $allowedschemes=array('http', 'https'), $localurl=0, $ssl_verifypeer=-1, $timeoutconnect=0, $timeoutresponse=0, $otherCurlOptions=array(), $morelogsuffix='')
Function to get a content from an URL (use proxy if proxy defined).
picto_from_langcode($codelang, $moreatt='', $notitlealt=0)
Return img flag of country for a language code or country code.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
Definition html.lib.php:542
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition html.lib.php:740
img_previous($titlealt='default', $moreatt='')
Show previous logo.
getTitleFieldOfList($name, $thead=0, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="", $prefix="", $disablesortlink=0, $tooltip='', $forcenowrapcolumntitle=0)
Get title line of an array.
img_next($titlealt='default', $moreatt='')
Show next logo.
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='', $textonpictotooltip='', $cssfordropdown='info_admin')
Show information in HTML for admin users or standard users.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:165
getMaxFileSizeArray()
Return the max allowed for file upload.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.
if(empty( $takeposterminal)) fail($message)
Abort invoice creation with a given error message.
Definition invoice.php:125
multi select button
0 = Do not include form tag and submit button -1 = Do not include form tag but include submit button
a disabled
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.
websiteGetContentPolicyDirectives()
Prepare array of directives for Website.
websiteGetContentPolicySources()
Prepare array of sources for Website.
websiteGetContentPolicyToArray($forceCSP)
Transform a Content Security Policy to an array.
websiteconfigPrepareHead($object)
Prepare array of tabs for Website.