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