dolibarr 24.0.0-beta
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($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' : $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' : $this->status).',';
218 $sql .= ' '.(!isset($this->fk_default_home) ? 'NULL' : $this->fk_default_home).',';
219 $sql .= ' '.(!isset($this->virtualhost) ? 'NULL' : "'".$this->db->escape($this->virtualhost)."'").",";
220 $sql .= ' '.(!isset($this->fk_user_creat) ? $user->id : $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->escape($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($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) ? $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) ? $this->status : "null").',';
542 $sql .= ' fk_default_home = '.(($this->fk_default_home > 0) ? $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) ? $user->id : $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 setEventMessages('Failed to write file '.$filealias, null, 'errors');
838 }
839
840 $result = dolSavePageContent($filetplnew, $object, $objectpagenew);
841 if (!$result) {
842 setEventMessages('Failed to write file '.$filetplnew, null, 'errors');
843 }
844
845 if ($pageid == $oldidforhome) {
846 $newidforhome = $objectpagenew->id;
847 }
848 } else {
849 setEventMessages($objectpageold->error, $objectpageold->errors, 'errors');
850 $error++;
851 }
852 }
853 }
854
855 if (!$error) {
856 // Restore id of home page
857 $object->fk_default_home = $newidforhome;
858 $res = $object->update($user);
859 if (!($res > 0)) {
860 $error++;
861 setEventMessages($object->error, $object->errors, 'errors');
862 }
863
864 if (!$error) {
865 $filetpl = $pathofwebsitenew.'/page'.$newidforhome.'.tpl.php';
866 $filewrapper = $pathofwebsitenew.'/wrapper.php';
867
868 // Re-generates the index.php page to be the home page, and re-generates the wrapper.php
869 //--------------------------------------------------------------------------------------
870 $result = dolSaveIndexPage($pathofwebsitenew, $fileindex, $filetpl, $filewrapper, $object);
871 }
872 }
873
874 unset($object->context['createfromclone']);
875
876 // End
877 if (!$error) {
878 $this->db->commit();
879
880 return $object;
881 } else {
882 $this->db->rollback();
883
884 return -3;
885 }
886 }
887
899 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $maxlen = 24, $morecss = '')
900 {
901 global $langs;
902
903 $result = '';
904
905 $label = '<u>'.img_picto('', 'website', 'class="pictofixedwidth"').$langs->trans("WebSite").'</u>';
906 $label .= '<br>';
907 $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref.'<br>';
908 $label .= '<b>'.$langs->trans('MainLanguage').':</b> '.$this->lang;
909
910 // Links for internal access
911 /*
912 $linkstart = '<a href="'.DOL_URL_ROOT.'/website/index.php?website='.urlencode($this->ref).'"';
913 $linkstart .= ($notooltip ? '' : ' title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip'.($morecss ? ' '.$morecss : '').'"');
914 $linkstart .= '>';
915 */
916 if (!empty($this->virtualhost)) {
917 $linkstart = '<a target="_blank" rel="noopener" href="'.$this->virtualhost.'">';
918 $linkend = '</a>';
919 } else {
920 $linkstart = $linkend = '';
921 }
922
923 $result .= $linkstart;
924 if ($withpicto) {
925 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), 'class="pictofixedwidth'.($notooltip ? '' : ' classfortooltip').'"');
926 }
927 $result .= $this->ref;
928 $result .= $linkend;
929
930 return $result;
931 }
932
939 public function getLibStatut($mode = 0)
940 {
941 return $this->LibStatut($this->status, $mode);
942 }
943
944 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
952 public function LibStatut($status, $mode = 0)
953 {
954 // phpcs:enable
955 global $langs;
956
957 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
958 global $langs;
959 //$langs->load("mymodule");
960 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Offline');
961 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Online');
962 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Offline');
963 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Online');
964 }
965
966 $statusType = 'status5';
967 if ($status == self::STATUS_VALIDATED) {
968 $statusType = 'status4';
969 }
970
971 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
972 }
973
974
981 public function initAsSpecimen()
982 {
983 global $user;
984
985 $this->id = 0;
986 $this->specimen = 1;
987 $this->entity = 1;
988 $this->ref = 'myspecimenwebsite';
989 $this->description = 'A specimen website';
990 $this->lang = 'en';
991 $this->otherlang = 'fr,es';
992 $this->status = 1;
993 $this->fk_default_home = 0;
994 $this->virtualhost = 'http://myvirtualhost';
995 $this->fk_user_creat = $user->id;
996 $this->fk_user_modif = $user->id;
997 $this->date_creation = dol_now();
998 $this->tms = dol_now();
999
1000 return 1;
1001 }
1002
1003
1009 public function exportWebSite()
1010 {
1011 global $conf, $mysoc;
1012
1013 $website = $this;
1014
1015 if (empty($website->id) || empty($website->ref)) {
1016 setEventMessages("Website id or ref is not defined", null, 'errors');
1017 return '';
1018 }
1019
1020 dol_syslog("Create temp dir ".$conf->website->dir_temp);
1021 dol_mkdir($conf->website->dir_temp);
1022 if (!is_writable($conf->website->dir_temp)) {
1023 setEventMessages("Temporary dir ".$conf->website->dir_temp." is not writable", null, 'errors');
1024 return '';
1025 }
1026
1027 $destdir = $conf->website->dir_temp.'/'.$website->ref;
1028 dol_syslog("Clear temp dir ".$destdir);
1029 $count = 0;
1030 $countreallydeleted = 0;
1031 $counttodelete = dol_delete_dir_recursive($destdir, $count, 1, 0, $countreallydeleted);
1032 if ($counttodelete != $countreallydeleted) {
1033 setEventMessages("Failed to clean temp directory ".$destdir, null, 'errors');
1034 return '';
1035 }
1036
1037 $arrayreplacementinfilename = array();
1038 $arrayreplacementincss = array();
1039 $arrayreplacementincss['file=image/'.$website->ref.'/'] = "file=image/__WEBSITE_KEY__/";
1040 $arrayreplacementincss['file=js/'.$website->ref.'/'] = "file=js/__WEBSITE_KEY__/";
1041 $arrayreplacementincss['medias/image/'.$website->ref.'/'] = "medias/image/__WEBSITE_KEY__/";
1042 $arrayreplacementincss['medias/js/'.$website->ref.'/'] = "medias/js/__WEBSITE_KEY__/";
1043 if ($mysoc->logo_small) {
1044 $arrayreplacementincss['file=logos%2Fthumbs%2F'.$mysoc->logo_small] = "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__";
1045 }
1046 if ($mysoc->logo_mini) {
1047 $arrayreplacementincss['file=logos%2Fthumbs%2F'.$mysoc->logo_mini] = "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__";
1048 }
1049 if ($mysoc->logo) {
1050 $arrayreplacementincss['file=logos%2Fthumbs%2F'.$mysoc->logo] = "file=logos%2Fthumbs%2F__LOGO_KEY__";
1051 }
1052
1053 // Create output directories
1054 dol_syslog("Create containers dir");
1055 dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/containers');
1056 dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/medias/image/websitekey');
1057 dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/medias/js/websitekey');
1058
1059 // Copy files into 'containers'
1060 $srcdir = $conf->website->dir_output.'/'.$website->ref;
1061 $destdir = $conf->website->dir_temp.'/'.$website->ref.'/containers';
1062
1063 dol_syslog("Copy pages from ".$srcdir." into ".$destdir);
1064 dolCopyDir($srcdir, $destdir, '0', 1, $arrayreplacementinfilename, 2, array('old', 'back'), 1);
1065
1066 // Remove non required files (will be re-generated during the import)
1067 dol_delete_file($conf->website->dir_temp.'/'.$website->ref.'/containers/master.inc.php');
1068
1069 // Copy file README.md and LICENSE from directory containers into directory root
1070 if (dol_is_file($conf->website->dir_temp.'/'.$website->ref.'/containers/README.md')) {
1071 dol_copy($conf->website->dir_temp.'/'.$website->ref.'/containers/README.md', $conf->website->dir_temp.'/'.$website->ref.'/README.md');
1072 }
1073 if (dol_is_file($conf->website->dir_temp.'/'.$website->ref.'/containers/LICENSE')) {
1074 dol_copy($conf->website->dir_temp.'/'.$website->ref.'/containers/LICENSE', $conf->website->dir_temp.'/'.$website->ref.'/LICENSE');
1075 }
1076
1077 // Copy files into medias/image
1078 $srcdir = DOL_DATA_ROOT.'/medias/image/'.$website->ref;
1079 $destdir = $conf->website->dir_temp.'/'.$website->ref.'/medias/image/websitekey';
1080
1081 dol_syslog("Copy content from ".$srcdir." into ".$destdir);
1082 dolCopyDir($srcdir, $destdir, '0', 1, $arrayreplacementinfilename);
1083
1084 // Copy files into medias/js
1085 $srcdir = DOL_DATA_ROOT.'/medias/js/'.$website->ref;
1086 $destdir = $conf->website->dir_temp.'/'.$website->ref.'/medias/js/websitekey';
1087
1088 dol_syslog("Copy content from ".$srcdir." into ".$destdir);
1089 dolCopyDir($srcdir, $destdir, '0', 1, $arrayreplacementinfilename);
1090
1091 // Make some replacement into some files
1092 $cssindestdir = $conf->website->dir_temp.'/'.$website->ref.'/containers/styles.css.php';
1093 if (dol_is_file($cssindestdir)) {
1094 dolReplaceInFile($cssindestdir, $arrayreplacementincss);
1095 }
1096
1097 $htmldeaderindestdir = $conf->website->dir_temp.'/'.$website->ref.'/containers/htmlheader.html';
1098 if (dol_is_file($htmldeaderindestdir)) {
1099 dolReplaceInFile($htmldeaderindestdir, $arrayreplacementincss);
1100 }
1101
1102 // Build the website_page.sql file
1103 $filesql = $conf->website->dir_temp.'/'.$website->ref.'/website_pages.sql';
1104 $fp = fopen($filesql, "w");
1105 if (empty($fp)) {
1106 setEventMessages("Failed to create file ".$filesql, null, 'errors');
1107 return '';
1108 }
1109
1110 $objectpages = new WebsitePage($this->db);
1111 $listofpages = $objectpages->fetchAll($website->id);
1112
1113
1114 // Assign ->newid and ->newfk_page starting at 1.
1115 $i = 1;
1116 foreach ($listofpages as $pageid => $objectpageold) {
1117 $objectpageold->newid = $i;
1118 $i++;
1119 }
1120 $i = 1;
1121 foreach ($listofpages as $pageid => $objectpageold) {
1122 // Search newid
1123 $newfk_page = 0;
1124 foreach ($listofpages as $pageid2 => $objectpageold2) {
1125 if ($pageid2 == $objectpageold->fk_page) {
1126 $newfk_page = $objectpageold2->newid;
1127 break;
1128 }
1129 }
1130 $objectpageold->newfk_page = $newfk_page;
1131 $i++;
1132 }
1133
1134 $line = '-- File generated by Dolibarr '.DOL_VERSION.' --;'."\n";
1135 $line .= "\n";
1136 fwrite($fp, $line);
1137
1138 foreach ($listofpages as $pageid => $objectpageold) {
1139 $oldpageid = $objectpageold->id;
1140
1141 $allaliases = $objectpageold->pageurl;
1142 $allaliases .= ($objectpageold->aliasalt ? ','.$objectpageold->aliasalt : '');
1143
1144 if (!getDolGlobalInt('WEBSITE_EXPORT_KEEP_FILES_OF_PAGES')) {
1145 // We don't need to keep the PHP files of pages and aliases (they are regenerated at import) so we remove them.
1146 // Delete the pageX.tpl.php page
1147 dol_delete_file($conf->website->dir_temp.'/'.$website->ref.'/containers/page'.$objectpageold->id.'.tpl.php', 0, 0, 0, null, false, 0);
1148 // Delete the alias page
1149 dol_delete_file($conf->website->dir_temp.'/'.$website->ref.'/containers/'.$objectpageold->pageurl.'.php', 0, 0, 0, null, false, 0);
1150 dol_delete_file($conf->website->dir_temp.'/'.$website->ref.'/containers/*/'.$objectpageold->pageurl.'.php', 0, 0, 0, null, false, 0);
1151 // Delete alternative alias pages
1152 $arrayofaliases = explode(',', $objectpageold->aliasalt);
1153 foreach ($arrayofaliases as $tmpaliasalt) {
1154 dol_delete_file($conf->website->dir_temp.'/'.$website->ref.'/containers/'.trim($tmpaliasalt).'.php', 0, 0, 0, null, false, 0);
1155 dol_delete_file($conf->website->dir_temp.'/'.$website->ref.'/containers/*/'.trim($tmpaliasalt).'.php', 0, 0, 0, null, false, 0);
1156 }
1157 }
1158
1159 // This comment syntax is important, it is parsed by import to get information on page ID and all aliases to regenerate
1160 $line = '-- Page ID '.$objectpageold->newid.'__+MAX_llx_website_page__ - Aliases '.$allaliases.' --;'; // newid start at 1, 2...
1161 $line .= "\n";
1162 fwrite($fp, $line);
1163
1164 // Warning: We must keep llx_ here. It is a generic SQL.
1165 $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)';
1166 $line .= " VALUES(";
1167 $line .= $objectpageold->newid."__+MAX_llx_website_page__, ";
1168 $line .= ($objectpageold->newfk_page ? $this->db->escape($objectpageold->newfk_page)."__+MAX_llx_website_page__" : "null").", ";
1169 $line .= "__WEBSITE_ID__, ";
1170 $line .= "'".$this->db->escape($objectpageold->pageurl)."', ";
1171 $line .= "'".$this->db->escape($objectpageold->aliasalt)."', ";
1172 $line .= "'".$this->db->escape($objectpageold->title)."', ";
1173 $line .= "'".$this->db->escape($objectpageold->description)."', ";
1174 $line .= "'".$this->db->escape($objectpageold->lang)."', ";
1175 $line .= "'".$this->db->escape($objectpageold->image)."', ";
1176 $line .= "'".$this->db->escape($objectpageold->keywords)."', ";
1177 $line .= "'".$this->db->escape((string) $objectpageold->status)."', ";
1178 $line .= "'".$this->db->idate($objectpageold->date_creation)."', ";
1179 $line .= "'".$this->db->idate($objectpageold->date_modification)."', ";
1180 $line .= ($objectpageold->import_key ? "'".$this->db->escape((string) $objectpageold->import_key)."'" : "null").", ";
1181 $line .= "'".$this->db->escape($objectpageold->grabbed_from)."', ";
1182 $line .= "'".$this->db->escape($objectpageold->type_container)."', ";
1183
1184 // Make substitution with a generic path into htmlheader content
1185 $stringtoexport = $objectpageold->htmlheader;
1186 $stringtoexport = str_replace(array("\r\n", "\r", "\n"), "__N__", $stringtoexport);
1187 $stringtoexport = str_replace('file=image/'.$website->ref.'/', "file=image/__WEBSITE_KEY__/", $stringtoexport);
1188 $stringtoexport = str_replace('file=js/'.$website->ref.'/', "file=js/__WEBSITE_KEY__/", $stringtoexport);
1189 $stringtoexport = str_replace('medias/image/'.$website->ref.'/', "medias/image/__WEBSITE_KEY__/", $stringtoexport);
1190 $stringtoexport = str_replace('medias/js/'.$website->ref.'/', "medias/js/__WEBSITE_KEY__/", $stringtoexport);
1191
1192 $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_small, "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__", $stringtoexport);
1193 $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_mini, "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__", $stringtoexport);
1194 $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo, "file=logos%2Fthumbs%2F__LOGO_KEY__", $stringtoexport);
1195
1196 if (getDolGlobalString('WEBSITE_EXPORT_SQL_ON_SEVERAL_LINES')) {
1197 $line .= "/* new line */\n"; // Add a comment so we will able to restore a one line instruction on import
1198 }
1199 $line .= "'".$this->db->escape($stringtoexport)."', ";
1200
1201 // Make substitution with a generic path into page content
1202 $stringtoexport = $objectpageold->content;
1203 $stringtoexport = str_replace(array("\r\n", "\r", "\n"), "__N__", $stringtoexport);
1204 $stringtoexport = str_replace('file=image/'.$website->ref.'/', "file=image/__WEBSITE_KEY__/", $stringtoexport);
1205 $stringtoexport = str_replace('file=js/'.$website->ref.'/', "file=js/__WEBSITE_KEY__/", $stringtoexport);
1206 $stringtoexport = str_replace('medias/image/'.$website->ref.'/', "medias/image/__WEBSITE_KEY__/", $stringtoexport);
1207 $stringtoexport = str_replace('medias/js/'.$website->ref.'/', "medias/js/__WEBSITE_KEY__/", $stringtoexport);
1208 $stringtoexport = str_replace('"image/'.$website->ref.'/', '"image/__WEBSITE_KEY__/', $stringtoexport); // When we have a link src="image/websiteref/file.png" into html content
1209 $stringtoexport = str_replace('"/image/'.$website->ref.'/', '"/image/__WEBSITE_KEY__/', $stringtoexport); // When we have a link src="/image/websiteref/file.png" into html content
1210 $stringtoexport = str_replace('"js/'.$website->ref.'/', '"js/__WEBSITE_KEY__/', $stringtoexport);
1211 $stringtoexport = str_replace('"/js/'.$website->ref.'/', '"/js/__WEBSITE_KEY__/', $stringtoexport);
1212
1213 $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_small, "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__", $stringtoexport);
1214 $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_mini, "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__", $stringtoexport);
1215 $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo, "file=logos%2Fthumbs%2F__LOGO_KEY__", $stringtoexport);
1216
1217 if (getDolGlobalString('WEBSITE_EXPORT_SQL_ON_SEVERAL_LINES')) {
1218 $line .= "/* new line */\n"; // Add a comment so we will able to restore a one line instruction on import
1219 }
1220 $line .= "'".$this->db->escape($stringtoexport)."', ";
1221
1222 $line .= "'".$this->db->escape($objectpageold->author_alias)."', ";
1223 $line .= (int) $objectpageold->allowed_in_frames;
1224 $line .= ");";
1225 $line .= "\n";
1226
1227 fwrite($fp, $line);
1228
1229 // Add line to update home page id during import
1230 //var_dump($this->fk_default_home.' - '.$objectpageold->id.' - '.$objectpageold->newid);exit;
1231 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
1232 // Warning: We must keep llx_ here. It is a generic SQL.
1233 $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__;";
1234 $line .= "\n";
1235 fwrite($fp, $line);
1236 }
1237
1238 fwrite($fp, "\n");
1239 }
1240
1241 $line = "\n-- For Dolibarr v14+ --;\n";
1242 $line .= "UPDATE llx_website SET lang = '".$this->db->escape($this->lang)."' WHERE rowid = __WEBSITE_ID__;\n";
1243 $line .= "UPDATE llx_website SET otherlang = '".$this->db->escape($this->otherlang)."' WHERE rowid = __WEBSITE_ID__;\n";
1244 $line .= "\n";
1245 fwrite($fp, $line);
1246
1247 fclose($fp);
1248
1249 dolChmod($filesql);
1250
1251 // Build zip file
1252 $filedir = $conf->website->dir_temp.'/'.$website->ref.'/.';
1253 $fileglob = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-*.zip';
1254 $filename = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-'.dol_print_date(dol_now(), 'dayhourlog').'-V'.((float) DOL_VERSION).'.zip';
1255
1256 dol_delete_file($fileglob, 0);
1257
1258 $result = dol_compress_dir($filedir, $filename, 'zip');
1259
1260 if ($result > 0) {
1261 return $filename;
1262 } else {
1263 global $errormsg;
1264 $this->error = $errormsg;
1265 return '';
1266 }
1267 }
1268
1269
1276 public function importWebSite($pathtofile)
1277 {
1278 global $conf, $mysoc;
1279
1280 $error = 0;
1281
1282 $pathtofile = dol_sanitizePathName($pathtofile);
1283 if (!file_exists($pathtofile)) {
1284 $this->error = 'The zip file "'.$pathtofile.'" is not found';
1285 return -9;
1286 }
1287
1288 $object = $this;
1289 if (empty($object->ref)) {
1290 $this->error = 'Function importWebSite called on object not loaded (object->ref is empty)';
1291 return -2;
1292 }
1293
1294 dol_delete_dir_recursive($conf->website->dir_temp."/".$object->ref);
1295 dol_mkdir($conf->website->dir_temp.'/'.$object->ref);
1296
1297 $filename = basename($pathtofile);
1298 $reg = array();
1299 if (!preg_match('/^website_(.*)-(.*)$/', $filename, $reg)) {
1300 $this->errors[] = 'Bad format for filename '.$filename.'. Must be website_XXX-VERSION.';
1301 return -3;
1302 }
1303
1304 // Uncompress the zip
1305 $result = dol_uncompress($pathtofile, $conf->website->dir_temp.'/'.$object->ref);
1306
1307 if (!empty($result['error'])) {
1308 $this->errors[] = 'Failed to unzip file '.$pathtofile;
1309 return -4;
1310 }
1311
1312 $arrayreplacement = array();
1313 $arrayreplacement['__WEBSITE_ID__'] = $object->id;
1314 $arrayreplacement['__WEBSITE_KEY__'] = $object->ref;
1315 $arrayreplacement['__N__'] = $this->db->escape("\n"); // Restore \n
1316 $arrayreplacement['__LOGO_SMALL_KEY__'] = $this->db->escape($mysoc->logo_small);
1317 $arrayreplacement['__LOGO_MINI_KEY__'] = $this->db->escape($mysoc->logo_mini);
1318 $arrayreplacement['__LOGO_KEY__'] = $this->db->escape($mysoc->logo);
1319
1320
1321 // Copy containers directory
1322 dolCopyDir($conf->website->dir_temp.'/'.$object->ref.'/containers', $conf->website->dir_output.'/'.$object->ref, '0', 1); // Overwrite if exists
1323
1324 // Make replacement into css and htmlheader file
1325 $cssindestdir = $conf->website->dir_output.'/'.$object->ref.'/styles.css.php';
1326 $result = dolReplaceInFile($cssindestdir, $arrayreplacement);
1327
1328 $htmldeaderindestdir = $conf->website->dir_output.'/'.$object->ref.'/htmlheader.html';
1329 $result = dolReplaceInFile($htmldeaderindestdir, $arrayreplacement);
1330
1331 // Now generate the master.inc.php page
1332 $filemaster = $conf->website->dir_output.'/'.$object->ref.'/master.inc.php';
1333 $result = dolSaveMasterFile($filemaster);
1334 if (!$result) {
1335 $this->errors[] = 'Failed to write file '.$filemaster;
1336 $error++;
1337 }
1338
1339 // Copy dir medias/image/websitekey
1340 if (dol_is_dir($conf->website->dir_temp.'/'.$object->ref.'/medias/image/websitekey')) {
1341 $result = dolCopyDir($conf->website->dir_temp.'/'.$object->ref.'/medias/image/websitekey', $conf->website->dir_output.'/'.$object->ref.'/medias/image/'.$object->ref, '0', 1);
1342 if ($result < 0) {
1343 $this->error = 'Failed to copy files into '.$conf->website->dir_output.'/'.$object->ref.'/medias/image/'.$object->ref.'.';
1344 dol_syslog($this->error, LOG_WARNING);
1345 $this->errors[] = $this->error;
1346 return -5;
1347 }
1348 }
1349
1350 // Copy dir medias/js/websitekey
1351 if (dol_is_dir($conf->website->dir_temp.'/'.$object->ref.'/medias/js/websitekey')) {
1352 $result = dolCopyDir($conf->website->dir_temp.'/'.$object->ref.'/medias/js/websitekey', $conf->website->dir_output.'/'.$object->ref.'/medias/js/'.$object->ref, '0', 1);
1353 if ($result < 0) {
1354 $this->error = 'Failed to copy files into '.$conf->website->dir_output.'/'.$object->ref.'/medias/js/'.$object->ref.'.';
1355 dol_syslog($this->error, LOG_WARNING);
1356 $this->errors[] = $this->error;
1357 return -6;
1358 }
1359 }
1360
1361 $sqlfile = $conf->website->dir_temp."/".$object->ref.'/website_pages.sql';
1362
1363 $result = dolReplaceInFile($sqlfile, $arrayreplacement);
1364
1365 $this->db->begin();
1366
1367 // Search the $maxrowid because we need it later
1368 $sqlgetrowid = 'SELECT MAX(rowid) as max from '.MAIN_DB_PREFIX.'website_page';
1369 $maxrowid = 0;
1370 $resql = $this->db->query($sqlgetrowid);
1371 if ($resql) {
1372 $obj = $this->db->fetch_object($resql);
1373 $maxrowid = $obj->max;
1374 }
1375
1376 // Load sql record
1377 $runsql = run_sql($sqlfile, 1, 0, 0, '', 'none', 0, 1, 0, 0, 1, ''); // The maxrowid of table is searched into this function two
1378 if ($runsql <= 0) {
1379 $this->errors[] = 'Failed to load sql file '.$sqlfile.' (ret='.((int) $runsql).')';
1380 $error++;
1381 }
1382
1383 $objectpagestatic = new WebsitePage($this->db);
1384 $aliasesarray = null;
1385
1386 // Regenerate the php files for pages
1387 $fp = fopen($sqlfile, "r");
1388 if ($fp) {
1389 while (!feof($fp)) {
1390 $reg = array();
1391
1392 // Warning fgets with second parameter that is null or 0 hang.
1393 $buf = fgets($fp, 65000); // No needto have a high value here for second parameter. We will process only short lines starting with '-- Page ID ...'
1394 $newid = 0;
1395
1396 // Scan the line
1397 if (preg_match('/^-- Page ID (\d+)\s[^\s]+\s(\d+).*Aliases\s(.+)\s--;/i', $buf, $reg)) {
1398 // Example of line: "-- Page ID 179 -> 1__+MAX_llx_website_page__ - Aliases about-us --;"
1399 $oldid = (int) $reg[1];
1400 $newid = ((int) $reg[2] + $maxrowid);
1401 $aliasesarray = explode(',', $reg[3]);
1402
1403 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]);
1404
1405 //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);
1406 } elseif (preg_match('/^-- Page ID (\d+).*Aliases\s(.*)\s--;/i', $buf, $reg)) {
1407 // Example of line: "-- Page ID 1__+MAX_llx_website_page__ - Aliases about-us --;"
1408 $newid = ((int) $reg[1] + $maxrowid);
1409 $aliasesarray = explode(',', $reg[2]);
1410
1411 dol_syslog("In sql source file, we have the page with the new ID ".$newid.", and we must create the shortcut aliases: ".$reg[2]);
1412 }
1413
1414 if ($newid) {
1415 $objectpagestatic->fetch($newid);
1416
1417 // We regenerate the pageX.tpl.php
1418 $filetpl = $conf->website->dir_output.'/'.$object->ref.'/page'.$newid.'.tpl.php';
1419 $result = dolSavePageContent($filetpl, $object, $objectpagestatic);
1420 if (!$result) {
1421 $this->errors[] = 'Failed to write file '.basename($filetpl);
1422 $error++;
1423 }
1424
1425 // Regenerate also the main alias + alternative aliases pages
1426 if (is_array($aliasesarray)) {
1427 foreach ($aliasesarray as $aliasshortcuttocreate) {
1428 if (trim($aliasshortcuttocreate)) {
1429 $filealias = $conf->website->dir_output.'/'.$object->ref.'/'.trim($aliasshortcuttocreate).'.php';
1430 $result = dolSavePageAlias($filealias, $object, $objectpagestatic);
1431 if (!$result) {
1432 $this->errors[] = 'Failed to write file '.basename($filealias);
1433 $error++;
1434 }
1435 }
1436 }
1437 }
1438 }
1439 }
1440 }
1441
1442 // Read record of website that has been updated by the run_sql function previously called so we can get the
1443 // value of fk_default_home that is ID of home page
1444 $sql = "SELECT fk_default_home FROM ".MAIN_DB_PREFIX."website WHERE rowid = ".((int) $object->id);
1445 $resql = $this->db->query($sql);
1446 if ($resql) {
1447 $obj = $this->db->fetch_object($resql);
1448 if ($obj) {
1449 $object->fk_default_home = $obj->fk_default_home;
1450 } else {
1451 //$this->errors[] = 'Failed to get the Home page';
1452 //$error++;
1453 }
1454 }
1455
1456 // Regenerate the index.php page to point to the new index page
1457 $pathofwebsite = $conf->website->dir_output.'/'.$object->ref;
1458 dolSaveIndexPage($pathofwebsite, $pathofwebsite.'/index.php', $pathofwebsite.'/page'.$object->fk_default_home.'.tpl.php', $pathofwebsite.'/wrapper.php', $object);
1459
1460 //$this->initFilesStatus($pathofwebsite);
1461
1462 if ($error) {
1463 $this->db->rollback();
1464 return -1;
1465 } else {
1466 $this->db->commit();
1467 return $object->id;
1468 }
1469 }
1470
1477 public function rebuildWebSiteFiles()
1478 {
1479 global $conf;
1480
1481 $error = 0;
1482
1483 $object = $this;
1484 if (empty($object->ref)) {
1485 $this->error = 'Function rebuildWebSiteFiles called on object not loaded (object->ref is empty)';
1486 return -1;
1487 }
1488
1489 $objectpagestatic = new WebsitePage($this->db);
1490
1491 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."website_page WHERE fk_website = ".((int) $this->id);
1492
1493 $resql = $this->db->query($sql);
1494 if (!$resql) {
1495 $this->error = $this->db->lasterror();
1496 return -1;
1497 }
1498
1499 $num = $this->db->num_rows($resql);
1500
1501 // Loop on each container/page
1502 $i = 0;
1503 while ($i < $num) {
1504 $obj = $this->db->fetch_object($resql);
1505
1506 $newid = $obj->rowid;
1507
1508 $objectpagestatic->fetch($newid);
1509
1510 $aliasesarray = explode(',', $objectpagestatic->aliasalt);
1511
1512 $filetpl = $conf->website->dir_output.'/'.$object->ref.'/page'.$newid.'.tpl.php';
1513 $result = dolSavePageContent($filetpl, $object, $objectpagestatic);
1514 if (!$result) {
1515 $this->errors[] = 'Failed to write file '.basename($filetpl);
1516 $error++;
1517 }
1518
1519 // Add main alias to list of alternative aliases
1520 if (!empty($objectpagestatic->pageurl) && !in_array($objectpagestatic->pageurl, $aliasesarray)) {
1521 $aliasesarray[] = $objectpagestatic->pageurl;
1522 }
1523
1524 // Regenerate also all aliases pages (pages with a natural name) by calling dolSavePageAlias()
1525 if (is_array($aliasesarray)) {
1526 foreach ($aliasesarray as $aliasshortcuttocreate) {
1527 if (trim($aliasshortcuttocreate)) {
1528 $filealias = $conf->website->dir_output.'/'.$object->ref.'/'.trim($aliasshortcuttocreate).'.php';
1529 $result = dolSavePageAlias($filealias, $object, $objectpagestatic); // This includes also a copy into sublanguage directories.
1530 if (!$result) {
1531 $this->errors[] = 'Failed to write file '.basename($filealias);
1532 $error++;
1533 }
1534 }
1535 }
1536 }
1537
1538 $i++;
1539 }
1540
1541 if (!$error) {
1542 // Save index.php and wrapper.php
1543 $pathofwebsite = $conf->website->dir_output.'/'.$object->ref;
1544 $fileindex = $pathofwebsite.'/index.php';
1545 $filetpl = '';
1546 if ($object->fk_default_home > 0) {
1547 $filetpl = $pathofwebsite.'/page'.$object->fk_default_home.'.tpl.php';
1548 }
1549 $filewrapper = $pathofwebsite.'/wrapper.php';
1550 dolSaveIndexPage($pathofwebsite, $fileindex, $filetpl, $filewrapper, $object); // This includes also a version of index.php into sublanguage directories
1551 }
1552
1553 // Erase cache files
1554 $filecacheglob = $conf->website->dir_output.'/temp/'.$object->ref.'-*.php.cache';
1555 dol_delete_file($filecacheglob, 0, 1, 1, null, false, 0, 1);
1556
1557 if ($error) {
1558 return -1;
1559 } else {
1560 return $num;
1561 }
1562 }
1563
1569 public function isMultiLang()
1570 {
1571 return !empty($this->otherlang);
1572 }
1573
1583 public function componentSelectLang($languagecodes, $weblangs, $morecss = '', $htmlname = '')
1584 {
1585 global $websitepagefile, $website;
1586 '@phan-var-force Website $website';
1587
1588 if (!is_object($weblangs)) {
1589 return 'ERROR componentSelectLang called with parameter $weblangs not defined';
1590 }
1591
1592 $arrayofspecialmainlanguages = array(
1593 'en' => 'en_US',
1594 'sq' => 'sq_AL',
1595 'ar' => 'ar_SA',
1596 'eu' => 'eu_ES',
1597 'bn' => 'bn_DB',
1598 'bs' => 'bs_BA',
1599 'ca' => 'ca_ES',
1600 'zh' => 'zh_CN',
1601 'cs' => 'cs_CZ',
1602 'da' => 'da_DK',
1603 'et' => 'et_EE',
1604 'ka' => 'ka_GE',
1605 'el' => 'el_GR',
1606 'he' => 'he_IL',
1607 'kn' => 'kn_IN',
1608 'km' => 'km_KH',
1609 'ko' => 'ko_KR',
1610 'lo' => 'lo_LA',
1611 'nb' => 'nb_NO',
1612 'fa' => 'fa_IR',
1613 'sr' => 'sr_RS',
1614 'sl' => 'sl_SI',
1615 'uk' => 'uk_UA',
1616 'vi' => 'vi_VN'
1617 );
1618
1619 // Load tmppage if we have $websitepagefile defined
1620 $tmppage = new WebsitePage($this->db);
1621
1622 $pageid = 0;
1623 if (!empty($websitepagefile)) {
1624 $websitepagefileshort = basename($websitepagefile);
1625 if ($websitepagefileshort == 'index.php') {
1626 $pageid = $website->fk_default_home;
1627 } else {
1628 $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), $websitepagefileshort);
1629 }
1630 if ($pageid > 0) {
1631 $tmppage->fetch($pageid);
1632 }
1633 }
1634
1635 // Fill $languagecodes array with existing translation, nothing if none
1636 if (!is_array($languagecodes) && $pageid > 0) {
1637 $languagecodes = array();
1638
1639 $sql = "SELECT wp.rowid, wp.lang, wp.pageurl, wp.fk_page";
1640 $sql .= " FROM ".MAIN_DB_PREFIX."website_page as wp";
1641 $sql .= " WHERE wp.fk_website = ".((int) $website->id);
1642 $sql .= " AND (wp.fk_page = ".((int) $pageid)." OR wp.rowid = ".((int) $pageid);
1643 if ($tmppage->fk_page > 0) {
1644 $sql .= " OR wp.fk_page = ".((int) $tmppage->fk_page)." OR wp.rowid = ".((int) $tmppage->fk_page);
1645 }
1646 $sql .= ")";
1647
1648 $resql = $this->db->query($sql);
1649 if ($resql) {
1650 while ($obj = $this->db->fetch_object($resql)) {
1651 $newlang = $obj->lang;
1652 if ($obj->rowid == $pageid) {
1653 $newlang = $obj->lang;
1654 }
1655 if (!in_array($newlang, $languagecodes)) {
1656 $languagecodes[] = $newlang;
1657 }
1658 }
1659 }
1660 }
1661 // Now $languagecodes is always an array. Example array('en', 'fr', 'es');
1662
1663 $languagecodeselected = substr($weblangs->defaultlang, 0, 2); // Because we must init with a value, but real value is the lang of main parent container
1664 if (!empty($websitepagefile)) {
1665 $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), basename($websitepagefile));
1666 if ($pageid > 0) {
1667 $pagelang = substr($tmppage->lang, 0, 2);
1668 $languagecodeselected = substr($pagelang, 0, 2);
1669 if (!in_array($pagelang, $languagecodes)) {
1670 $languagecodes[] = $pagelang; // We add language code of page into combo list
1671 }
1672 }
1673 }
1674
1675 $weblangs->load('languages');
1676 //var_dump($weblangs->defaultlang);
1677
1678 $url = $_SERVER["REQUEST_URI"];
1679 $url = preg_replace('/(\?|&)l=([a-zA-Z_]*)/', '', $url); // We remove param l from url
1680 //$url = preg_replace('/(\?|&)lang=([a-zA-Z_]*)/', '', $url); // We remove param lang from url
1681 $url .= (preg_match('/\?/', $url) ? '&' : '?').'l=';
1682 if (!preg_match('/^\//', $url)) {
1683 $url = '/'.$url;
1684 }
1685
1686 $HEIGHTOPTION = 40;
1687 $MAXHEIGHT = 4 * $HEIGHTOPTION;
1688 $nboflanguage = count($languagecodes);
1689
1690 $out = '<!-- componentSelectLang'.$htmlname.' -->'."\n";
1691
1692 $out .= '<style>';
1693 $out .= '.componentSelectLang'.$htmlname.':hover { height: '.min($MAXHEIGHT, ($HEIGHTOPTION * $nboflanguage)).'px; overflow-x: hidden; overflow-y: '.((($HEIGHTOPTION * $nboflanguage) > $MAXHEIGHT) ? ' scroll' : 'hidden').'; }'."\n";
1694 $out .= '.componentSelectLang'.$htmlname.' li { line-height: '.$HEIGHTOPTION.'px; }'."\n";
1695 $out .= '.componentSelectLang'.$htmlname.' {
1696 display: inline-block;
1697 padding: 0;
1698 height: '.$HEIGHTOPTION.'px;
1699 overflow: hidden;
1700 transition: all .3s ease;
1701 margin: 0 0 0 0;
1702 vertical-align: top;
1703 }
1704 .componentSelectLang'.$htmlname.':hover, .componentSelectLang'.$htmlname.':hover a { background-color: #fff; color: #000 !important; }
1705 ul.componentSelectLang'.$htmlname.' { width: 150px; }
1706 ul.componentSelectLang'.$htmlname.':hover .fa { visibility: hidden; }
1707 .componentSelectLang'.$htmlname.' a { text-decoration: none; width: 100%; }
1708 .componentSelectLang'.$htmlname.' li { display: block; padding: 0px 15px; margin-left: 0; margin-right: 0; }
1709 .componentSelectLang'.$htmlname.' li:hover { background-color: #EEE; }
1710 ';
1711 $out .= '</style>';
1712 $out .= '<ul class="componentSelectLang'.$htmlname.($morecss ? ' '.$morecss : '').'">';
1713
1714 if ($languagecodeselected) {
1715 // Convert $languagecodeselected into a long language code
1716 if (strlen($languagecodeselected) == 2) {
1717 $languagecodeselected = (string) (empty($arrayofspecialmainlanguages[$languagecodeselected]) ? $languagecodeselected.'_'.strtoupper($languagecodeselected) : $arrayofspecialmainlanguages[$languagecodeselected]);
1718 }
1719
1720 $countrycode = strtolower(substr($languagecodeselected, -2));
1721 $label = $weblangs->trans("Language_".$languagecodeselected);
1722 if ($countrycode == 'us') {
1723 $label = preg_replace('/\s*\‍(.*\‍)/', '', $label);
1724 }
1725 $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>';
1726 $out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
1727 $out .= '</a></li>';
1728 }
1729 $i = 0;
1730 if (is_array($languagecodes)) {
1731 foreach ($languagecodes as $languagecode) {
1732 // Convert $languagecode into a long language code
1733 if (strlen($languagecode) == 2) {
1734 $languagecode = (empty($arrayofspecialmainlanguages[$languagecode]) ? $languagecode.'_'.strtoupper($languagecode) : $arrayofspecialmainlanguages[$languagecode]);
1735 }
1736
1737 if ($languagecode == $languagecodeselected) {
1738 continue; // Already output
1739 }
1740
1741 $countrycode = strtolower(substr($languagecode, -2));
1742 $label = $weblangs->trans("Language_".$languagecode);
1743 if ($countrycode == 'us') {
1744 $label = preg_replace('/\s*\‍(.*\‍)/', '', $label);
1745 }
1746 $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>';
1747 if (empty($i) && empty($languagecodeselected)) {
1748 $out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
1749 }
1750 $out .= '</a></li>';
1751 $i++;
1752 }
1753 }
1754 $out .= '</ul>';
1755
1756 return $out;
1757 }
1758
1766 public function overwriteTemplate(string $pathtotmpzip, $exportPath = '')
1767 {
1768 global $conf;
1769
1770 $website = $this;
1771 if (empty($website->id) || empty($website->ref)) {
1772 setEventMessages("Website id or ref is not defined", null, 'errors');
1773 return -1;
1774 }
1775 if (empty($website->name_template) && empty($exportPath)) {
1776 setEventMessages("To export the website template into a directory of the server, the name of the directory/template must be provided.", null, 'errors');
1777 return -1;
1778 }
1779 if (!is_writable($conf->website->dir_temp)) {
1780 setEventMessages("Temporary dir ".$conf->website->dir_temp." is not writable", null, 'errors');
1781 return -1;
1782 }
1783
1784 $destdir = null; // Otherwise only set when 'WEBSITE_ALLOW_OVERWRITE_GIT_SOURCE' is not falsy.
1785 $destdirrel = ''; // Otherwise only set when 'WEBSITE_ALLOW_OVERWRITE_GIT_SOURCE' is not falsy.
1786 // Replace modified files into the doctemplates directory.
1787 if (getDolGlobalString('WEBSITE_ALLOW_OVERWRITE_GIT_SOURCE')) {
1788 // If the user has not specified a path
1789 if (empty($exportPath)) {
1790 $destdirrel = 'install/doctemplates/websites/'.$website->name_template;
1791 $destdir = DOL_DOCUMENT_ROOT.'/'.$destdirrel;
1792 } else {
1793 $exportPath = rtrim($exportPath, '/');
1794 if (strpos($exportPath, '..') !== false) {
1795 setEventMessages("Invalid path.", null, 'errors');
1796 return -1;
1797 }
1798 // if path start with / (absolute path)
1799 if (strpos($exportPath, '/') === 0 || preg_match('/^[a-zA-Z]:/', $exportPath)) {
1800 if (!is_dir($exportPath)) {
1801 setEventMessages("The specified absolute path does not exist.", null, 'errors');
1802 return -1;
1803 }
1804
1805 if (!is_writable($exportPath)) {
1806 setEventMessages("The specified absolute path is not writable.", null, 'errors');
1807 return -1;
1808 }
1809 $destdirrel = $exportPath;
1810 $destdir = $exportPath;
1811 } else {
1812 // relatif path
1813 $destdirrel = 'install/doctemplates/websites/'.$exportPath;
1814 $destdir = DOL_DOCUMENT_ROOT.'/'.$destdirrel;
1815 }
1816 }
1817 }
1818
1819 if ($destdir === null) {
1820 setEventMessages("The destination path is not determined.", null, 'errors');
1821 return -1;
1822 }
1823
1824 dol_mkdir($destdir);
1825
1826 if (!is_writable($destdir)) {
1827 setEventMessages("The specified path ".$destdir." is not writable.", null, 'errors');
1828 return -1;
1829 }
1830
1831 // Export on target sources
1832 $resultarray = dol_uncompress($pathtotmpzip, $destdir);
1833
1834 // Remove the file README.md and LICENSE from the $destdir/containers
1835 if (dol_is_file($destdir.'/containers/README.md')) {
1836 dol_move($destdir.'/containers/README.md', $destdir.'/README.md', '0', 1, 0, 0);
1837 }
1838 if (dol_is_file($destdir.'/containers/LICENSE')) {
1839 dol_move($destdir.'/containers/LICENSE', $destdir.'/LICENSE', '0', 1, 0, 0);
1840 }
1841 /*
1842 if (empty($exportPath)) {
1843 dol_delete_file($destdir.'/containers/README.md');
1844 dol_delete_file($destdir.'/containers/LICENSE');
1845 }
1846 */
1847
1848 // Remove non required files (will be re-generated during the import)
1849 dol_delete_file($destdir.'/containers/index.php');
1850 dol_delete_file($destdir.'/containers/master.inc.php');
1851
1852 // Now we remove the flag o+x on files
1853 // TODO
1854
1855 if (!empty($resultarray)) {
1856 setEventMessages("Error, failed to unzip the export into target dir ".$destdir.": ".implode(',', $resultarray), null, 'errors');
1857 } else {
1858 setEventMessages("Website content written into ".$destdirrel, null, 'mesgs');
1859 }
1860
1861 header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website->ref);
1862 exit();
1863 }
1864
1870 protected function extractNumberFromFilename($filename)
1871 {
1872 $matches = [];
1873 if (preg_match('/page(\d+)\.tpl\.php/', $filename, $matches)) {
1874 return (int) $matches[1];
1875 }
1876 return -1;
1877 }
1878
1884 public function setTemplateName($name_template)
1885 {
1886 $this->db->begin();
1887
1888 $sql = "UPDATE ".$this->db->prefix()."website SET";
1889 $sql .= " name_template = '".$this->db->escape($name_template)."'";
1890 $sql .= " WHERE rowid = ".(int) $this->id;
1891 $result = $this->db->query($sql);
1892
1893 if ($result) {
1894 $this->db->commit();
1895 return 1;
1896 } else {
1897 $this->db->rollback();
1898 return -1;
1899 }
1900 }
1901
1909 public function compareFichierModifie($dossierSource, $dossierDestination, $fichierModifie)
1910 {
1911
1912 $fichiersSource = [];
1913 $fichiersDestination = [];
1914
1915 $fichierWithNoPage = [];
1916 $fichierWithNoPageInDest = [];
1917
1918 // Filter source files
1919 foreach (dol_dir_list($dossierSource, "files") as $file) {
1920 if (preg_match('/^page\d+/', $file['name']) && !str_contains($file['name'], '.old')) {
1921 $fichiersSource[] = $file;
1922 } else {
1923 $fichierWithNoPage[] = $file;
1924 }
1925 }
1926
1927 // Filter destination files
1928 foreach (dol_dir_list($dossierDestination, "all", 1) as $file) {
1929 if (preg_match('/^page\d+/', $file['name']) && !str_contains($file['name'], '.old')) {
1930 $fichiersDestination[] = $file;
1931 } else {
1932 $fichierWithNoPageInDest[] = $file;
1933 }
1934 }
1935
1936 // find index source and search it in folder destination
1937 $numOfPageSource = 0;
1938 foreach ($fichiersSource as $index => $file) {
1939 if ($file['name'] == basename($fichierModifie['fullname'])) {
1940 $numOfPageSource = $this->extractNumberFromFilename($file['name']);
1941 break;
1942 }
1943 }
1944
1945 //search numPage where was declared
1946 $filesFound = array();
1947 foreach ($fichierWithNoPage as $filesource) {
1948 $fileContent = file_get_contents($filesource['fullname']);
1949 if (strpos($fileContent, "require './page".$numOfPageSource.".tpl.php'") !== false) {
1950 $filesFound = $filesource;
1951 break;
1952 }
1953 }
1954 // find file with same name and extract num page in destination folder
1955 $numPagesFound = '';
1956 foreach ($fichierWithNoPageInDest as $filedest) {
1957 if ($filedest['name'] === $filesFound['name']) {
1958 $fileContent = file_get_contents($filedest['fullname']);
1959 if (preg_match("/page\d+\.tpl\.php/", $fileContent, $matches)) {
1960 $numPagesFound = $matches[0];
1961 break;
1962 }
1963 }
1964 }
1965 //search file with the number of pages found
1966 $fileNeeded = array();
1967 foreach ($fichiersDestination as $index => $file) {
1968 if ($file['name'] == $numPagesFound) {
1969 $fileNeeded = $file;
1970 break;
1971 }
1972 }
1973
1974 if (isset($fileNeeded)) {
1975 $sourceContent = file_get_contents($fichierModifie['fullname']);
1976 if (file_exists($fileNeeded['fullname'])) {
1977 $destContent = file_get_contents($fileNeeded['fullname']);
1978
1979 $numOfPageDest = $this->extractNumberFromFilename($fileNeeded['name']);
1980 $differences = $this->showDifferences($destContent, $sourceContent, array($numOfPageDest,$numOfPageSource));
1981 $differences['file_destination'] = $fileNeeded;
1982 } else {
1983 $differences = array();
1984 }
1985 return $differences;
1986 }
1987 return array();
1988 }
1989
1995 private function normalizeString($str)
1996 {
1997 $str = str_replace("\r\n", "\n", $str);
1998 $str = str_replace("\r", "\n", $str);
1999 return $str;
2000 }
2001
2009 protected function showDifferences($str1, $str2, $exceptNumPge = array())
2010 {
2011 $diff = array();
2012 $str1 = $this->normalizeString($str1);
2013 $str2 = $this->normalizeString($str2);
2014
2015 $lines1 = explode("\n", $str1);
2016 $lines2 = explode("\n", $str2);
2017
2018 $linesShouldChange = array();
2019 $linesShouldNotChange = array();
2020 $linefound = array();
2021 $countNumPage = count($exceptNumPge);
2022
2023 for ($i = 0;$i < $countNumPage; $i++) {
2024 $linefound[$i] = array();
2025 $linefound[$i]['meta'] = '/content="' . preg_quote((string) $exceptNumPge[$i], '/') . '" \/>/';
2026 $linefound[$i]['output'] = '/dolWebsiteOutput\‍(\$tmp, "html", ' . preg_quote((string) $exceptNumPge[$i], '/') . '\‍);/';
2027 }
2028
2029 if (isset($linefound[1])) {
2030 $maxLines = max(count($lines1), count($lines2));
2031 for ($lineNum = 0; $lineNum < $maxLines; $lineNum++) {
2032 $lineContent1 = $lines1[$lineNum] ?? '';
2033 $lineContent2 = $lines2[$lineNum] ?? '';
2034 if (preg_match($linefound[0]['output'], $lineContent1)) {
2035 $linesShouldChange[] = $lineContent1;
2036 }
2037 if (preg_match($linefound[0]['meta'], $lineContent1)) {
2038 $linesShouldChange[] = $lineContent1;
2039 }
2040 if (preg_match($linefound[1]['output'], $lineContent2)) {
2041 $linesShouldNotChange[] = $lineContent2;
2042 }
2043 if (preg_match($linefound[1]['meta'], $lineContent2)) {
2044 $linesShouldNotChange[] = $lineContent2;
2045 }
2046 if ($lineContent1 !== $lineContent2) {
2047 if (isset($lines1[$lineNum]) && !isset($lines2[$lineNum])) {
2048 // Line deleted from the source
2049 $diff["Supprimée à la ligne " . ($lineNum + 1)] = $lineContent1;
2050 } elseif (!isset($lines1[$lineNum]) && isset($lines2[$lineNum])) {
2051 // New line added to the target
2052 $diff["Ajoutée à la ligne " . ($lineNum + 1)] = $lineContent2;
2053 } else {
2054 // Found a difference
2055 $diff["Modifiée à la ligne " . ($lineNum + 1)] = $lineContent2;
2056 }
2057 }
2058 }
2059 }
2060
2061
2062 if (empty($linesShouldChange)) {
2063 $linesShouldChange[0] = '<meta name="dolibarr:pageid" content="'.$exceptNumPge[0].'" />';
2064 $linesShouldChange[1] = '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "html", '.$exceptNumPge[0].');';
2065 }
2066
2067 $replacementMapping = array();
2068 if (!empty($linesShouldNotChange)) {
2069 $i = 0;
2070 foreach ($linesShouldNotChange as $numLigne => $ligneRemplacement) {
2071 if (isset($linesShouldChange[$numLigne])) {
2072 $replacementMapping[$ligneRemplacement] = $linesShouldChange[$numLigne];
2073 } else {
2074 $replacementMapping[$ligneRemplacement] = $linesShouldChange[$i];
2075 }
2076 $i++;
2077 }
2078 $diff['lignes_dont_change'] = $replacementMapping;
2079 }
2080 // search path of image and replace it with the correct path
2081 $pattern = '/medias\/image\/'.preg_quote($this->ref, '/').'\/([^\'"\s]+)/';
2082
2083 foreach ($diff as $key => $value) {
2084 // Ensure the value is a string
2085 if (is_string($value)) {
2086 if (preg_match($pattern, $value)) {
2087 $newValue = preg_replace($pattern, 'medias/image/'.$this->name_template.'/$1', $value);
2088 $diff[$key] = $newValue;
2089 }
2090 }
2091 }
2092 return $diff;
2093 }
2094
2102 protected function replaceLineUsingNum($inplaceFile, $differences)
2103 {
2104 if (file_exists($inplaceFile)) {
2105 dolChmod($inplaceFile, '0664');
2106 }
2107 if (!is_writable($inplaceFile)) {
2108 return -2;
2109 }
2110
2111 unset($differences['file_destination']);
2112 $contentDest = file($inplaceFile, FILE_IGNORE_NEW_LINES);
2113 foreach ($differences as $key => $ligneSource) {
2114 $matches = array();
2115 if (preg_match('/(Ajoutée|Modifiée) à la ligne (\d+)/', $key, $matches)) {
2116 $typeModification = $matches[1];
2117 $numLigne = (int) $matches[2] - 1;
2118
2119 if ($typeModification === 'Ajoutée') {
2120 array_splice($contentDest, $numLigne, 0, $ligneSource);
2121 } elseif ($typeModification === 'Modifiée') {
2122 $contentDest[$numLigne] = $ligneSource;
2123 }
2124 } elseif (preg_match('/Supprimée à la ligne (\d+)/', $key, $matches)) {
2125 $numLigne = (int) $matches[1] - 1;
2126 unset($contentDest[$numLigne]);
2127 }
2128 }
2129 // Reindex the table keys
2130 $contentDest = array_values($contentDest);
2131 $stringreplacement = implode("\n", $contentDest);
2132
2133 file_put_contents($inplaceFile, $stringreplacement);
2134 dolChmod($inplaceFile);
2135
2136 foreach ($differences['lignes_dont_change'] as $linechanged => $line) {
2137 if (in_array($linechanged, $contentDest)) {
2138 dolReplaceInFile($inplaceFile, array($linechanged => $line));
2139 }
2140 }
2141
2142 return 0;
2143 }
2144}
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
Parent class of all other business classes (invoices, contracts, proposals, orders,...
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:168
global $mysoc
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:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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:64
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.
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_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.
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)
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
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).