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