dolibarr 25.0.0-alpha
website.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2007-2018 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2014 Juanjo Menent <jmenent@2byte.es>
4 * Copyright (C) 2015 Florian Henry <florian.henry@open-concept.pro>
5 * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
6 * Copyright (C) 2018-2026 Frédéric France <frederic.france@free.fr>
7 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
29// Put here all includes required by your class file
30require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
31//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
32//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
33
34
38class Website extends CommonObject
39{
43 public $element = 'website';
44
48 public $table_element = 'website';
49
53 protected $childtablesoncascade = array();
54
58 public $picto = 'globe';
59
63 public $ref;
64
68 public $description;
69
73 public $lang;
74
78 public $otherlang;
79
83 public $status;
84
88 public $fk_default_home;
89
93 public $fk_user_creat;
94
98 public $fk_user_modif;
99
103 public $virtualhost;
104
108 public $use_manifest;
109
113 public $position;
114
118 public $name_template;
119
120 const STATUS_DRAFT = 0;
121 const STATUS_VALIDATED = 1;
122
123
129 public function __construct(DoliDB $db)
130 {
131 $this->db = $db;
132
133 $this->ismultientitymanaged = 1;
134 }
135
143 public function create(User $user, $notrigger = 0)
144 {
145 global $conf, $langs;
146
147 dol_syslog(__METHOD__, LOG_DEBUG);
148
149 $error = 0;
150 $now = dol_now();
151
152 // Clean parameters
153 if (isset($this->entity)) {
154 $this->entity = (int) $this->entity;
155 }
156 if (isset($this->ref)) {
157 $this->ref = trim($this->ref);
158 }
159 if (isset($this->description)) {
160 $this->description = trim($this->description);
161 }
162 if (isset($this->status)) {
163 $this->status = (int) $this->status;
164 }
165 if (empty($this->date_creation)) {
166 $this->date_creation = $now;
167 }
168 if (empty($this->date_modification)) {
169 $this->date_modification = $now;
170 }
171 // Remove spaces and be sure we have main language only
172 $this->lang = preg_replace('/[_-].*$/', '', trim((string) $this->lang)); // en_US or en-US -> en
173 $tmparray = explode(',', $this->otherlang);
174 if (is_array($tmparray)) {
175 foreach ($tmparray as $key => $val) {
176 // It possible we have empty val here if postparam WEBSITE_OTHERLANG is empty or set like this : 'en,,sv' or 'en,sv,'
177 if (empty(trim($val))) {
178 unset($tmparray[$key]);
179 continue;
180 }
181 $tmparray[$key] = preg_replace('/[_-].*$/', '', trim($val)); // en_US or en-US -> en
182 }
183 $this->otherlang = implode(',', $tmparray);
184 }
185
186 // Check parameters
187 if (empty($this->entity)) {
188 $this->entity = $conf->entity;
189 }
190 if (empty($this->lang)) {
191 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MainLanguage"));
192 return -1;
193 }
194
195 $pathofwebsite = $conf->website->dir_output.'/'.$this->ref;
196
197 // Insert request
198 $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.'(';
199 $sql .= 'entity,';
200 $sql .= 'ref,';
201 $sql .= 'description,';
202 $sql .= 'lang,';
203 $sql .= 'otherlang,';
204 $sql .= 'status,';
205 $sql .= 'fk_default_home,';
206 $sql .= 'virtualhost,';
207 $sql .= 'fk_user_creat,';
208 $sql .= 'date_creation,';
209 $sql .= 'position,';
210 $sql .= 'tms';
211 $sql .= ') VALUES (';
212 $sql .= ' '.((empty($this->entity) && $this->entity != '0') ? 'NULL' : ((int) $this->entity)).',';
213 $sql .= ' '.(!isset($this->ref) ? 'NULL' : "'".$this->db->escape($this->ref)."'").',';
214 $sql .= ' '.(!isset($this->description) ? 'NULL' : "'".$this->db->escape($this->description)."'").',';
215 $sql .= ' '.(!isset($this->lang) ? 'NULL' : "'".$this->db->escape($this->lang)."'").',';
216 $sql .= ' '.(!isset($this->otherlang) ? 'NULL' : "'".$this->db->escape($this->otherlang)."'").',';
217 $sql .= ' '.(!isset($this->status) ? '1' : ((int) $this->status)).',';
218 $sql .= ' '.(!isset($this->fk_default_home) ? 'NULL' : ((int) $this->fk_default_home)).',';
219 $sql .= ' '.(!isset($this->virtualhost) ? 'NULL' : "'".$this->db->escape($this->virtualhost)."'").",";
220 $sql .= ' '.(!isset($this->fk_user_creat) ? ((int) $user->id) : ((int) $this->fk_user_creat)).',';
221 $sql .= ' '.(!isset($this->date_creation) || dol_strlen((string) $this->date_creation) == 0 ? 'NULL' : "'".$this->db->idate($this->date_creation)."'").",";
222 $sql .= ' '.((int) $this->position).",";
223 $sql .= ' '.(!isset($this->date_modification) || dol_strlen((string) $this->date_modification) == 0 ? 'NULL' : "'".$this->db->idate($this->date_modification)."'");
224 $sql .= ')';
225
226 $this->db->begin();
227
228 $resql = $this->db->query($sql);
229 if (!$resql) {
230 $error++;
231 $this->errors[] = 'Error '.$this->db->lasterror();
232 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
233 }
234
235 if (!$error) {
236 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
237
238 // Create a subdirectory for each language (except main language)
239 $tmplangarray = explode(',', $this->otherlang);
240 if (is_array($tmplangarray)) {
241 dol_mkdir($conf->website->dir_output.'/'.$this->ref);
242 foreach ($tmplangarray as $val) {
243 if (trim($val) == $this->lang) {
244 continue;
245 }
246 dol_mkdir($conf->website->dir_output.'/'.$this->ref.'/'.trim($val), DOL_DATA_ROOT);
247 }
248 }
249
250 // Create subdirectory for images and js into documents/medias directory
251 dol_mkdir($conf->medias->multidir_output[$conf->entity].'/image/'.$this->ref, DOL_DATA_ROOT);
252 dol_mkdir($conf->medias->multidir_output[$conf->entity].'/js/'.$this->ref, DOL_DATA_ROOT);
253
254 // Check symlink documents/website/mywebsite/medias to point to documents/medias and restore it if ko.
255 // Recreate also dir of website if not found.
256 $pathtomedias = DOL_DATA_ROOT.'/medias';
257 $pathtomediasinwebsite = $pathofwebsite.'/medias';
258 if (!is_link(dol_osencode($pathtomediasinwebsite))) {
259 dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite);
260 dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure that the directory for website exists
261 $result = symlink($pathtomedias, $pathtomediasinwebsite);
262 if (!$result) {
263 $langs->load("errors");
264 //setEventMessages($langs->trans("ErrorFailedToCreateSymLinkToMedias", $pathtomediasinwebsite, $pathtomedias), null, 'errors');
265 $error++;
266 }
267 }
268
269 // if (!$notrigger) {
270 // // Call triggers
271 // $result = $this->call_trigger('WEBSITE_CREATE',$user);
272 // if ($result < 0) $error++;
273 // // End call triggers
274 // }
275 }
276
277 if (!$error) {
278 $stringtodolibarrfile = "# Some properties for Dolibarr web site CMS\n";
279 $stringtodolibarrfile .= "param=value\n";
280 //print $conf->website->dir_output.'/'.$this->ref.'/.dolibarr';exit;
281 file_put_contents($pathofwebsite.'/.dolibarr', $stringtodolibarrfile);
282 dolChmod($pathofwebsite.'/.dolibarr');
283
284 $filelicense = $pathofwebsite.'/LICENSE';
285 if (!dol_is_file($filelicense)) {
286 $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/";
287 $result = dolSaveLicense($filelicense, $licensecontent);
288 }
289 }
290
291 // Commit or rollback
292 if ($error) {
293 $this->db->rollback();
294 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
295 return 0;
296 } else {
297 return -1 * $error;
298 }
299 } else {
300 $this->db->commit();
301
302 return $this->id;
303 }
304 }
305
313 public function fetch($id, $ref = null)
314 {
315 dol_syslog(__METHOD__, LOG_DEBUG);
316
317 $sql = "SELECT";
318 $sql .= " t.rowid,";
319 $sql .= " t.entity,";
320 $sql .= " t.ref,";
321 $sql .= " t.position,";
322 $sql .= " t.description,";
323 $sql .= " t.lang,";
324 $sql .= " t.otherlang,";
325 $sql .= " t.status,";
326 $sql .= " t.fk_default_home,";
327 $sql .= " t.use_manifest,";
328 $sql .= " t.virtualhost,";
329 $sql .= " t.fk_user_creat,";
330 $sql .= " t.fk_user_modif,";
331 $sql .= " t.date_creation,";
332 $sql .= " t.tms as date_modification,";
333 $sql .= " t.name_template";
334 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
335 $sql .= " WHERE t.entity IN (".getEntity('website').")";
336 if (!empty($ref)) {
337 $sql .= " AND t.ref = '".$this->db->escape($ref)."'";
338 } else {
339 $sql .= " AND t.rowid = ".(int) $id;
340 }
341
342 $resql = $this->db->query($sql);
343 if ($resql) {
344 $numrows = $this->db->num_rows($resql);
345 if ($numrows) {
346 $obj = $this->db->fetch_object($resql);
347
348 $this->id = $obj->rowid;
349
350 $this->entity = $obj->entity;
351 $this->ref = $obj->ref;
352 $this->position = $obj->position;
353 $this->description = $obj->description;
354 $this->lang = $obj->lang;
355 $this->otherlang = $obj->otherlang;
356 $this->status = $obj->status;
357 $this->fk_default_home = $obj->fk_default_home;
358 $this->virtualhost = $obj->virtualhost;
359 $this->use_manifest = $obj->use_manifest;
360 $this->fk_user_creat = $obj->fk_user_creat;
361 $this->fk_user_modif = $obj->fk_user_modif;
362 $this->date_creation = $this->db->jdate($obj->date_creation);
363 $this->date_modification = $this->db->jdate($obj->date_modification);
364 $this->name_template = $obj->name_template;
365 }
366 $this->db->free($resql);
367
368 if ($numrows > 0) {
369 return 1;
370 } else {
371 return 0;
372 }
373 } else {
374 $this->errors[] = 'Error '.$this->db->lasterror();
375 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
376
377 return -1;
378 }
379 }
380
381
393 public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND')
394 {
395 dol_syslog(__METHOD__, LOG_DEBUG);
396
397 $records = array();
398
399 $sql = "SELECT";
400 $sql .= " t.rowid,";
401 $sql .= " t.entity,";
402 $sql .= " t.ref,";
403 $sql .= " t.description,";
404 $sql .= " t.lang,";
405 $sql .= " t.otherlang,";
406 $sql .= " t.status,";
407 $sql .= " t.fk_default_home,";
408 $sql .= " t.virtualhost,";
409 $sql .= " t.fk_user_creat,";
410 $sql .= " t.fk_user_modif,";
411 $sql .= " t.date_creation,";
412 $sql .= " t.tms as date_modification";
413 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
414 $sql .= " WHERE t.entity IN (".getEntity('website').")";
415
416 // Manage filter
417 if (is_array($filter)) {
418 $sqlwhere = array();
419 if (count($filter) > 0) {
420 foreach ($filter as $key => $value) {
421 $sqlwhere[] = $this->db->sanitize($key)." LIKE '%".$this->db->escape($value)."%'";
422 }
423 }
424 if (count($sqlwhere) > 0) {
425 $sql .= ' AND '.implode(' '.$this->db->sanitize($filtermode).' ', $sqlwhere);
426 }
427
428 $filter = '';
429 }
430
431 // Manage filter
432 $errormessage = '';
433 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
434 if ($errormessage) {
435 $this->errors[] = $errormessage;
436 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
437 return -1;
438 }
439
440 if (!empty($sortfield)) {
441 $sql .= $this->db->order($sortfield, $sortorder);
442 }
443 if (!empty($limit)) {
444 $sql .= $this->db->plimit($limit, $offset);
445 }
446
447 $resql = $this->db->query($sql);
448 if ($resql) {
449 $num = $this->db->num_rows($resql);
450
451 while ($obj = $this->db->fetch_object($resql)) {
452 $record = new self($this->db);
453
454 $record->id = $obj->rowid;
455
456 $record->entity = $obj->entity;
457 $record->ref = $obj->ref;
458 $record->description = $obj->description;
459 $record->lang = $obj->lang;
460 $record->otherlang = $obj->otherlang;
461 $record->status = $obj->status;
462 $record->fk_default_home = $obj->fk_default_home;
463 $record->virtualhost = $obj->virtualhost;
464 $record->fk_user_creat = $obj->fk_user_creat;
465 $record->fk_user_modif = $obj->fk_user_modif;
466 $record->date_creation = $this->db->jdate($obj->date_creation);
467 $record->date_modification = $this->db->jdate($obj->date_modification);
468
469 $records[$record->id] = $record;
470 }
471 $this->db->free($resql);
472
473 return $records;
474 } else {
475 $this->errors[] = 'Error '.$this->db->lasterror();
476 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
477
478 return -1;
479 }
480 }
481
489 public function update(User $user, $notrigger = 0)
490 {
491 global $conf, $langs;
492
493 $error = 0;
494
495 dol_syslog(__METHOD__, LOG_DEBUG);
496
497 // Clean parameters
498
499 if (isset($this->entity)) {
500 $this->entity = (int) $this->entity;
501 }
502 if (isset($this->ref)) {
503 $this->ref = trim($this->ref);
504 }
505 if (isset($this->description)) {
506 $this->description = trim($this->description);
507 }
508 if (isset($this->status)) {
509 $this->status = (int) $this->status;
510 }
511
512 // Remove spaces and be sure we have main language only
513 $this->lang = preg_replace('/[_-].*$/', '', trim((string) $this->lang)); // en_US or en-US -> en
514 $tmparray = explode(',', $this->otherlang);
515 if (is_array($tmparray)) {
516 foreach ($tmparray as $key => $val) {
517 // It possible we have empty val here if postparam WEBSITE_OTHERLANG is empty or set like this : 'en,,sv' or 'en,sv,'
518 if (empty(trim($val))) {
519 unset($tmparray[$key]);
520 continue;
521 }
522 $tmparray[$key] = preg_replace('/[_-].*$/', '', trim($val)); // en_US or en-US -> en
523 }
524 $this->otherlang = implode(',', $tmparray);
525 }
526 if (empty($this->lang)) {
527 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MainLanguage"));
528 return -1;
529 }
530
531 // Check parameters
532 // Put here code to add a control on parameters values
533
534 // Update request
535 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
536 $sql .= ' entity = '.(isset($this->entity) ? ((int) $this->entity) : "null").',';
537 $sql .= ' ref = '.(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").',';
538 $sql .= ' description = '.(isset($this->description) ? "'".$this->db->escape($this->description)."'" : "null").',';
539 $sql .= ' lang = '.(isset($this->lang) ? "'".$this->db->escape($this->lang)."'" : "null").',';
540 $sql .= ' otherlang = '.(isset($this->otherlang) ? "'".$this->db->escape($this->otherlang)."'" : "null").',';
541 $sql .= ' status = '.(isset($this->status) ? ((int) $this->status) : "null").',';
542 $sql .= ' fk_default_home = '.(($this->fk_default_home > 0) ? ((int) $this->fk_default_home) : "null").',';
543 $sql .= ' use_manifest = '.((int) $this->use_manifest).',';
544 $sql .= ' virtualhost = '.(($this->virtualhost != '') ? "'".$this->db->escape($this->virtualhost)."'" : "null").',';
545 $sql .= ' fk_user_modif = '.(!isset($this->fk_user_modif) ? ((int) $user->id) : ((int) $this->fk_user_modif)).',';
546 $sql .= ' date_creation = '.(!isset($this->date_creation) || dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').',';
547 $sql .= ' tms = '.(dol_strlen($this->date_modification) != 0 ? "'".$this->db->idate($this->date_modification)."'" : "'".$this->db->idate(dol_now())."'");
548 $sql .= ' WHERE rowid='.((int) $this->id);
549
550 $this->db->begin();
551
552 $resql = $this->db->query($sql);
553 if (!$resql) {
554 $error++;
555 $this->errors[] = 'Error '.$this->db->lasterror();
556 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
557 }
558
559 if (!$error && !$notrigger) {
560 // Uncomment this and change MYOBJECT to your own tag if you
561 // want this action calls a trigger.
562
563 // Create subdirectory per language
564 $tmplangarray = explode(',', $this->otherlang);
565 if (is_array($tmplangarray)) {
566 dol_mkdir($conf->website->dir_output.'/'.$this->ref);
567 foreach ($tmplangarray as $val) {
568 if (trim($val) == $this->lang) {
569 continue;
570 }
571 dol_mkdir($conf->website->dir_output.'/'.$this->ref.'/'.trim($val));
572 }
573 }
574
576 //$result=$this->call_trigger('WEBSITE_MODIFY',$user);
577 //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
579 }
580
581 // Commit or rollback
582 if ($error) {
583 $this->db->rollback();
584
585 return -1 * $error;
586 } else {
587 $this->db->commit();
588
589 return 1;
590 }
591 }
592
600 public function delete(User $user, $notrigger = 0)
601 {
602 global $conf;
603
604 dol_syslog(__METHOD__, LOG_DEBUG);
605
606 $error = 0;
607
608 $this->db->begin();
609
610 if (!$error) {
611 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'categorie_website_page';
612 $sql .= ' WHERE fk_website_page IN (SELECT rowid FROM '.MAIN_DB_PREFIX.'website_page WHERE fk_website = '.((int) $this->id).')';
613
614 $resql = $this->db->query($sql);
615 if (!$resql) {
616 $error++;
617 $this->errors[] = 'Error '.$this->db->lasterror();
618 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
619 }
620 }
621
622 if (!$error) {
623 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'website_page';
624 $sql .= ' WHERE fk_website = '.((int) $this->id);
625
626 $resql = $this->db->query($sql);
627 if (!$resql) {
628 $error++;
629 $this->errors[] = 'Error '.$this->db->lasterror();
630 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
631 }
632 }
633
634 // Delete common code. This include execution of trigger.
635 $result = $this->deleteCommon($user, $notrigger);
636 if ($result <= 0) {
637 $error++;
638 }
639
640 if (!$error && !empty($this->ref)) {
641 $pathofwebsite = DOL_DATA_ROOT.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.$this->ref;
642
643 dol_delete_dir_recursive($pathofwebsite);
644 }
645
646 // Commit or rollback
647 if ($error) {
648 $this->db->rollback();
649
650 return -1 * $error;
651 } else {
652 $this->db->commit();
653
654 return 1;
655 }
656 }
657
665 public function purge(User $user)
666 {
667 global $conf, $langs;
668
669 dol_syslog(__METHOD__, LOG_DEBUG);
670
671 $error = 0;
672
673 $this->db->begin();
674
675 if (!$error) {
676 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'website_page';
677 $sql .= ' WHERE fk_website = '.((int) $this->id);
678
679 $resql = $this->db->query($sql);
680 if (!$resql) {
681 $error++;
682 $this->errors[] = 'Error '.$this->db->lasterror();
683 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
684 }
685 }
686
687 if (!$error && !empty($this->ref)) {
688 $pathofwebsite = DOL_DATA_ROOT.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.$this->ref;
689 // Delete content of website directory without deleting the website directory
690 dol_delete_dir_recursive($pathofwebsite, 0, 0, 1);
691
692 // Check symlink documents/website/mywebsite/medias to point to documents/medias and restore it if ko.
693 // Recreate also dir of website if not found.
694 $pathtomedias = DOL_DATA_ROOT.'/medias';
695 $pathtomediasinwebsite = $pathofwebsite.'/medias';
696 if (!is_link(dol_osencode($pathtomediasinwebsite))) {
697 dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite);
698 dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure that the directory for website exists
699 $result = symlink($pathtomedias, $pathtomediasinwebsite);
700 if (!$result) {
701 $this->errors[] = $langs->trans("ErrorFailedToCreateSymLinkToMedias", $pathtomediasinwebsite, $pathtomedias);
702 $error++;
703 }
704 }
705 }
706
707 // Commit or rollback
708 if ($error) {
709 $this->db->rollback();
710
711 return -1 * $error;
712 } else {
713 $this->db->commit();
714
715 return 1;
716 }
717 }
718
729 public function createFromClone($user, $fromid, $newref, $newlang = '')
730 {
731 global $conf, $langs;
732 global $dolibarr_main_data_root;
733
734 $now = dol_now();
735 $error = 0;
736
737 dol_syslog(__METHOD__, LOG_DEBUG);
738
739 $newref = dol_sanitizeFileName($newref);
740
741 if (empty($newref)) {
742 $this->error = 'ErrorBadParameter newref';
743 return -1;
744 }
745
746 $object = new self($this->db);
747
748 // Check no site with ref exists
749 if ($object->fetch(0, $newref) > 0) {
750 $this->error = 'ErrorNewRefIsAlreadyUsed';
751 return -2;
752 }
753
754 $this->db->begin();
755
756 // Load source object
757 $object->fetch($fromid);
758
759 $oldidforhome = $object->fk_default_home;
760 $oldref = $object->ref;
761
762 $pathofwebsiteold = $dolibarr_main_data_root.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.dol_sanitizeFileName($oldref);
763 $pathofwebsitenew = $dolibarr_main_data_root.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.dol_sanitizeFileName($newref);
764 dol_delete_dir_recursive($pathofwebsitenew);
765
766 $fileindex = $pathofwebsitenew.'/index.php';
767
768 // Reset some properties
769 unset($object->id);
770 unset($object->fk_user_creat);
771 unset($object->import_key);
772
773 // Clear fields
774 $object->ref = $newref;
775 $object->fk_default_home = 0;
776 $object->virtualhost = '';
777 $object->date_creation = $now;
778 $object->fk_user_creat = $user->id;
779 $object->position = ((int) $object->position) + 1;
780 $object->status = self::STATUS_DRAFT;
781 if (empty($object->lang)) {
782 $object->lang = substr($langs->defaultlang, 0, 2); // Should not happen. Protection for corrupted site with no languages
783 }
784
785 // Create clone
786 $object->context['createfromclone'] = 'createfromclone';
787 $result = $object->create($user);
788 if ($result < 0) {
789 $error++;
791 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
792 }
793
794 $newidforhome = 0;
795
796 if (!$error) {
797 // @phan-suppress-next-line PhanPluginSuspiciousParamOrder
798 dolCopyDir($pathofwebsiteold, $pathofwebsitenew, getDolGlobalString('MAIN_UMASK'), 0, [], 2);
799
800 // Check symlink to medias and restore it if ko
801 $pathtomedias = DOL_DATA_ROOT.'/medias'; // Target
802 $pathtomediasinwebsite = $pathofwebsitenew.'/medias'; // Source / Link name
803 if (!is_link(dol_osencode($pathtomediasinwebsite))) {
804 dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite);
805 dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists
806 $result = symlink($pathtomedias, $pathtomediasinwebsite);
807 }
808
809 // Copy images and js dir
810 $pathofmediasjsold = DOL_DATA_ROOT.'/medias/js/'.$oldref;
811 $pathofmediasjsnew = DOL_DATA_ROOT.'/medias/js/'.$newref;
812 dolCopyDir($pathofmediasjsold, $pathofmediasjsnew, getDolGlobalString('MAIN_UMASK'), 0);
813
814 $pathofmediasimageold = DOL_DATA_ROOT.'/medias/image/'.$oldref;
815 $pathofmediasimagenew = DOL_DATA_ROOT.'/medias/image/'.$newref;
816 dolCopyDir($pathofmediasimageold, $pathofmediasimagenew, getDolGlobalString('MAIN_UMASK'), 0);
817
818 // Duplicate pages
819 $objectpages = new WebsitePage($this->db);
820 $listofpages = $objectpages->fetchAll($fromid);
821 foreach ($listofpages as $pageid => $objectpageold) {
822 // Delete old file
823 $filetplold = $pathofwebsitenew.'/page'.$pageid.'.tpl.php';
824 dol_delete_file($filetplold);
825
826 // Create new file
827 $objectpagenew = $objectpageold->createFromClone($user, $pageid, $objectpageold->pageurl, '', 0, $object->id, '1');
828
829 //print $pageid.' = '.$objectpageold->pageurl.' -> '.$objectpagenew->id.' = '.$objectpagenew->pageurl.'<br>';
830 if (is_object($objectpagenew) && $objectpagenew->pageurl) {
831 $filealias = $pathofwebsitenew.'/'.$objectpagenew->pageurl.'.php';
832 $filetplnew = $pathofwebsitenew.'/page'.$objectpagenew->id.'.tpl.php';
833
834 // Save page alias
835 $result = dolSavePageAlias($filealias, $object, $objectpagenew);
836 if (!$result) {
837 $this->error = 'Failed to write file '.$filealias;
838 $this->errors[] = $this->error;
839 $error++;
840 }
841
842 $result = dolSavePageContent($filetplnew, $object, $objectpagenew);
843 if (!$result) {
844 $this->error = 'Failed to write file '.$filetplnew;
845 $this->errors[] = $this->error;
846 $error++;
847 }
848
849 if ($pageid == $oldidforhome) {
850 $newidforhome = $objectpagenew->id;
851 }
852 } else {
853 $this->setErrorsFromObject($objectpageold);
854 $error++;
855 }
856 }
857 }
858
859 if (!$error) {
860 // Restore id of home page
861 $object->fk_default_home = $newidforhome;
862 $res = $object->update($user);
863 if (!($res > 0)) {
864 $error++;
866 }
867
868 if (!$error) {
869 $filetpl = $pathofwebsitenew.'/page'.$newidforhome.'.tpl.php';
870 $filewrapper = $pathofwebsitenew.'/wrapper.php';
871
872 // Re-generates the index.php page to be the home page, and re-generates the wrapper.php
873 //--------------------------------------------------------------------------------------
874 $result = dolSaveIndexPage($pathofwebsitenew, $fileindex, $filetpl, $filewrapper, $object);
875 }
876 }
877
878 unset($object->context['createfromclone']);
879
880 // End
881 if (!$error) {
882 $this->db->commit();
883
884 return $object;
885 } else {
886 $this->db->rollback();
887
888 return -3;
889 }
890 }
891
903 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $maxlen = 24, $morecss = '')
904 {
905 global $langs;
906
907 $result = '';
908
909 $label = '<u>'.img_picto('', 'website', 'class="pictofixedwidth"').$langs->trans("WebSite").'</u>';
910 $label .= '<br>';
911 $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref.'<br>';
912 $label .= '<b>'.$langs->trans('MainLanguage').':</b> '.$this->lang;
913
914 // Links for internal access
915 /*
916 $linkstart = '<a href="'.DOL_URL_ROOT.'/website/index.php?website='.urlencode($this->ref).'"';
917 $linkstart .= ($notooltip ? '' : ' title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip'.($morecss ? ' '.$morecss : '').'"');
918 $linkstart .= '>';
919 */
920 if (!empty($this->virtualhost)) {
921 $linkstart = '<a target="_blank" rel="noopener" href="'.$this->virtualhost.'">';
922 $linkend = '</a>';
923 } else {
924 $linkstart = $linkend = '';
925 }
926
927 $result .= $linkstart;
928 if ($withpicto) {
929 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), 'class="pictofixedwidth'.($notooltip ? '' : ' classfortooltip').'"');
930 }
931 $result .= $this->ref;
932 $result .= $linkend;
933
934 return $result;
935 }
936
943 public function getLibStatut($mode = 0)
944 {
945 return $this->LibStatut($this->status, $mode);
946 }
947
948 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
956 public function LibStatut($status, $mode = 0)
957 {
958 // phpcs:enable
959 global $langs;
960
961 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
962 global $langs;
963 //$langs->load("mymodule");
964 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Offline');
965 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Online');
966 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Offline');
967 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Online');
968 }
969
970 $statusType = 'status5';
971 if ($status == self::STATUS_VALIDATED) {
972 $statusType = 'status4';
973 }
974
975 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
976 }
977
978
985 public function initAsSpecimen()
986 {
987 global $user;
988
989 $this->id = 0;
990 $this->specimen = 1;
991 $this->entity = 1;
992 $this->ref = 'myspecimenwebsite';
993 $this->description = 'A specimen website';
994 $this->lang = 'en';
995 $this->otherlang = 'fr,es';
996 $this->status = 1;
997 $this->fk_default_home = 0;
998 $this->virtualhost = 'http://myvirtualhost';
999 $this->fk_user_creat = $user->id;
1000 $this->fk_user_modif = $user->id;
1001 $this->date_creation = dol_now();
1002 $this->tms = dol_now();
1003
1004 return 1;
1005 }
1006
1007
1014 public function exportWebSite()
1015 {
1016 global $conf, $mysoc;
1017
1018 $website = $this;
1019
1020 if (empty($website->id) || empty($website->ref)) {
1021 $this->error = "Website id or ref is not defined";
1022 $this->errors[] = $this->error;
1023 return '';
1024 }
1025
1026 dol_syslog("Create temp dir ".$conf->website->dir_temp);
1027 dol_mkdir($conf->website->dir_temp);
1028 if (!is_writable($conf->website->dir_temp)) {
1029 $this->error = "Temporary dir ".$conf->website->dir_temp." is not writable";
1030 $this->errors[] = $this->error;
1031 return '';
1032 }
1033
1034 $destdir = $conf->website->dir_temp.'/'.$website->ref;
1035 dol_syslog("Clear temp dir ".$destdir);
1036 $count = 0;
1037 $countreallydeleted = 0;
1038 $counttodelete = dol_delete_dir_recursive($destdir, $count, 1, 0, $countreallydeleted);
1039 if ($counttodelete != $countreallydeleted) {
1040 $this->error = "Failed to clean temp directory ".$destdir;
1041 $this->errors[] = $this->error;
1042 return '';
1043 }
1044
1045 $arrayreplacementinfilename = array();
1046 $arrayreplacementincss = array();
1047 $arrayreplacementincss['file=image/'.$website->ref.'/'] = "file=image/__WEBSITE_KEY__/";
1048 $arrayreplacementincss['file=js/'.$website->ref.'/'] = "file=js/__WEBSITE_KEY__/";
1049 $arrayreplacementincss['medias/image/'.$website->ref.'/'] = "medias/image/__WEBSITE_KEY__/";
1050 $arrayreplacementincss['medias/js/'.$website->ref.'/'] = "medias/js/__WEBSITE_KEY__/";
1051 if ($mysoc->logo_small) {
1052 $arrayreplacementincss['file=logos%2Fthumbs%2F'.$mysoc->logo_small] = "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__";
1053 }
1054 if ($mysoc->logo_mini) {
1055 $arrayreplacementincss['file=logos%2Fthumbs%2F'.$mysoc->logo_mini] = "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__";
1056 }
1057 if ($mysoc->logo) {
1058 $arrayreplacementincss['file=logos%2Fthumbs%2F'.$mysoc->logo] = "file=logos%2Fthumbs%2F__LOGO_KEY__";
1059 }
1060
1061 // Create output directories
1062 dol_syslog("Create containers dir");
1063 dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/containers');
1064 dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/medias/image/websitekey');
1065 dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/medias/js/websitekey');
1066
1067 // Copy files into 'containers'
1068 $srcdir = $conf->website->dir_output.'/'.$website->ref;
1069 $destdir = $conf->website->dir_temp.'/'.$website->ref.'/containers';
1070
1071 dol_syslog("Copy pages from ".$srcdir." into ".$destdir);
1072 dolCopyDir($srcdir, $destdir, '0', 1, $arrayreplacementinfilename, 2, array('old', 'back'), 1);
1073
1074 // Remove non required files (will be re-generated during the import)
1075 dol_delete_file($conf->website->dir_temp.'/'.$website->ref.'/containers/master.inc.php');
1076
1077 // Copy file README.md and LICENSE from directory containers into directory root
1078 if (dol_is_file($conf->website->dir_temp.'/'.$website->ref.'/containers/README.md')) {
1079 dol_copy($conf->website->dir_temp.'/'.$website->ref.'/containers/README.md', $conf->website->dir_temp.'/'.$website->ref.'/README.md');
1080 }
1081 if (dol_is_file($conf->website->dir_temp.'/'.$website->ref.'/containers/LICENSE')) {
1082 dol_copy($conf->website->dir_temp.'/'.$website->ref.'/containers/LICENSE', $conf->website->dir_temp.'/'.$website->ref.'/LICENSE');
1083 }
1084
1085 // Copy files into medias/image
1086 $srcdir = DOL_DATA_ROOT.'/medias/image/'.$website->ref;
1087 $destdir = $conf->website->dir_temp.'/'.$website->ref.'/medias/image/websitekey';
1088
1089 dol_syslog("Copy content from ".$srcdir." into ".$destdir);
1090 dolCopyDir($srcdir, $destdir, '0', 1, $arrayreplacementinfilename);
1091
1092 // Copy files into medias/js
1093 $srcdir = DOL_DATA_ROOT.'/medias/js/'.$website->ref;
1094 $destdir = $conf->website->dir_temp.'/'.$website->ref.'/medias/js/websitekey';
1095
1096 dol_syslog("Copy content from ".$srcdir." into ".$destdir);
1097 dolCopyDir($srcdir, $destdir, '0', 1, $arrayreplacementinfilename);
1098
1099 // Make some replacement into some files
1100 $cssindestdir = $conf->website->dir_temp.'/'.$website->ref.'/containers/styles.css.php';
1101 if (dol_is_file($cssindestdir)) {
1102 dolReplaceInFile($cssindestdir, $arrayreplacementincss);
1103 }
1104
1105 $htmldeaderindestdir = $conf->website->dir_temp.'/'.$website->ref.'/containers/htmlheader.html';
1106 if (dol_is_file($htmldeaderindestdir)) {
1107 dolReplaceInFile($htmldeaderindestdir, $arrayreplacementincss);
1108 }
1109
1110 // Build the website_page.sql file
1111 $filesql_path = $conf->website->dir_temp.'/'.$website->ref.'/website_pages.sql';
1112 $fp = fopen($filesql_path, "w");
1113 if (empty($fp)) {
1114 $this->error = "Failed to create file ".$filesql_path;
1115 $this->errors[] = $this->error;
1116 return '';
1117 }
1118
1119 $objectpages = new WebsitePage($this->db);
1120 $listofpages = $objectpages->fetchAll($website->id);
1121
1122
1123 // Assign ->newid and ->newfk_page starting at 1.
1124 $i = 1;
1125 foreach ($listofpages as $pageid => $objectpageold) {
1126 $objectpageold->newid = $i;
1127 $i++;
1128 }
1129 $i = 1;
1130 foreach ($listofpages as $pageid => $objectpageold) {
1131 // Search newid
1132 $newfk_page = 0;
1133 foreach ($listofpages as $pageid2 => $objectpageold2) {
1134 if ($pageid2 == $objectpageold->fk_page) {
1135 $newfk_page = $objectpageold2->newid;
1136 break;
1137 }
1138 }
1139 $objectpageold->newfk_page = $newfk_page;
1140 $i++;
1141 }
1142
1143 $line = '-- File generated by Dolibarr '.DOL_VERSION.' --;'."\n";
1144 $line .= "\n";
1145 fwrite($fp, $line);
1146
1147 foreach ($listofpages as $pageid => $objectpageold) {
1148 $oldpageid = $objectpageold->id;
1149
1150 $allaliases = $objectpageold->pageurl;
1151 $allaliases .= ($objectpageold->aliasalt ? ','.$objectpageold->aliasalt : '');
1152
1153 if (!getDolGlobalInt('WEBSITE_EXPORT_KEEP_FILES_OF_PAGES')) {
1154 // We don't need to keep the PHP files of pages and aliases (they are regenerated at import) so we remove them.
1155 // Delete the pageX.tpl.php page
1156 dol_delete_file($conf->website->dir_temp.'/'.$website->ref.'/containers/page'.$objectpageold->id.'.tpl.php', 0, 0, 0, null, false, 0);
1157 // Delete the alias page
1158 dol_delete_file($conf->website->dir_temp.'/'.$website->ref.'/containers/'.$objectpageold->pageurl.'.php', 0, 0, 0, null, false, 0);
1159 dol_delete_file($conf->website->dir_temp.'/'.$website->ref.'/containers/*/'.$objectpageold->pageurl.'.php', 0, 0, 0, null, false, 0);
1160 // Delete alternative alias pages
1161 $arrayofaliases = explode(',', $objectpageold->aliasalt);
1162 foreach ($arrayofaliases as $tmpaliasalt) {
1163 dol_delete_file($conf->website->dir_temp.'/'.$website->ref.'/containers/'.trim($tmpaliasalt).'.php', 0, 0, 0, null, false, 0);
1164 dol_delete_file($conf->website->dir_temp.'/'.$website->ref.'/containers/*/'.trim($tmpaliasalt).'.php', 0, 0, 0, null, false, 0);
1165 }
1166 }
1167
1168 // This comment syntax is important, it is parsed by import to get information on page ID and all aliases to regenerate
1169 $line = '-- Page ID '.$objectpageold->newid.'__+MAX_llx_website_page__ - Aliases '.$allaliases.' --;'; // newid start at 1, 2...
1170 $line .= "\n";
1171 fwrite($fp, $line);
1172
1173 // Warning: We must keep llx_ here. It is a generic SQL.
1174 $line = 'INSERT INTO llx_website_page(rowid, fk_page, fk_website, pageurl, aliasalt, title, description, lang, image, keywords, status, date_creation, tms, import_key, grabbed_from, type_container, htmlheader, content, author_alias, allowed_in_frames)';
1175 $line .= " VALUES(";
1176 $line .= $objectpageold->newid."__+MAX_llx_website_page__, ";
1177 $line .= ($objectpageold->newfk_page ? $this->db->escape($objectpageold->newfk_page)."__+MAX_llx_website_page__" : "null").", ";
1178 $line .= "__WEBSITE_ID__, ";
1179 $line .= "'".$this->db->escape($objectpageold->pageurl)."', ";
1180 $line .= "'".$this->db->escape($objectpageold->aliasalt)."', ";
1181 $line .= "'".$this->db->escape($objectpageold->title)."', ";
1182 $line .= "'".$this->db->escape($objectpageold->description)."', ";
1183 $line .= "'".$this->db->escape($objectpageold->lang)."', ";
1184 $line .= "'".$this->db->escape($objectpageold->image)."', ";
1185 $line .= "'".$this->db->escape($objectpageold->keywords)."', ";
1186 $line .= "'".$this->db->escape((string) $objectpageold->status)."', ";
1187 $line .= "'".$this->db->idate($objectpageold->date_creation)."', ";
1188 $line .= "'".$this->db->idate($objectpageold->date_modification)."', ";
1189 $line .= ($objectpageold->import_key ? "'".$this->db->escape((string) $objectpageold->import_key)."'" : "null").", ";
1190 $line .= "'".$this->db->escape($objectpageold->grabbed_from)."', ";
1191 $line .= "'".$this->db->escape($objectpageold->type_container)."', ";
1192
1193 // Make substitution with a generic path into htmlheader content
1194 $stringtoexport = $objectpageold->htmlheader;
1195 $stringtoexport = str_replace(array("\r\n", "\r", "\n"), "__N__", $stringtoexport);
1196 $stringtoexport = str_replace('file=image/'.$website->ref.'/', "file=image/__WEBSITE_KEY__/", $stringtoexport);
1197 $stringtoexport = str_replace('file=js/'.$website->ref.'/', "file=js/__WEBSITE_KEY__/", $stringtoexport);
1198 $stringtoexport = str_replace('medias/image/'.$website->ref.'/', "medias/image/__WEBSITE_KEY__/", $stringtoexport);
1199 $stringtoexport = str_replace('medias/js/'.$website->ref.'/', "medias/js/__WEBSITE_KEY__/", $stringtoexport);
1200
1201 $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_small, "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__", $stringtoexport);
1202 $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_mini, "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__", $stringtoexport);
1203 $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo, "file=logos%2Fthumbs%2F__LOGO_KEY__", $stringtoexport);
1204
1205 if (getDolGlobalString('WEBSITE_EXPORT_SQL_ON_SEVERAL_LINES')) {
1206 $line .= "/* new line */\n"; // Add a comment so we will able to restore a one line instruction on import
1207 }
1208 $line .= "'".$this->db->escape($stringtoexport)."', ";
1209
1210 // Make substitution with a generic path into page content
1211 $stringtoexport = $objectpageold->content;
1212 $stringtoexport = str_replace(array("\r\n", "\r", "\n"), "__N__", $stringtoexport);
1213 $stringtoexport = str_replace('file=image/'.$website->ref.'/', "file=image/__WEBSITE_KEY__/", $stringtoexport);
1214 $stringtoexport = str_replace('file=js/'.$website->ref.'/', "file=js/__WEBSITE_KEY__/", $stringtoexport);
1215 $stringtoexport = str_replace('medias/image/'.$website->ref.'/', "medias/image/__WEBSITE_KEY__/", $stringtoexport);
1216 $stringtoexport = str_replace('medias/js/'.$website->ref.'/', "medias/js/__WEBSITE_KEY__/", $stringtoexport);
1217 $stringtoexport = str_replace('"image/'.$website->ref.'/', '"image/__WEBSITE_KEY__/', $stringtoexport); // When we have a link src="image/websiteref/file.png" into html content
1218 $stringtoexport = str_replace('"/image/'.$website->ref.'/', '"/image/__WEBSITE_KEY__/', $stringtoexport); // When we have a link src="/image/websiteref/file.png" into html content
1219 $stringtoexport = str_replace('"js/'.$website->ref.'/', '"js/__WEBSITE_KEY__/', $stringtoexport);
1220 $stringtoexport = str_replace('"/js/'.$website->ref.'/', '"/js/__WEBSITE_KEY__/', $stringtoexport);
1221
1222 $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_small, "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__", $stringtoexport);
1223 $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_mini, "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__", $stringtoexport);
1224 $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo, "file=logos%2Fthumbs%2F__LOGO_KEY__", $stringtoexport);
1225
1226 if (getDolGlobalString('WEBSITE_EXPORT_SQL_ON_SEVERAL_LINES')) {
1227 $line .= "/* new line */\n"; // Add a comment so we will able to restore a one line instruction on import
1228 }
1229 $line .= "'".$this->db->escape($stringtoexport)."', ";
1230
1231 $line .= "'".$this->db->escape($objectpageold->author_alias)."', ";
1232 $line .= (int) $objectpageold->allowed_in_frames;
1233 $line .= ");";
1234 $line .= "\n";
1235
1236 fwrite($fp, $line);
1237
1238 // Add line to update home page id during import
1239 //var_dump($this->fk_default_home.' - '.$objectpageold->id.' - '.$objectpageold->newid);exit;
1240 if ($this->fk_default_home > 0 && ($objectpageold->id == $this->fk_default_home) && ($objectpageold->newid > 0)) { // This is the page that is set as the home page
1241 // Warning: We must keep llx_ here. It is a generic SQL.
1242 $line = "UPDATE llx_website SET fk_default_home = ".($objectpageold->newid > 0 ? $this->db->escape((string) $objectpageold->newid)."__+MAX_llx_website_page__" : "null")." WHERE rowid = __WEBSITE_ID__;";
1243 $line .= "\n";
1244 fwrite($fp, $line);
1245 }
1246
1247 fwrite($fp, "\n");
1248 }
1249
1250 $line = "\n-- For Dolibarr v14+ --;\n";
1251 $line .= "UPDATE llx_website SET lang = '".$this->db->escape($this->lang)."' WHERE rowid = __WEBSITE_ID__;\n";
1252 $line .= "UPDATE llx_website SET otherlang = '".$this->db->escape($this->otherlang)."' WHERE rowid = __WEBSITE_ID__;\n";
1253 $line .= "\n";
1254 fwrite($fp, $line);
1255
1256 fclose($fp);
1257
1258 dolChmod($filesql_path);
1259
1260 // Build zip file
1261 $filedir = $conf->website->dir_temp.'/'.$website->ref.'/.';
1262 $fileglob = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-*.zip';
1263 $filename = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-'.dol_print_date(dol_now(), 'dayhourlog').'-V'.((float) DOL_VERSION).'.zip';
1264
1265 dol_delete_file($fileglob, 0);
1266
1267 $result = dol_compress_dir($filedir, $filename, 'zip');
1268
1269 if ($result > 0) {
1270 return $filename;
1271 } else {
1272 global $errormsg;
1273 $this->error = $errormsg;
1274 return '';
1275 }
1276 }
1277
1278
1286 public function importWebSite($pathtofile)
1287 {
1288 global $conf, $mysoc, $user;
1289
1290 $error = 0;
1291
1292 $pathtofile = dol_sanitizePathName($pathtofile);
1293 if (!file_exists($pathtofile)) {
1294 $this->error = 'The zip file "'.$pathtofile.'" is not found';
1295 return -9;
1296 }
1297
1298 $object = $this;
1299 if (empty($object->ref)) {
1300 $this->error = 'Function importWebSite called on object not loaded (object->ref is empty)';
1301 return -2;
1302 }
1303
1304 dol_delete_dir_recursive($conf->website->dir_temp."/".$object->ref);
1305 dol_mkdir($conf->website->dir_temp.'/'.$object->ref);
1306
1307 $filename = basename($pathtofile);
1308 $reg = array();
1309 if (!preg_match('/^website_(.*)-(.*)$/', $filename, $reg)) {
1310 $this->errors[] = 'Bad format for filename '.$filename.'. Must be website_XXX-VERSION.';
1311 return -3;
1312 }
1313
1314 // Uncompress the zip
1315 $result = dol_uncompress($pathtofile, $conf->website->dir_temp.'/'.$object->ref);
1316
1317 if (!empty($result['error'])) {
1318 $this->errors[] = 'Failed to unzip file '.$pathtofile;
1319 return -4;
1320 }
1321
1322 $arrayreplacement = array();
1323 $arrayreplacement['__WEBSITE_ID__'] = $object->id;
1324 $arrayreplacement['__WEBSITE_KEY__'] = $object->ref;
1325 $arrayreplacement['__N__'] = $this->db->escape("\n"); // Restore \n
1326 $arrayreplacement['__LOGO_SMALL_KEY__'] = $this->db->escape($mysoc->logo_small);
1327 $arrayreplacement['__LOGO_MINI_KEY__'] = $this->db->escape($mysoc->logo_mini);
1328 $arrayreplacement['__LOGO_KEY__'] = $this->db->escape($mysoc->logo);
1329
1330
1331 // Make replacement into css (replace dolSaveCssFile)
1332 $cssinsrcdir = $conf->website->dir_temp.'/'.$object->ref.'/containers/styles.css.php';
1333 $result = dolReplaceInFile($cssinsrcdir, $arrayreplacement);
1334
1335 // Test if imported CSS page contains dynamic PHP content
1336 if (!$user->hasRight('website', 'writephp')) {
1337 $newpathofsrcfile = dol_osencode($cssinsrcdir);
1338 $csscontent = file_get_contents($newpathofsrcfile);
1339
1340 // Check there is no PHP content into the imported file (must be only HTML + JS)
1341 $phpcontent = dolKeepOnlyPhpCode($csscontent);
1342
1343 if ($phpcontent) {
1344 $this->error = 'Error: you try to import a website with a page with PHP dynamic content in style sheet without having permissions for that.';
1345 $this->errors[] = $this->error;
1346 return -1;
1347 }
1348 }
1349 dol_copy($conf->website->dir_temp.'/'.$object->ref.'/containers/styles.css.php', $conf->website->dir_output.'/'.$object->ref.'/styles.css.php', '0', 1);
1350
1351
1352 // Make replacement in htmlheader.html (replace dolSaveHtmlHeader)
1353 $htmldeaderinsrcdir = $conf->website->dir_temp.'/'.$object->ref.'/containers/htmlheader.html';
1354 $result = dolReplaceInFile($htmldeaderinsrcdir, $arrayreplacement);
1355
1356 // Test if imported html page contains dynamic PHP content
1357 if (!$user->hasRight('website', 'writephp')) {
1358 $newpathofsrcfile = dol_osencode($htmldeaderinsrcdir);
1359 $htmlcontent = file_get_contents($newpathofsrcfile);
1360
1361 // Check there is no PHP content into the imported file (must be only HTML + JS)
1362 $phpcontent = dolKeepOnlyPhpCode($htmlcontent);
1363
1364 if ($phpcontent) {
1365 $this->error = 'Error: you try to import a website with a page with PHP dynamic content in htmlheader.html without having permissions for that.';
1366 $this->errors[] = $this->error;
1367 return -1;
1368 }
1369 }
1370 dol_copy($conf->website->dir_temp.'/'.$object->ref.'/containers/htmlheader.html', $conf->website->dir_output.'/'.$object->ref.'/htmlheader.html', '0', 1);
1371
1372
1373 //dolCopyDir($conf->website->dir_temp.'/'.$object->ref.'/containers', $conf->website->dir_output.'/'.$object->ref, '0', 1); // Overwrite if exists
1374
1375
1376 // Copy special files (replace dolSaveLicense and dolSaveHtaccessFile)
1377 foreach (array('robots.txt', '.dolibarr', '.htaccess', 'LICENSE', 'README.md') as $filename) {
1378 // Test if imported file contains dynamic PHP content
1379 $newpathofsrcfile = dol_osencode($conf->website->dir_temp.'/'.$object->ref.'/containers/'.$filename);
1380 $filecontent = file_get_contents($newpathofsrcfile);
1381
1382 // Check there is no PHP content into the imported file (must be only HTML + JS)
1383 $phpcontent = dolKeepOnlyPhpCode($filecontent);
1384
1385 if ($phpcontent) {
1386 $this->error = 'Error: you try to import a website with a page with PHP dynamic content in '.$filename.'.';
1387 $this->errors[] = $this->error;
1388 return -1;
1389 }
1390
1391 dol_copy($conf->website->dir_temp.'/'.$object->ref.'/containers/'.$filename, $conf->website->dir_output.'/'.$object->ref.'/'.$filename, '0', 1);
1392 }
1393
1394 // Now generate the javascript.js.php
1395 $filejs = dol_osencode($conf->website->dir_temp.'/'.$object->ref.'/containers/javascript.js.php');
1396 $jscontent = @file_get_contents($filejs);
1397 // Clean the php js file to remove php code and get only js part
1398 $jscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP( \?>)?\n*/ims', '', $jscontent);
1399 $phpcontent = dolKeepOnlyPhpCode($jscontent);
1400 if ($phpcontent) {
1401 $this->error = 'Error: you try to import a website with a page with PHP dynamic content in '.$filename.'.';
1402 $this->errors[] = $this->error;
1403 return -1;
1404 }
1405 dolSaveJsFile($conf->website->dir_output.'/'.$object->ref.'/javascript.js.php', $jscontent);
1406
1407
1408 // Now generate the manifest.json.php
1409 $filemanifestjson = dol_osencode($conf->website->dir_temp.'/'.$object->ref.'/containers/manifest.json.php');
1410 $manifestjsoncontent = @file_get_contents($filemanifestjson);
1411 // Clean the manifestjson file to remove php code and get only html part
1412 $manifestjsoncontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP( \?>)?\n*/ims', '', $manifestjsoncontent);
1413 // Check there is no PHP content into the imported file (must be only HTML + JS)
1414 $phpcontent = dolKeepOnlyPhpCode($manifestjsoncontent);
1415 if ($phpcontent) {
1416 $this->error = 'Error: you try to import a website with a page with PHP dynamic content in '.$filename.'.';
1417 $this->errors[] = $this->error;
1418 return -1;
1419 }
1420 dolSaveManifestJson($conf->website->dir_output.'/'.$object->ref.'/manifest.json.php', $manifestjsoncontent);
1421
1422
1423 // Now generate the master.inc.php page
1424 $filemaster = $conf->website->dir_output.'/'.$object->ref.'/master.inc.php';
1425 $result = dolSaveMasterFile($filemaster);
1426 if (!$result) {
1427 $this->errors[] = 'Failed to write file '.$filemaster;
1428 $error++;
1429 }
1430
1431
1432 // Copy dir medias/image/websitekey
1433 if (dol_is_dir($conf->website->dir_temp.'/'.$object->ref.'/medias/image/websitekey')) {
1434 $result = dolCopyDir($conf->website->dir_temp.'/'.$object->ref.'/medias/image/websitekey', $conf->website->dir_output.'/'.$object->ref.'/medias/image/'.$object->ref, '0', 1);
1435 if ($result < 0) {
1436 $this->error = 'Failed to copy files into '.$conf->website->dir_output.'/'.$object->ref.'/medias/image/'.$object->ref.'.';
1437 dol_syslog($this->error, LOG_WARNING);
1438 $this->errors[] = $this->error;
1439 return -5;
1440 }
1441 }
1442
1443 // Copy dir medias/js/websitekey
1444 if (dol_is_dir($conf->website->dir_temp.'/'.$object->ref.'/medias/js/websitekey')) {
1445 $result = dolCopyDir($conf->website->dir_temp.'/'.$object->ref.'/medias/js/websitekey', $conf->website->dir_output.'/'.$object->ref.'/medias/js/'.$object->ref, '0', 1);
1446 if ($result < 0) {
1447 $this->error = 'Failed to copy files into '.$conf->website->dir_output.'/'.$object->ref.'/medias/js/'.$object->ref.'.';
1448 dol_syslog($this->error, LOG_WARNING);
1449 $this->errors[] = $this->error;
1450 return -6;
1451 }
1452 }
1453
1454 $sqlfile = $conf->website->dir_temp."/".$object->ref.'/website_pages.sql';
1455
1456 $result = dolReplaceInFile($sqlfile, $arrayreplacement);
1457
1458 $this->db->begin();
1459
1460 // Search the $maxrowid because we need it later
1461 $sqlgetrowid = 'SELECT MAX(rowid) as max from '.MAIN_DB_PREFIX.'website_page';
1462 $maxrowid = 0;
1463 $resql = $this->db->query($sqlgetrowid);
1464 if ($resql) {
1465 $obj = $this->db->fetch_object($resql);
1466 $maxrowid = $obj->max;
1467 }
1468
1469 // Load sql record
1470 $resqlrun = run_sql($sqlfile, 1, 0, 0, '', 'none', 0, 1, 0, 0, 1, ''); // The maxrowid of table is searched into this function two
1471 if ($resqlrun <= 0) {
1472 $this->errors[] = 'Failed to load sql file '.$sqlfile.' (ret='.((int) $resqlrun).')';
1473 $error++;
1474 }
1475
1476 $objectpagestatic = new WebsitePage($this->db);
1477 $aliasesarray = null;
1478
1479 // Regenerate the php files for pages
1480 $fp = fopen($sqlfile, "r");
1481 if ($fp) {
1482 while (!feof($fp)) {
1483 $reg = array();
1484
1485 // Warning fgets with second parameter that is null or 0 hang.
1486 $buf = fgets($fp, 65000); // No need to have a high value here for second parameter. We will process only short lines starting with '-- Page ID ...'
1487 $newid = 0;
1488
1489 // Scan the line
1490 if (preg_match('/^-- Page ID (\d+)\s[^\s]+\s(\d+).*Aliases\s(.+)\s--;/i', $buf, $reg)) {
1491 // Example of line: "-- Page ID 179 -> 1__+MAX_llx_website_page__ - Aliases about-us --;"
1492 $oldid = (int) $reg[1];
1493 $newid = ((int) $reg[2] + $maxrowid);
1494 $aliasesarray = explode(',', $reg[3]);
1495
1496 dol_syslog("In sql source file, we have the page ID ".$oldid." to replace with the new ID ".$newid.", and we must create the shortcut aliases: ".$reg[3]);
1497
1498 //dol_move($conf->website->dir_output.'/'.$object->ref.'/page'.$oldid.'.tpl.php', $conf->website->dir_output.'/'.$object->ref.'/page'.$newid.'.tpl.php', 0, 1, 0, 0);
1499 } elseif (preg_match('/^-- Page ID (\d+).*Aliases\s(.*)\s--;/i', $buf, $reg)) {
1500 // Example of line: "-- Page ID 1__+MAX_llx_website_page__ - Aliases about-us --;"
1501 $newid = ((int) $reg[1] + $maxrowid);
1502 $aliasesarray = explode(',', $reg[2]);
1503
1504 dol_syslog("In sql source file, we have the page with the new ID ".$newid.", and we must create the shortcut aliases: ".$reg[2]);
1505 }
1506
1507 if ($newid) {
1508 $objectpagestatic->fetch($newid);
1509
1510 // We write the pageX.tpl.php
1511 $filetpl = $conf->website->dir_output.'/'.$object->ref.'/page'.$newid.'.tpl.php';
1512 $result = dolSavePageContent($filetpl, $object, $objectpagestatic);
1513 if (!$result) {
1514 $this->errors[] = 'Failed to write file '.basename($filetpl);
1515 $error++;
1516 }
1517
1518 // Test if imported page contains dynamic PHP content
1519 if (!$user->hasRight('website', 'writephp')) {
1520 $newpathofsrcfile = dol_osencode($filetpl);
1521 $tplcontent = file_get_contents($newpathofsrcfile);
1522
1523 // Check there is no PHP content into the imported file (must be only HTML + JS)
1524 $phpcontent = dolKeepOnlyPhpCode($tplcontent);
1525
1526 if ($phpcontent) {
1527 $this->error = 'Error: you try to import a website with a page with PHP dynamic content without having permissions for that.';
1528 $this->errors[] = $this->error;
1529 $error++;
1530 }
1531 }
1532
1533 // Regenerate also the main alias + alternative aliases pages
1534 if (is_array($aliasesarray)) {
1535 foreach ($aliasesarray as $aliasshortcuttocreate) {
1536 if (trim($aliasshortcuttocreate)) {
1537 $filealias = $conf->website->dir_output.'/'.$object->ref.'/'.trim($aliasshortcuttocreate).'.php';
1538 $result = dolSavePageAlias($filealias, $object, $objectpagestatic);
1539 if (!$result) {
1540 $this->errors[] = 'Failed to write file '.basename($filealias);
1541 $error++;
1542 }
1543 }
1544 }
1545 }
1546 }
1547 }
1548 }
1549
1550 // Read record of website that has been updated by the run_sql function previously called so we can get the
1551 // value of fk_default_home that is ID of home page
1552 $sql = "SELECT fk_default_home FROM ".MAIN_DB_PREFIX."website WHERE rowid = ".((int) $object->id);
1553 $resql = $this->db->query($sql);
1554 if ($resql) {
1555 $obj = $this->db->fetch_object($resql);
1556 if ($obj) {
1557 $object->fk_default_home = $obj->fk_default_home;
1558 } else {
1559 //$this->errors[] = 'Failed to get the Home page';
1560 //$error++;
1561 }
1562 }
1563
1564 // Regenerate the index.php page to point to the new index page
1565 $pathofwebsite = $conf->website->dir_output.'/'.$object->ref;
1566 dolSaveIndexPage($pathofwebsite, $pathofwebsite.'/index.php', $pathofwebsite.'/page'.$object->fk_default_home.'.tpl.php', $pathofwebsite.'/wrapper.php', $object);
1567
1568 //$this->initFilesStatus($pathofwebsite);
1569
1570 if ($error) {
1571 $this->db->rollback();
1572 return -1;
1573 } else {
1574 $this->db->commit();
1575 return $object->id;
1576 }
1577 }
1578
1585 public function rebuildWebSiteFiles()
1586 {
1587 global $conf;
1588
1589 $error = 0;
1590
1591 $object = $this;
1592 if (empty($object->ref)) {
1593 $this->error = 'Function rebuildWebSiteFiles called on object not loaded (object->ref is empty)';
1594 return -1;
1595 }
1596
1597 $objectpagestatic = new WebsitePage($this->db);
1598
1599 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."website_page WHERE fk_website = ".((int) $this->id);
1600
1601 $resql = $this->db->query($sql);
1602 if (!$resql) {
1603 $this->error = $this->db->lasterror();
1604 return -1;
1605 }
1606
1607 $num = $this->db->num_rows($resql);
1608
1609 // Loop on each container/page
1610 $i = 0;
1611 while ($i < $num) {
1612 $obj = $this->db->fetch_object($resql);
1613
1614 $newid = $obj->rowid;
1615
1616 $objectpagestatic->fetch($newid);
1617
1618 $aliasesarray = explode(',', $objectpagestatic->aliasalt);
1619
1620 $filetpl = $conf->website->dir_output.'/'.$object->ref.'/page'.$newid.'.tpl.php';
1621 $result = dolSavePageContent($filetpl, $object, $objectpagestatic);
1622 if (!$result) {
1623 $this->errors[] = 'Failed to write file '.basename($filetpl);
1624 $error++;
1625 }
1626
1627 // Add main alias to list of alternative aliases
1628 if (!empty($objectpagestatic->pageurl) && !in_array($objectpagestatic->pageurl, $aliasesarray)) {
1629 $aliasesarray[] = $objectpagestatic->pageurl;
1630 }
1631
1632 // Regenerate also all aliases pages (pages with a natural name) by calling dolSavePageAlias()
1633 if (is_array($aliasesarray)) {
1634 foreach ($aliasesarray as $aliasshortcuttocreate) {
1635 if (trim($aliasshortcuttocreate)) {
1636 $filealias = $conf->website->dir_output.'/'.$object->ref.'/'.trim($aliasshortcuttocreate).'.php';
1637 $result = dolSavePageAlias($filealias, $object, $objectpagestatic); // This includes also a copy into sublanguage directories.
1638 if (!$result) {
1639 $this->errors[] = 'Failed to write file '.basename($filealias);
1640 $error++;
1641 }
1642 }
1643 }
1644 }
1645
1646 $i++;
1647 }
1648
1649 if (!$error) {
1650 // Save index.php and wrapper.php
1651 $pathofwebsite = $conf->website->dir_output.'/'.$object->ref;
1652 $fileindex = $pathofwebsite.'/index.php';
1653 $filetpl = '';
1654 if ($object->fk_default_home > 0) {
1655 $filetpl = $pathofwebsite.'/page'.$object->fk_default_home.'.tpl.php';
1656 }
1657 $filewrapper = $pathofwebsite.'/wrapper.php';
1658 dolSaveIndexPage($pathofwebsite, $fileindex, $filetpl, $filewrapper, $object); // This includes also a version of index.php into sublanguage directories
1659 }
1660
1661 // Erase cache files
1662 $filecacheglob = $conf->website->dir_output.'/temp/'.$object->ref.'-*.php.cache';
1663 dol_delete_file($filecacheglob, 0, 1, 1, null, false, 0, 1);
1664
1665 if ($error) {
1666 return -1;
1667 } else {
1668 return $num;
1669 }
1670 }
1671
1677 public function isMultiLang()
1678 {
1679 return !empty($this->otherlang);
1680 }
1681
1691 public function componentSelectLang($languagecodes, $weblangs, $morecss = '', $htmlname = '')
1692 {
1693 global $websitepagefile, $website;
1694 '@phan-var-force Website $website';
1695
1696 if (!is_object($weblangs)) {
1697 return 'ERROR componentSelectLang called with parameter $weblangs not defined';
1698 }
1699
1700 $arrayofspecialmainlanguages = array(
1701 'en' => 'en_US',
1702 'sq' => 'sq_AL',
1703 'ar' => 'ar_SA',
1704 'eu' => 'eu_ES',
1705 'bn' => 'bn_DB',
1706 'bs' => 'bs_BA',
1707 'ca' => 'ca_ES',
1708 'zh' => 'zh_CN',
1709 'cs' => 'cs_CZ',
1710 'da' => 'da_DK',
1711 'et' => 'et_EE',
1712 'ka' => 'ka_GE',
1713 'el' => 'el_GR',
1714 'he' => 'he_IL',
1715 'kn' => 'kn_IN',
1716 'km' => 'km_KH',
1717 'ko' => 'ko_KR',
1718 'lo' => 'lo_LA',
1719 'nb' => 'nb_NO',
1720 'fa' => 'fa_IR',
1721 'sr' => 'sr_RS',
1722 'sl' => 'sl_SI',
1723 'uk' => 'uk_UA',
1724 'vi' => 'vi_VN'
1725 );
1726
1727 // Load tmppage if we have $websitepagefile defined
1728 $tmppage = new WebsitePage($this->db);
1729
1730 $pageid = 0;
1731 if (!empty($websitepagefile)) {
1732 $websitepagefileshort = basename($websitepagefile);
1733 if ($websitepagefileshort == 'index.php') {
1734 $pageid = $website->fk_default_home;
1735 } else {
1736 $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), $websitepagefileshort);
1737 }
1738 if ($pageid > 0) {
1739 $tmppage->fetch($pageid);
1740 }
1741 }
1742
1743 // Fill $languagecodes array with existing translation, nothing if none
1744 if (!is_array($languagecodes) && $pageid > 0) {
1745 $languagecodes = array();
1746
1747 $sql = "SELECT wp.rowid, wp.lang, wp.pageurl, wp.fk_page";
1748 $sql .= " FROM ".MAIN_DB_PREFIX."website_page as wp";
1749 $sql .= " WHERE wp.fk_website = ".((int) $website->id);
1750 $sql .= " AND (wp.fk_page = ".((int) $pageid)." OR wp.rowid = ".((int) $pageid);
1751 if ($tmppage->fk_page > 0) {
1752 $sql .= " OR wp.fk_page = ".((int) $tmppage->fk_page)." OR wp.rowid = ".((int) $tmppage->fk_page);
1753 }
1754 $sql .= ")";
1755
1756 $resql = $this->db->query($sql);
1757 if ($resql) {
1758 while ($obj = $this->db->fetch_object($resql)) {
1759 $newlang = $obj->lang;
1760 if ($obj->rowid == $pageid) {
1761 $newlang = $obj->lang;
1762 }
1763 if (!in_array($newlang, $languagecodes)) {
1764 $languagecodes[] = $newlang;
1765 }
1766 }
1767 }
1768 }
1769 // Now $languagecodes is always an array. Example array('en', 'fr', 'es');
1770
1771 $languagecodeselected = substr($weblangs->defaultlang, 0, 2); // Because we must init with a value, but real value is the lang of main parent container
1772 if (!empty($websitepagefile)) {
1773 $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), basename($websitepagefile));
1774 if ($pageid > 0) {
1775 $pagelang = substr($tmppage->lang, 0, 2);
1776 $languagecodeselected = substr($pagelang, 0, 2);
1777 if (!in_array($pagelang, $languagecodes)) {
1778 $languagecodes[] = $pagelang; // We add language code of page into combo list
1779 }
1780 }
1781 }
1782
1783 $weblangs->load('languages');
1784 //var_dump($weblangs->defaultlang);
1785
1786 $url = $_SERVER["REQUEST_URI"];
1787 $url = preg_replace('/(\?|&)l=([a-zA-Z_]*)/', '', $url); // We remove param l from url
1788 //$url = preg_replace('/(\?|&)lang=([a-zA-Z_]*)/', '', $url); // We remove param lang from url
1789 $url .= (preg_match('/\?/', $url) ? '&' : '?').'l=';
1790 if (!preg_match('/^\//', $url)) {
1791 $url = '/'.$url;
1792 }
1793
1794 $HEIGHTOPTION = 40;
1795 $MAXHEIGHT = 4 * $HEIGHTOPTION;
1796 $nboflanguage = count($languagecodes);
1797
1798 $out = '<!-- componentSelectLang'.$htmlname.' -->'."\n";
1799
1800 $out .= '<style>';
1801 $out .= '.componentSelectLang'.$htmlname.':hover { height: '.min($MAXHEIGHT, ($HEIGHTOPTION * $nboflanguage)).'px; overflow-x: hidden; overflow-y: '.((($HEIGHTOPTION * $nboflanguage) > $MAXHEIGHT) ? ' scroll' : 'hidden').'; }'."\n";
1802 $out .= '.componentSelectLang'.$htmlname.' li { line-height: '.$HEIGHTOPTION.'px; }'."\n";
1803 $out .= '.componentSelectLang'.$htmlname.' {
1804 display: inline-block;
1805 padding: 0;
1806 height: '.$HEIGHTOPTION.'px;
1807 overflow: hidden;
1808 transition: all .3s ease;
1809 margin: 0 0 0 0;
1810 vertical-align: top;
1811 }
1812 .componentSelectLang'.$htmlname.':hover, .componentSelectLang'.$htmlname.':hover a { background-color: #fff; color: #000 !important; }
1813 ul.componentSelectLang'.$htmlname.' { width: 150px; }
1814 ul.componentSelectLang'.$htmlname.':hover .fa { visibility: hidden; }
1815 .componentSelectLang'.$htmlname.' a { text-decoration: none; width: 100%; }
1816 .componentSelectLang'.$htmlname.' li { display: block; padding: 0px 15px; margin-left: 0; margin-right: 0; }
1817 .componentSelectLang'.$htmlname.' li:hover { background-color: #EEE; }
1818 ';
1819 $out .= '</style>';
1820 $out .= '<ul class="componentSelectLang'.$htmlname.($morecss ? ' '.$morecss : '').'">';
1821
1822 if ($languagecodeselected) {
1823 // Convert $languagecodeselected into a long language code
1824 if (strlen($languagecodeselected) == 2) {
1825 $languagecodeselected = (string) (empty($arrayofspecialmainlanguages[$languagecodeselected]) ? $languagecodeselected.'_'.strtoupper($languagecodeselected) : $arrayofspecialmainlanguages[$languagecodeselected]);
1826 }
1827
1828 $countrycode = strtolower(substr($languagecodeselected, -2));
1829 $label = $weblangs->trans("Language_".$languagecodeselected);
1830 if ($countrycode == 'us') {
1831 $label = preg_replace('/\s*\‍(.*\‍)/', '', $label);
1832 }
1833 $out .= '<li><a href="'.$url.substr($languagecodeselected, 0, 2).'"><img height="12px" src="/medias/image/common/flags/'.$countrycode.'.png" style="margin-right: 5px;"/><span class="websitecomponentlilang">'.$label.'</span>';
1834 $out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
1835 $out .= '</a></li>';
1836 }
1837 $i = 0;
1838 if (is_array($languagecodes)) {
1839 foreach ($languagecodes as $languagecode) {
1840 // Convert $languagecode into a long language code
1841 if (strlen($languagecode) == 2) {
1842 $languagecode = (empty($arrayofspecialmainlanguages[$languagecode]) ? $languagecode.'_'.strtoupper($languagecode) : $arrayofspecialmainlanguages[$languagecode]);
1843 }
1844
1845 if ($languagecode == $languagecodeselected) {
1846 continue; // Already output
1847 }
1848
1849 $countrycode = strtolower(substr($languagecode, -2));
1850 $label = $weblangs->trans("Language_".$languagecode);
1851 if ($countrycode == 'us') {
1852 $label = preg_replace('/\s*\‍(.*\‍)/', '', $label);
1853 }
1854 $out .= '<li><a href="'.$url.substr($languagecode, 0, 2).'"><img height="12px" src="/medias/image/common/flags/'.$countrycode.'.png" style="margin-right: 5px;"/><span class="websitecomponentlilang">'.$label.'</span>';
1855 if (empty($i) && empty($languagecodeselected)) {
1856 $out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
1857 }
1858 $out .= '</a></li>';
1859 $i++;
1860 }
1861 }
1862 $out .= '</ul>';
1863
1864 return $out;
1865 }
1866
1874 public function overwriteTemplate(string $pathtotmpzip, $exportPath = '')
1875 {
1876 global $conf;
1877
1878 $website = $this;
1879 if (empty($website->id) || empty($website->ref)) {
1880 $this->error = "Website id or ref is not defined";
1881 $this->errors[] = $this->error;
1882 return -1;
1883 }
1884 if (empty($website->name_template) && empty($exportPath)) {
1885 $this->error = "To export the website template into a directory of the server, the name of the directory/template must be provided.";
1886 $this->errors[] = $this->error;
1887 return -1;
1888 }
1889 if (!is_writable($conf->website->dir_temp)) {
1890 $this->error = "Temporary dir ".$conf->website->dir_temp." is not writable";
1891 $this->errors[] = $this->error;
1892 return -1;
1893 }
1894
1895 $destdir = null; // Otherwise only set when 'WEBSITE_ALLOW_OVERWRITE_GIT_SOURCE' is not falsy.
1896 $destdirrel = ''; // Otherwise only set when 'WEBSITE_ALLOW_OVERWRITE_GIT_SOURCE' is not falsy.
1897 // Replace modified files into the doctemplates directory.
1898 if (getDolGlobalString('WEBSITE_ALLOW_OVERWRITE_GIT_SOURCE')) {
1899 // If the user has not specified a path
1900 if (empty($exportPath)) {
1901 $destdirrel = 'install/doctemplates/websites/'.$website->name_template;
1902 $destdir = DOL_DOCUMENT_ROOT.'/'.$destdirrel;
1903 } else {
1904 $exportPath = rtrim($exportPath, '/');
1905 if (strpos($exportPath, '..') !== false) {
1906 $this->error = "Invalid path.";
1907 $this->errors[] = $this->error;
1908 return -1;
1909 }
1910 // if path start with / (absolute path)
1911 if (strpos($exportPath, '/') === 0 || preg_match('/^[a-zA-Z]:/', $exportPath)) {
1912 if (!is_dir($exportPath)) {
1913 $this->error = "The specified absolute path does not exist.";
1914 $this->errors[] = $this->error;
1915 return -1;
1916 }
1917
1918 if (!is_writable($exportPath)) {
1919 $this->error = "The specified absolute path is not writable.";
1920 $this->errors[] = $this->error;
1921 return -1;
1922 }
1923 $destdirrel = $exportPath;
1924 $destdir = $exportPath;
1925 } else {
1926 // relatif path
1927 $destdirrel = 'install/doctemplates/websites/'.$exportPath;
1928 $destdir = DOL_DOCUMENT_ROOT.'/'.$destdirrel;
1929 }
1930 }
1931 }
1932
1933 if ($destdir === null) {
1934 $this->error = "The destination path is not determined.";
1935 $this->errors[] = $this->error;
1936 return -1;
1937 }
1938
1939 dol_mkdir($destdir);
1940
1941 if (!is_writable($destdir)) {
1942 $this->error = "The specified path ".$destdir." is not writable.";
1943 $this->errors[] = $this->error;
1944 return -1;
1945 }
1946
1947 // Export on target sources
1948 $resultarray = dol_uncompress($pathtotmpzip, $destdir);
1949
1950 // Remove the file README.md and LICENSE from the $destdir/containers
1951 if (dol_is_file($destdir.'/containers/README.md')) {
1952 dol_move($destdir.'/containers/README.md', $destdir.'/README.md', '0', 1, 0, 0);
1953 }
1954 if (dol_is_file($destdir.'/containers/LICENSE')) {
1955 dol_move($destdir.'/containers/LICENSE', $destdir.'/LICENSE', '0', 1, 0, 0);
1956 }
1957 /*
1958 if (empty($exportPath)) {
1959 dol_delete_file($destdir.'/containers/README.md');
1960 dol_delete_file($destdir.'/containers/LICENSE');
1961 }
1962 */
1963
1964 // Remove non required files (will be re-generated during the import)
1965 dol_delete_file($destdir.'/containers/index.php');
1966 dol_delete_file($destdir.'/containers/master.inc.php');
1967
1968 // Now we remove the flag o+x on files
1969 // TODO
1970
1971 if (!empty($resultarray)) {
1972 $this->error = "Error, failed to unzip the export into target dir ".$destdir.": ".implode(',', $resultarray);
1973 $this->errors[] = $this->error;
1974 return -1;
1975 }
1976
1977 setEventMessages("Website content written into ".$destdirrel, null, 'mesgs');
1978
1979 header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website->ref);
1980 exit();
1981 }
1982
1988 protected function extractNumberFromFilename($filename)
1989 {
1990 $matches = [];
1991 if (preg_match('/page(\d+)\.tpl\.php/', $filename, $matches)) {
1992 return (int) $matches[1];
1993 }
1994 return -1;
1995 }
1996
2002 public function setTemplateName($name_template)
2003 {
2004 $this->db->begin();
2005
2006 $sql = "UPDATE ".$this->db->prefix()."website SET";
2007 $sql .= " name_template = '".$this->db->escape($name_template)."'";
2008 $sql .= " WHERE rowid = ".(int) $this->id;
2009 $result = $this->db->query($sql);
2010
2011 if ($result) {
2012 $this->db->commit();
2013 return 1;
2014 } else {
2015 $this->db->rollback();
2016 return -1;
2017 }
2018 }
2019
2027 public function compareFichierModifie($dossierSource, $dossierDestination, $fichierModifie)
2028 {
2029
2030 $fichiersSource = [];
2031 $fichiersDestination = [];
2032
2033 $fichierWithNoPage = [];
2034 $fichierWithNoPageInDest = [];
2035
2036 // Filter source files
2037 foreach (dol_dir_list($dossierSource, "files") as $file) {
2038 if (preg_match('/^page\d+/', $file['name']) && !str_contains($file['name'], '.old')) {
2039 $fichiersSource[] = $file;
2040 } else {
2041 $fichierWithNoPage[] = $file;
2042 }
2043 }
2044
2045 // Filter destination files
2046 foreach (dol_dir_list($dossierDestination, "all", 1) as $file) {
2047 if (preg_match('/^page\d+/', $file['name']) && !str_contains($file['name'], '.old')) {
2048 $fichiersDestination[] = $file;
2049 } else {
2050 $fichierWithNoPageInDest[] = $file;
2051 }
2052 }
2053
2054 // find index source and search it in folder destination
2055 $numOfPageSource = 0;
2056 foreach ($fichiersSource as $index => $file) {
2057 if ($file['name'] == basename($fichierModifie['fullname'])) {
2058 $numOfPageSource = $this->extractNumberFromFilename($file['name']);
2059 break;
2060 }
2061 }
2062
2063 //search numPage where was declared
2064 $filesFound = array();
2065 foreach ($fichierWithNoPage as $filesource) {
2066 $fileContent = file_get_contents($filesource['fullname']);
2067 if (strpos($fileContent, "require './page".$numOfPageSource.".tpl.php'") !== false) {
2068 $filesFound = $filesource;
2069 break;
2070 }
2071 }
2072 // find file with same name and extract num page in destination folder
2073 $numPagesFound = '';
2074 foreach ($fichierWithNoPageInDest as $filedest) {
2075 if ($filedest['name'] === $filesFound['name']) {
2076 $fileContent = file_get_contents($filedest['fullname']);
2077 if (preg_match("/page\d+\.tpl\.php/", $fileContent, $matches)) {
2078 $numPagesFound = $matches[0];
2079 break;
2080 }
2081 }
2082 }
2083 //search file with the number of pages found
2084 $fileNeeded = array();
2085 foreach ($fichiersDestination as $index => $file) {
2086 if ($file['name'] == $numPagesFound) {
2087 $fileNeeded = $file;
2088 break;
2089 }
2090 }
2091
2092 if (isset($fileNeeded)) {
2093 $sourceContent = file_get_contents($fichierModifie['fullname']);
2094 if (file_exists($fileNeeded['fullname'])) {
2095 $destContent = file_get_contents($fileNeeded['fullname']);
2096
2097 $numOfPageDest = $this->extractNumberFromFilename($fileNeeded['name']);
2098 $differences = $this->showDifferences($destContent, $sourceContent, array($numOfPageDest,$numOfPageSource));
2099 $differences['file_destination'] = $fileNeeded;
2100 } else {
2101 $differences = array();
2102 }
2103 return $differences;
2104 }
2105 return array();
2106 }
2107
2113 private function normalizeString($str)
2114 {
2115 $str = str_replace("\r\n", "\n", $str);
2116 $str = str_replace("\r", "\n", $str);
2117 return $str;
2118 }
2119
2127 protected function showDifferences($str1, $str2, $exceptNumPge = array())
2128 {
2129 $diff = array();
2130 $str1 = $this->normalizeString($str1);
2131 $str2 = $this->normalizeString($str2);
2132
2133 $lines1 = explode("\n", $str1);
2134 $lines2 = explode("\n", $str2);
2135
2136 $linesShouldChange = array();
2137 $linesShouldNotChange = array();
2138 $linefound = array();
2139 $countNumPage = count($exceptNumPge);
2140
2141 for ($i = 0;$i < $countNumPage; $i++) {
2142 $linefound[$i] = array();
2143 $linefound[$i]['meta'] = '/content="' . preg_quote((string) $exceptNumPge[$i], '/') . '" \/>/';
2144 $linefound[$i]['output'] = '/dolWebsiteOutput\‍(\$tmp, "html", ' . preg_quote((string) $exceptNumPge[$i], '/') . '\‍);/';
2145 }
2146
2147 if (isset($linefound[1])) {
2148 $maxLines = max(count($lines1), count($lines2));
2149 for ($lineNum = 0; $lineNum < $maxLines; $lineNum++) {
2150 $lineContent1 = $lines1[$lineNum] ?? '';
2151 $lineContent2 = $lines2[$lineNum] ?? '';
2152 if (preg_match($linefound[0]['output'], $lineContent1)) {
2153 $linesShouldChange[] = $lineContent1;
2154 }
2155 if (preg_match($linefound[0]['meta'], $lineContent1)) {
2156 $linesShouldChange[] = $lineContent1;
2157 }
2158 if (preg_match($linefound[1]['output'], $lineContent2)) {
2159 $linesShouldNotChange[] = $lineContent2;
2160 }
2161 if (preg_match($linefound[1]['meta'], $lineContent2)) {
2162 $linesShouldNotChange[] = $lineContent2;
2163 }
2164 if ($lineContent1 !== $lineContent2) {
2165 if (isset($lines1[$lineNum]) && !isset($lines2[$lineNum])) {
2166 // Line deleted from the source
2167 $diff["Supprimée à la ligne " . ($lineNum + 1)] = $lineContent1;
2168 } elseif (!isset($lines1[$lineNum]) && isset($lines2[$lineNum])) {
2169 // New line added to the target
2170 $diff["Ajoutée à la ligne " . ($lineNum + 1)] = $lineContent2;
2171 } else {
2172 // Found a difference
2173 $diff["Modifiée à la ligne " . ($lineNum + 1)] = $lineContent2;
2174 }
2175 }
2176 }
2177 }
2178
2179
2180 if (empty($linesShouldChange)) {
2181 $linesShouldChange[0] = '<meta name="dolibarr:pageid" content="'.$exceptNumPge[0].'" />';
2182 $linesShouldChange[1] = '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "html", '.$exceptNumPge[0].');';
2183 }
2184
2185 $replacementMapping = array();
2186 if (!empty($linesShouldNotChange)) {
2187 $i = 0;
2188 foreach ($linesShouldNotChange as $numLigne => $ligneRemplacement) {
2189 if (isset($linesShouldChange[$numLigne])) {
2190 $replacementMapping[$ligneRemplacement] = $linesShouldChange[$numLigne];
2191 } else {
2192 $replacementMapping[$ligneRemplacement] = $linesShouldChange[$i];
2193 }
2194 $i++;
2195 }
2196 $diff['lignes_dont_change'] = $replacementMapping;
2197 }
2198 // search path of image and replace it with the correct path
2199 $pattern = '/medias\/image\/'.preg_quote($this->ref, '/').'\/([^\'"\s]+)/';
2200
2201 foreach ($diff as $key => $value) {
2202 // Ensure the value is a string
2203 if (is_string($value)) {
2204 if (preg_match($pattern, $value)) {
2205 $newValue = preg_replace($pattern, 'medias/image/'.$this->name_template.'/$1', $value);
2206 $diff[$key] = $newValue;
2207 }
2208 }
2209 }
2210 return $diff;
2211 }
2212
2220 protected function replaceLineUsingNum($inplaceFile, $differences)
2221 {
2222 if (file_exists($inplaceFile)) {
2223 dolChmod($inplaceFile, '0664');
2224 }
2225 if (!is_writable($inplaceFile)) {
2226 return -2;
2227 }
2228
2229 unset($differences['file_destination']);
2230 $contentDest = file($inplaceFile, FILE_IGNORE_NEW_LINES);
2231 foreach ($differences as $key => $ligneSource) {
2232 $matches = array();
2233 if (preg_match('/(Ajoutée|Modifiée) à la ligne (\d+)/', $key, $matches)) {
2234 $typeModification = $matches[1];
2235 $numLigne = (int) $matches[2] - 1;
2236
2237 if ($typeModification === 'Ajoutée') {
2238 array_splice($contentDest, $numLigne, 0, $ligneSource);
2239 } elseif ($typeModification === 'Modifiée') {
2240 $contentDest[$numLigne] = $ligneSource;
2241 }
2242 } elseif (preg_match('/Supprimée à la ligne (\d+)/', $key, $matches)) {
2243 $numLigne = (int) $matches[1] - 1;
2244 unset($contentDest[$numLigne]);
2245 }
2246 }
2247 // Reindex the table keys
2248 $contentDest = array_values($contentDest);
2249 $stringreplacement = implode("\n", $contentDest);
2250
2251 file_put_contents($inplaceFile, $stringreplacement);
2252 dolChmod($inplaceFile);
2253
2254 foreach ($differences['lignes_dont_change'] as $linechanged => $line) {
2255 if (in_array($linechanged, $contentDest)) {
2256 dolReplaceInFile($inplaceFile, array($linechanged => $line));
2257 }
2258 }
2259
2260 return 0;
2261 }
2262}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
run_sql($sqlfile, $silent=1, $entity=0, $usesavepoint=1, $handler='', $okerror='default', $linelengthlimit=32768, $nocommentremoval=0, $offsetforchartofaccount=0, $colspan=0, $onlysqltoimportwebsite=0, $database='')
Launch a sql file.
print $object position
Definition edit.php:206
$object ref
Definition info.php:90
setErrorsFromObject($object)
setErrorsFromObject
deleteCommon(User $user, $notrigger=0, $forcechilddeletion=0)
Delete object in database.
Class to manage Dolibarr database access.
Class to manage Dolibarr users.
Class Website.
isMultiLang()
Return if web site is a multilanguage web site.
setTemplateName($name_template)
update name_template in table after import template
create(User $user, $notrigger=0)
Create object into database.
rebuildWebSiteFiles()
Rebuild all files of all the pages/containers of a website.
exportWebSite()
Generate a zip with all data of web site.
replaceLineUsingNum($inplaceFile, $differences)
Replace line by line in file using numbers of the lines.
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
componentSelectLang($languagecodes, $weblangs, $morecss='', $htmlname='')
Component to select language inside a container (Full CSS Only)
extractNumberFromFilename($filename)
extract num of page
createFromClone($user, $fromid, $newref, $newlang='')
Load a website its id and create a new one in database.
fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, $filter='', $filtermode='AND')
Load all object in memory ($this->records) from the database.
overwriteTemplate(string $pathtotmpzip, $exportPath='')
Overite template by copying all files.
__construct(DoliDB $db)
Constructor.
getLibStatut($mode=0)
Return the label of the status.
LibStatut($status, $mode=0)
Return the label of a given status.
purge(User $user)
Purge website Delete website directory content and all pages and medias.
getNomUrl($withpicto=0, $option='', $notooltip=0, $maxlen=24, $morecss='')
Return a link to the user card (with optionally the picto) Use this->id,this->lastname,...
normalizeString($str)
Remove spaces in string.
update(User $user, $notrigger=0)
Update object into database.
fetch($id, $ref=null)
Load object in memory from the database.
compareFichierModifie($dossierSource, $dossierDestination, $fichierModifie)
Compare two files has not same name but same content.
showDifferences($str1, $str2, $exceptNumPge=array())
show difference between to string
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
global $mysoc
dolKeepOnlyPhpCode($str)
Keep only PHP code part from a HTML string page.
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=null)
Move a file into another name.
dol_copy($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=0)
Copy a file to another file.
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_uncompress($inputfile, $outputdir)
Uncompress a file.
dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement=null, $excludesubdir=0, $excludefileext=null, $excludearchivefiles=0)
Copy a dir to another dir.
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:65
dol_is_dir($folder)
Test if filename is a directory.
dolReplaceInFile($srcfile, $arrayreplacement, $destfile='', $newmask='0', $indexdatabase=0, $arrayreplacementisregex=0)
Make replacement of strings into a file.
dol_now($mode='gmt')
Return date for now.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_sanitizePathName($str, $newstr='_', $unaccent=0, $allowdash=0)
Clean a string to use it as a path name.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
dolChmod($filepath, $newmask='')
Change mod of a file.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
dolSaveMasterFile($filemaster)
Save content of a page on disk.
dolSaveLicense($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).
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).