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