dolibarr 21.0.0-beta
website.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2007-2018 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2014 Juanjo Menent <jmenent@2byte.es>
4 * Copyright (C) 2015 Florian Henry <florian.henry@open-concept.pro>
5 * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
6 * Copyright (C) 2018-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;
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
688 dol_delete_dir_recursive($pathofwebsite);
689 }
690
691 // Commit or rollback
692 if ($error) {
693 $this->db->rollback();
694
695 return -1 * $error;
696 } else {
697 $this->db->commit();
698
699 return 1;
700 }
701 }
702
713 public function createFromClone($user, $fromid, $newref, $newlang = '')
714 {
715 global $conf, $langs;
716 global $dolibarr_main_data_root;
717
718 $now = dol_now();
719 $error = 0;
720
721 dol_syslog(__METHOD__, LOG_DEBUG);
722
723 $newref = dol_sanitizeFileName($newref);
724
725 if (empty($newref)) {
726 $this->error = 'ErrorBadParameter newref';
727 return -1;
728 }
729
730 $object = new self($this->db);
731
732 // Check no site with ref exists
733 if ($object->fetch(0, $newref) > 0) {
734 $this->error = 'ErrorNewRefIsAlreadyUsed';
735 return -2;
736 }
737
738 $this->db->begin();
739
740 // Load source object
741 $object->fetch($fromid);
742
743 $oldidforhome = $object->fk_default_home;
744 $oldref = $object->ref;
745
746 $pathofwebsiteold = $dolibarr_main_data_root.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.dol_sanitizeFileName($oldref);
747 $pathofwebsitenew = $dolibarr_main_data_root.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.dol_sanitizeFileName($newref);
748 dol_delete_dir_recursive($pathofwebsitenew);
749
750 $fileindex = $pathofwebsitenew.'/index.php';
751
752 // Reset some properties
753 unset($object->id);
754 unset($object->fk_user_creat);
755 unset($object->import_key);
756
757 // Clear fields
758 $object->ref = $newref;
759 $object->fk_default_home = 0;
760 $object->virtualhost = '';
761 $object->date_creation = $now;
762 $object->fk_user_creat = $user->id;
763 $object->position = ((int) $object->position) + 1;
764 $object->status = self::STATUS_DRAFT;
765 if (empty($object->lang)) {
766 $object->lang = substr($langs->defaultlang, 0, 2); // Should not happen. Protection for corrupted site with no languages
767 }
768
769 // Create clone
770 $object->context['createfromclone'] = 'createfromclone';
771 $result = $object->create($user);
772 if ($result < 0) {
773 $error++;
774 $this->error = $object->error;
775 $this->errors = $object->errors;
776 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
777 }
778
779 if (!$error) {
780 // @phan-suppress-next-line PhanPluginSuspiciousParamOrder
781 dolCopyDir($pathofwebsiteold, $pathofwebsitenew, getDolGlobalString('MAIN_UMASK'), 0, [], 2);
782
783 // Check symlink to medias and restore it if ko
784 $pathtomedias = DOL_DATA_ROOT.'/medias'; // Target
785 $pathtomediasinwebsite = $pathofwebsitenew.'/medias'; // Source / Link name
786 if (!is_link(dol_osencode($pathtomediasinwebsite))) {
787 dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite);
788 dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists
789 $result = symlink($pathtomedias, $pathtomediasinwebsite);
790 }
791
792 // Copy images and js dir
793 $pathofmediasjsold = DOL_DATA_ROOT.'/medias/js/'.$oldref;
794 $pathofmediasjsnew = DOL_DATA_ROOT.'/medias/js/'.$newref;
795 dolCopyDir($pathofmediasjsold, $pathofmediasjsnew, getDolGlobalString('MAIN_UMASK'), 0);
796
797 $pathofmediasimageold = DOL_DATA_ROOT.'/medias/image/'.$oldref;
798 $pathofmediasimagenew = DOL_DATA_ROOT.'/medias/image/'.$newref;
799 dolCopyDir($pathofmediasimageold, $pathofmediasimagenew, getDolGlobalString('MAIN_UMASK'), 0);
800
801 $newidforhome = 0;
802
803 // Duplicate pages
804 $objectpages = new WebsitePage($this->db);
805 $listofpages = $objectpages->fetchAll($fromid);
806 foreach ($listofpages as $pageid => $objectpageold) {
807 // Delete old file
808 $filetplold = $pathofwebsitenew.'/page'.$pageid.'.tpl.php';
809 dol_delete_file($filetplold);
810
811 // Create new file
812 $objectpagenew = $objectpageold->createFromClone($user, $pageid, $objectpageold->pageurl, '', 0, $object->id, 1);
813
814 //print $pageid.' = '.$objectpageold->pageurl.' -> '.$objectpagenew->id.' = '.$objectpagenew->pageurl.'<br>';
815 if (is_object($objectpagenew) && $objectpagenew->pageurl) {
816 $filealias = $pathofwebsitenew.'/'.$objectpagenew->pageurl.'.php';
817 $filetplnew = $pathofwebsitenew.'/page'.$objectpagenew->id.'.tpl.php';
818
819 // Save page alias
820 $result = dolSavePageAlias($filealias, $object, $objectpagenew);
821 if (!$result) {
822 setEventMessages('Failed to write file '.$filealias, null, 'errors');
823 }
824
825 $result = dolSavePageContent($filetplnew, $object, $objectpagenew);
826 if (!$result) {
827 setEventMessages('Failed to write file '.$filetplnew, null, 'errors');
828 }
829
830 if ($pageid == $oldidforhome) {
831 $newidforhome = $objectpagenew->id;
832 }
833 } else {
834 setEventMessages($objectpageold->error, $objectpageold->errors, 'errors');
835 $error++;
836 }
837 }
838 }
839
840 if (!$error) {
841 // Restore id of home page
842 $object->fk_default_home = $newidforhome;
843 $res = $object->update($user);
844 if (!($res > 0)) {
845 $error++;
846 setEventMessages($object->error, $object->errors, 'errors');
847 }
848
849 if (!$error) {
850 $filetpl = $pathofwebsitenew.'/page'.$newidforhome.'.tpl.php';
851 $filewrapper = $pathofwebsitenew.'/wrapper.php';
852
853 // Re-generates the index.php page to be the home page, and re-generates the wrapper.php
854 //--------------------------------------------------------------------------------------
855 $result = dolSaveIndexPage($pathofwebsitenew, $fileindex, $filetpl, $filewrapper, $object);
856 }
857 }
858
859 unset($object->context['createfromclone']);
860
861 // End
862 if (!$error) {
863 $this->db->commit();
864
865 return $object;
866 } else {
867 $this->db->rollback();
868
869 return -3;
870 }
871 }
872
884 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $maxlen = 24, $morecss = '')
885 {
886 global $langs;
887
888 $result = '';
889
890 $label = '<u>'.$langs->trans("WebSite").'</u>';
891 $label .= '<br>';
892 $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref.'<br>';
893 $label .= '<b>'.$langs->trans('MainLanguage').':</b> '.$this->lang;
894
895 $linkstart = '<a href="'.DOL_URL_ROOT.'/website/card.php?id='.$this->id.'"';
896 $linkstart .= ($notooltip ? '' : ' title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip'.($morecss ? ' '.$morecss : '').'"');
897 $linkstart .= '>';
898 $linkend = '</a>';
899
900 $linkstart = $linkend = '';
901
902 if ($withpicto) {
903 $result .= ($linkstart.img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? '' : 'class="classfortooltip"')).$linkend);
904 if ($withpicto != 2) {
905 $result .= ' ';
906 }
907 }
908 $result .= $linkstart.$this->ref.$linkend;
909 return $result;
910 }
911
918 public function getLibStatut($mode = 0)
919 {
920 return $this->LibStatut($this->status, $mode);
921 }
922
923 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
931 public function LibStatut($status, $mode = 0)
932 {
933 // phpcs:enable
934 global $langs;
935
936 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
937 global $langs;
938 //$langs->load("mymodule");
939 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Offline');
940 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Online');
941 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Offline');
942 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Online');
943 }
944
945 $statusType = 'status5';
946 if ($status == self::STATUS_VALIDATED) {
947 $statusType = 'status4';
948 }
949
950 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
951 }
952
953
960 public function initAsSpecimen()
961 {
962 global $user;
963
964 $this->id = 0;
965 $this->specimen = 1;
966 $this->entity = 1;
967 $this->ref = 'myspecimenwebsite';
968 $this->description = 'A specimen website';
969 $this->lang = 'en';
970 $this->otherlang = 'fr,es';
971 $this->status = 1;
972 $this->fk_default_home = 0;
973 $this->virtualhost = 'http://myvirtualhost';
974 $this->fk_user_creat = $user->id;
975 $this->fk_user_modif = $user->id;
976 $this->date_creation = dol_now();
977 $this->tms = dol_now();
978
979 return 1;
980 }
981
982
988 public function exportWebSite()
989 {
990 global $conf, $mysoc;
991
992 $website = $this;
993
994 if (empty($website->id) || empty($website->ref)) {
995 setEventMessages("Website id or ref is not defined", null, 'errors');
996 return '';
997 }
998
999 dol_syslog("Create temp dir ".$conf->website->dir_temp);
1000 dol_mkdir($conf->website->dir_temp);
1001 if (!is_writable($conf->website->dir_temp)) {
1002 setEventMessages("Temporary dir ".$conf->website->dir_temp." is not writable", null, 'errors');
1003 return '';
1004 }
1005
1006 $destdir = $conf->website->dir_temp.'/'.$website->ref;
1007 dol_syslog("Clear temp dir ".$destdir);
1008 $count = 0;
1009 $countreallydeleted = 0;
1010 $counttodelete = dol_delete_dir_recursive($destdir, $count, 1, 0, $countreallydeleted);
1011 if ($counttodelete != $countreallydeleted) {
1012 setEventMessages("Failed to clean temp directory ".$destdir, null, 'errors');
1013 return '';
1014 }
1015
1016 $arrayreplacementinfilename = array();
1017 $arrayreplacementincss = array();
1018 $arrayreplacementincss['file=image/'.$website->ref.'/'] = "file=image/__WEBSITE_KEY__/";
1019 $arrayreplacementincss['file=js/'.$website->ref.'/'] = "file=js/__WEBSITE_KEY__/";
1020 $arrayreplacementincss['medias/image/'.$website->ref.'/'] = "medias/image/__WEBSITE_KEY__/";
1021 $arrayreplacementincss['medias/js/'.$website->ref.'/'] = "medias/js/__WEBSITE_KEY__/";
1022 if ($mysoc->logo_small) {
1023 $arrayreplacementincss['file=logos%2Fthumbs%2F'.$mysoc->logo_small] = "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__";
1024 }
1025 if ($mysoc->logo_mini) {
1026 $arrayreplacementincss['file=logos%2Fthumbs%2F'.$mysoc->logo_mini] = "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__";
1027 }
1028 if ($mysoc->logo) {
1029 $arrayreplacementincss['file=logos%2Fthumbs%2F'.$mysoc->logo] = "file=logos%2Fthumbs%2F__LOGO_KEY__";
1030 }
1031
1032 // Create output directories
1033 dol_syslog("Create containers dir");
1034 dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/containers');
1035 dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/medias/image/websitekey');
1036 dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/medias/js/websitekey');
1037
1038 // Copy files into 'containers'
1039 $srcdir = $conf->website->dir_output.'/'.$website->ref;
1040 $destdir = $conf->website->dir_temp.'/'.$website->ref.'/containers';
1041
1042 dol_syslog("Copy pages from ".$srcdir." into ".$destdir);
1043 dolCopyDir($srcdir, $destdir, '0', 1, $arrayreplacementinfilename, 2, array('old', 'back'), 1);
1044
1045 // Copy file README.md and LICENSE from directory containers into directory root
1046 if (dol_is_file($conf->website->dir_temp.'/'.$website->ref.'/containers/README.md')) {
1047 dol_copy($conf->website->dir_temp.'/'.$website->ref.'/containers/README.md', $conf->website->dir_temp.'/'.$website->ref.'/README.md');
1048 }
1049 if (dol_is_file($conf->website->dir_temp.'/'.$website->ref.'/containers/LICENSE')) {
1050 dol_copy($conf->website->dir_temp.'/'.$website->ref.'/containers/LICENSE', $conf->website->dir_temp.'/'.$website->ref.'/LICENSE');
1051 }
1052
1053 // Copy files into medias/image
1054 $srcdir = DOL_DATA_ROOT.'/medias/image/'.$website->ref;
1055 $destdir = $conf->website->dir_temp.'/'.$website->ref.'/medias/image/websitekey';
1056
1057 dol_syslog("Copy content from ".$srcdir." into ".$destdir);
1058 dolCopyDir($srcdir, $destdir, '0', 1, $arrayreplacementinfilename);
1059
1060 // Copy files into medias/js
1061 $srcdir = DOL_DATA_ROOT.'/medias/js/'.$website->ref;
1062 $destdir = $conf->website->dir_temp.'/'.$website->ref.'/medias/js/websitekey';
1063
1064 dol_syslog("Copy content from ".$srcdir." into ".$destdir);
1065 dolCopyDir($srcdir, $destdir, '0', 1, $arrayreplacementinfilename);
1066
1067 // Make some replacement into some files
1068 $cssindestdir = $conf->website->dir_temp.'/'.$website->ref.'/containers/styles.css.php';
1069 if (dol_is_file($cssindestdir)) {
1070 dolReplaceInFile($cssindestdir, $arrayreplacementincss);
1071 }
1072
1073 $htmldeaderindestdir = $conf->website->dir_temp.'/'.$website->ref.'/containers/htmlheader.html';
1074 if (dol_is_file($htmldeaderindestdir)) {
1075 dolReplaceInFile($htmldeaderindestdir, $arrayreplacementincss);
1076 }
1077
1078 // Build the website_page.sql file
1079 $filesql = $conf->website->dir_temp.'/'.$website->ref.'/website_pages.sql';
1080 $fp = fopen($filesql, "w");
1081 if (empty($fp)) {
1082 setEventMessages("Failed to create file ".$filesql, null, 'errors');
1083 return '';
1084 }
1085
1086 $objectpages = new WebsitePage($this->db);
1087 $listofpages = $objectpages->fetchAll($website->id);
1088
1089
1090 // Assign ->newid and ->newfk_page starting at 1.
1091 $i = 1;
1092 foreach ($listofpages as $pageid => $objectpageold) {
1093 $objectpageold->newid = $i;
1094 $i++;
1095 }
1096 $i = 1;
1097 foreach ($listofpages as $pageid => $objectpageold) {
1098 // Search newid
1099 $newfk_page = 0;
1100 foreach ($listofpages as $pageid2 => $objectpageold2) {
1101 if ($pageid2 == $objectpageold->fk_page) {
1102 $newfk_page = $objectpageold2->newid;
1103 break;
1104 }
1105 }
1106 $objectpageold->newfk_page = $newfk_page;
1107 $i++;
1108 }
1109
1110 $line = '-- File generated by Dolibarr '.DOL_VERSION.' --;'."\n";
1111 $line .= "\n";
1112 fwrite($fp, $line);
1113
1114 foreach ($listofpages as $pageid => $objectpageold) {
1115 $oldpageid = $objectpageold->id;
1116
1117 $allaliases = $objectpageold->pageurl;
1118 $allaliases .= ($objectpageold->aliasalt ? ','.$objectpageold->aliasalt : '');
1119
1120 if (!getDolGlobalInt('WEBSITE_EXPORT_KEEP_FILES_OF_PAGES')) {
1121 // We don't need to keep the PHP files of pages and aliases (they are regenerated at import) so we remove them.
1122 // Delete the pageX.tpl.php page
1123 dol_delete_file($conf->website->dir_temp.'/'.$website->ref.'/containers/page'.$objectpageold->id.'.tpl.php', 0, 0, 0, null, false, 0);
1124 // Delete the alias page
1125 dol_delete_file($conf->website->dir_temp.'/'.$website->ref.'/containers/'.$objectpageold->pageurl.'.php', 0, 0, 0, null, false, 0);
1126 dol_delete_file($conf->website->dir_temp.'/'.$website->ref.'/containers/*/'.$objectpageold->pageurl.'.php', 0, 0, 0, null, false, 0);
1127 // Delete alternative alias pages
1128 $arrayofaliases = explode(',', $objectpageold->aliasalt);
1129 foreach ($arrayofaliases as $tmpaliasalt) {
1130 dol_delete_file($conf->website->dir_temp.'/'.$website->ref.'/containers/'.trim($tmpaliasalt).'.php', 0, 0, 0, null, false, 0);
1131 dol_delete_file($conf->website->dir_temp.'/'.$website->ref.'/containers/*/'.trim($tmpaliasalt).'.php', 0, 0, 0, null, false, 0);
1132 }
1133 }
1134
1135 // This comment syntax is important, it is parsed by import to get information on page ID and all aliases to regenerate
1136 $line = '-- Page ID '.$objectpageold->newid.'__+MAX_llx_website_page__ - Aliases '.$allaliases.' --;'; // newid start at 1, 2...
1137 $line .= "\n";
1138 fwrite($fp, $line);
1139
1140 // Warning: We must keep llx_ here. It is a generic SQL.
1141 $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)';
1142 $line .= " VALUES(";
1143 $line .= $objectpageold->newid."__+MAX_llx_website_page__, ";
1144 $line .= ($objectpageold->newfk_page ? $this->db->escape($objectpageold->newfk_page)."__+MAX_llx_website_page__" : "null").", ";
1145 $line .= "__WEBSITE_ID__, ";
1146 $line .= "'".$this->db->escape($objectpageold->pageurl)."', ";
1147 $line .= "'".$this->db->escape($objectpageold->aliasalt)."', ";
1148 $line .= "'".$this->db->escape($objectpageold->title)."', ";
1149 $line .= "'".$this->db->escape($objectpageold->description)."', ";
1150 $line .= "'".$this->db->escape($objectpageold->lang)."', ";
1151 $line .= "'".$this->db->escape($objectpageold->image)."', ";
1152 $line .= "'".$this->db->escape($objectpageold->keywords)."', ";
1153 $line .= "'".$this->db->escape($objectpageold->status)."', ";
1154 $line .= "'".$this->db->idate($objectpageold->date_creation)."', ";
1155 $line .= "'".$this->db->idate($objectpageold->date_modification)."', ";
1156 $line .= ($objectpageold->import_key ? "'".$this->db->escape($objectpageold->import_key)."'" : "null").", ";
1157 $line .= "'".$this->db->escape($objectpageold->grabbed_from)."', ";
1158 $line .= "'".$this->db->escape($objectpageold->type_container)."', ";
1159
1160 // Make substitution with a generic path into htmlheader content
1161 $stringtoexport = $objectpageold->htmlheader;
1162 $stringtoexport = str_replace(array("\r\n", "\r", "\n"), "__N__", $stringtoexport);
1163 $stringtoexport = str_replace('file=image/'.$website->ref.'/', "file=image/__WEBSITE_KEY__/", $stringtoexport);
1164 $stringtoexport = str_replace('file=js/'.$website->ref.'/', "file=js/__WEBSITE_KEY__/", $stringtoexport);
1165 $stringtoexport = str_replace('medias/image/'.$website->ref.'/', "medias/image/__WEBSITE_KEY__/", $stringtoexport);
1166 $stringtoexport = str_replace('medias/js/'.$website->ref.'/', "medias/js/__WEBSITE_KEY__/", $stringtoexport);
1167
1168 $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_small, "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__", $stringtoexport);
1169 $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_mini, "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__", $stringtoexport);
1170 $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo, "file=logos%2Fthumbs%2F__LOGO_KEY__", $stringtoexport);
1171 $line .= "'".$this->db->escape(str_replace(array("\r\n", "\r", "\n"), "__N__", $stringtoexport))."', "; // Replace \r \n to have record on 1 line
1172
1173 // Make substitution with a generic path into page content
1174 $stringtoexport = $objectpageold->content;
1175 $stringtoexport = str_replace(array("\r\n", "\r", "\n"), "__N__", $stringtoexport);
1176 $stringtoexport = str_replace('file=image/'.$website->ref.'/', "file=image/__WEBSITE_KEY__/", $stringtoexport);
1177 $stringtoexport = str_replace('file=js/'.$website->ref.'/', "file=js/__WEBSITE_KEY__/", $stringtoexport);
1178 $stringtoexport = str_replace('medias/image/'.$website->ref.'/', "medias/image/__WEBSITE_KEY__/", $stringtoexport);
1179 $stringtoexport = str_replace('medias/js/'.$website->ref.'/', "medias/js/__WEBSITE_KEY__/", $stringtoexport);
1180 $stringtoexport = str_replace('"image/'.$website->ref.'/', '"image/__WEBSITE_KEY__/', $stringtoexport); // When we have a link src="image/websiteref/file.png" into html content
1181 $stringtoexport = str_replace('"/image/'.$website->ref.'/', '"/image/__WEBSITE_KEY__/', $stringtoexport); // When we have a link src="/image/websiteref/file.png" into html content
1182 $stringtoexport = str_replace('"js/'.$website->ref.'/', '"js/__WEBSITE_KEY__/', $stringtoexport);
1183 $stringtoexport = str_replace('"/js/'.$website->ref.'/', '"/js/__WEBSITE_KEY__/', $stringtoexport);
1184
1185 $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_small, "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__", $stringtoexport);
1186 $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_mini, "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__", $stringtoexport);
1187 $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo, "file=logos%2Fthumbs%2F__LOGO_KEY__", $stringtoexport);
1188
1189
1190 $line .= "'".$this->db->escape($stringtoexport)."', "; // Replace \r \n to have record on 1 line
1191 $line .= "'".$this->db->escape($objectpageold->author_alias)."', ";
1192 $line .= (int) $objectpageold->allowed_in_frames;
1193 $line .= ");";
1194 $line .= "\n";
1195
1196 fwrite($fp, $line);
1197
1198 // Add line to update home page id during import
1199 //var_dump($this->fk_default_home.' - '.$objectpageold->id.' - '.$objectpageold->newid);exit;
1200 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
1201 // Warning: We must keep llx_ here. It is a generic SQL.
1202 $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__;";
1203 $line .= "\n";
1204 fwrite($fp, $line);
1205 }
1206
1207 fwrite($fp, "\n");
1208 }
1209
1210 $line = "\n-- For Dolibarr v14+ --;\n";
1211 $line .= "UPDATE llx_website SET lang = '".$this->db->escape($this->lang)."' WHERE rowid = __WEBSITE_ID__;\n";
1212 $line .= "UPDATE llx_website SET otherlang = '".$this->db->escape($this->otherlang)."' WHERE rowid = __WEBSITE_ID__;\n";
1213 $line .= "\n";
1214 fwrite($fp, $line);
1215
1216 fclose($fp);
1217
1218 dolChmod($filesql);
1219
1220 // Build zip file
1221 $filedir = $conf->website->dir_temp.'/'.$website->ref.'/.';
1222 $fileglob = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-*.zip';
1223 $filename = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-'.dol_print_date(dol_now(), 'dayhourlog').'-V'.((float) DOL_VERSION).'.zip';
1224
1225 dol_delete_file($fileglob, 0);
1226
1227 $result = dol_compress_dir($filedir, $filename, 'zip');
1228
1229 if ($result > 0) {
1230 return $filename;
1231 } else {
1232 global $errormsg;
1233 $this->error = $errormsg;
1234 return '';
1235 }
1236 }
1237
1238
1245 public function importWebSite($pathtofile)
1246 {
1247 global $conf, $mysoc;
1248
1249 $error = 0;
1250
1251 $pathtofile = dol_sanitizePathName($pathtofile);
1252 $object = $this;
1253 if (empty($object->ref)) {
1254 $this->error = 'Function importWebSite called on object not loaded (object->ref is empty)';
1255 return -2;
1256 }
1257
1258 dol_delete_dir_recursive($conf->website->dir_temp."/".$object->ref);
1259 dol_mkdir($conf->website->dir_temp.'/'.$object->ref);
1260
1261 $filename = basename($pathtofile);
1262 $reg = array();
1263 if (!preg_match('/^website_(.*)-(.*)$/', $filename, $reg)) {
1264 $this->errors[] = 'Bad format for filename '.$filename.'. Must be website_XXX-VERSION.';
1265 return -3;
1266 }
1267
1268 // Uncompress the zip
1269 $result = dol_uncompress($pathtofile, $conf->website->dir_temp.'/'.$object->ref);
1270
1271 if (!empty($result['error'])) {
1272 $this->errors[] = 'Failed to unzip file '.$pathtofile;
1273 return -4;
1274 }
1275
1276 $arrayreplacement = array();
1277 $arrayreplacement['__WEBSITE_ID__'] = $object->id;
1278 $arrayreplacement['__WEBSITE_KEY__'] = $object->ref;
1279 $arrayreplacement['__N__'] = $this->db->escape("\n"); // Restore \n
1280 $arrayreplacement['__LOGO_SMALL_KEY__'] = $this->db->escape($mysoc->logo_small);
1281 $arrayreplacement['__LOGO_MINI_KEY__'] = $this->db->escape($mysoc->logo_mini);
1282 $arrayreplacement['__LOGO_KEY__'] = $this->db->escape($mysoc->logo);
1283
1284
1285 // Copy containers directory
1286 dolCopyDir($conf->website->dir_temp.'/'.$object->ref.'/containers', $conf->website->dir_output.'/'.$object->ref, '0', 1); // Overwrite if exists
1287
1288 // Make replacement into css and htmlheader file
1289 $cssindestdir = $conf->website->dir_output.'/'.$object->ref.'/styles.css.php';
1290 $result = dolReplaceInFile($cssindestdir, $arrayreplacement);
1291
1292 $htmldeaderindestdir = $conf->website->dir_output.'/'.$object->ref.'/htmlheader.html';
1293 $result = dolReplaceInFile($htmldeaderindestdir, $arrayreplacement);
1294
1295 // Now generate the master.inc.php page
1296 $filemaster = $conf->website->dir_output.'/'.$object->ref.'/master.inc.php';
1297 $result = dolSaveMasterFile($filemaster);
1298 if (!$result) {
1299 $this->errors[] = 'Failed to write file '.$filemaster;
1300 $error++;
1301 }
1302
1303 // Copy dir medias/image/websitekey
1304 if (dol_is_dir($conf->website->dir_temp.'/'.$object->ref.'/medias/image/websitekey')) {
1305 $result = dolCopyDir($conf->website->dir_temp.'/'.$object->ref.'/medias/image/websitekey', $conf->website->dir_output.'/'.$object->ref.'/medias/image/'.$object->ref, '0', 1);
1306 if ($result < 0) {
1307 $this->error = 'Failed to copy files into '.$conf->website->dir_output.'/'.$object->ref.'/medias/image/'.$object->ref.'.';
1308 dol_syslog($this->error, LOG_WARNING);
1309 $this->errors[] = $this->error;
1310 return -5;
1311 }
1312 }
1313
1314 // Copy dir medias/js/websitekey
1315 if (dol_is_dir($conf->website->dir_temp.'/'.$object->ref.'/medias/js/websitekey')) {
1316 $result = dolCopyDir($conf->website->dir_temp.'/'.$object->ref.'/medias/js/websitekey', $conf->website->dir_output.'/'.$object->ref.'/medias/js/'.$object->ref, '0', 1);
1317 if ($result < 0) {
1318 $this->error = 'Failed to copy files into '.$conf->website->dir_output.'/'.$object->ref.'/medias/js/'.$object->ref.'.';
1319 dol_syslog($this->error, LOG_WARNING);
1320 $this->errors[] = $this->error;
1321 return -6;
1322 }
1323 }
1324
1325 $sqlfile = $conf->website->dir_temp."/".$object->ref.'/website_pages.sql';
1326
1327 $result = dolReplaceInFile($sqlfile, $arrayreplacement);
1328
1329 $this->db->begin();
1330
1331 // Search the $maxrowid because we need it later
1332 $sqlgetrowid = 'SELECT MAX(rowid) as max from '.MAIN_DB_PREFIX.'website_page';
1333 $resql = $this->db->query($sqlgetrowid);
1334 if ($resql) {
1335 $obj = $this->db->fetch_object($resql);
1336 $maxrowid = $obj->max;
1337 }
1338
1339 // Load sql record
1340 $runsql = run_sql($sqlfile, 1, 0, 0, '', 'none', 0, 1, 0, 0, 1); // The maxrowid of table is searched into this function two
1341 if ($runsql <= 0) {
1342 $this->errors[] = 'Failed to load sql file '.$sqlfile.' (ret='.((int) $runsql).')';
1343 $error++;
1344 }
1345
1346 $objectpagestatic = new WebsitePage($this->db);
1347
1348 // Regenerate the php files for pages
1349 $fp = fopen($sqlfile, "r");
1350 if ($fp) {
1351 while (!feof($fp)) {
1352 $reg = array();
1353
1354 // Warning fgets with second parameter that is null or 0 hang.
1355 $buf = fgets($fp, 65000);
1356 $newid = 0;
1357
1358 // Scan the line
1359 if (preg_match('/^-- Page ID (\d+)\s[^\s]+\s(\d+).*Aliases\s(.+)\s--;/i', $buf, $reg)) {
1360 // Example of line: "-- Page ID 179 -> 1__+MAX_llx_website_page__ - Aliases about-us --;"
1361 $oldid = (int) $reg[1];
1362 $newid = ((int) $reg[2] + $maxrowid);
1363 $aliasesarray = explode(',', $reg[3]);
1364
1365 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]);
1366
1367 //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);
1368 } elseif (preg_match('/^-- Page ID (\d+).*Aliases\s(.*)\s--;/i', $buf, $reg)) {
1369 // Example of line: "-- Page ID 1__+MAX_llx_website_page__ - Aliases about-us --;"
1370 $newid = ((int) $reg[1] + $maxrowid);
1371 $aliasesarray = explode(',', $reg[2]);
1372
1373 dol_syslog("In sql source file, we have the page with the new ID ".$newid.", and we must create the shortcut aliases: ".$reg[2]);
1374 }
1375
1376 if ($newid) {
1377 $objectpagestatic->fetch($newid);
1378
1379 // We regenerate the pageX.tpl.php
1380 $filetpl = $conf->website->dir_output.'/'.$object->ref.'/page'.$newid.'.tpl.php';
1381 $result = dolSavePageContent($filetpl, $object, $objectpagestatic);
1382 if (!$result) {
1383 $this->errors[] = 'Failed to write file '.basename($filetpl);
1384 $error++;
1385 }
1386
1387 // Regenerate also the main alias + alternative aliases pages
1388 if (is_array($aliasesarray)) {
1389 foreach ($aliasesarray as $aliasshortcuttocreate) {
1390 if (trim($aliasshortcuttocreate)) {
1391 $filealias = $conf->website->dir_output.'/'.$object->ref.'/'.trim($aliasshortcuttocreate).'.php';
1392 $result = dolSavePageAlias($filealias, $object, $objectpagestatic);
1393 if (!$result) {
1394 $this->errors[] = 'Failed to write file '.basename($filealias);
1395 $error++;
1396 }
1397 }
1398 }
1399 }
1400 }
1401 }
1402 }
1403
1404 // Read record of website that has been updated by the run_sql function previously called so we can get the
1405 // value of fk_default_home that is ID of home page
1406 $sql = "SELECT fk_default_home FROM ".MAIN_DB_PREFIX."website WHERE rowid = ".((int) $object->id);
1407 $resql = $this->db->query($sql);
1408 if ($resql) {
1409 $obj = $this->db->fetch_object($resql);
1410 if ($obj) {
1411 $object->fk_default_home = $obj->fk_default_home;
1412 } else {
1413 //$this->errors[] = 'Failed to get the Home page';
1414 //$error++;
1415 }
1416 }
1417
1418 // Regenerate the index.php page to point to the new index page
1419 $pathofwebsite = $conf->website->dir_output.'/'.$object->ref;
1420 dolSaveIndexPage($pathofwebsite, $pathofwebsite.'/index.php', $pathofwebsite.'/page'.$object->fk_default_home.'.tpl.php', $pathofwebsite.'/wrapper.php', $object);
1421
1422 //$this->initFilesStatus($pathofwebsite);
1423
1424 if ($error) {
1425 $this->db->rollback();
1426 return -1;
1427 } else {
1428 $this->db->commit();
1429 return $object->id;
1430 }
1431 }
1432
1439 public function rebuildWebSiteFiles()
1440 {
1441 global $conf;
1442
1443 $error = 0;
1444
1445 $object = $this;
1446 if (empty($object->ref)) {
1447 $this->error = 'Function rebuildWebSiteFiles called on object not loaded (object->ref is empty)';
1448 return -1;
1449 }
1450
1451 $objectpagestatic = new WebsitePage($this->db);
1452
1453 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."website_page WHERE fk_website = ".((int) $this->id);
1454
1455 $resql = $this->db->query($sql);
1456 if (!$resql) {
1457 $this->error = $this->db->lasterror();
1458 return -1;
1459 }
1460
1461 $num = $this->db->num_rows($resql);
1462
1463 // Loop on each container/page
1464 $i = 0;
1465 while ($i < $num) {
1466 $obj = $this->db->fetch_object($resql);
1467
1468 $newid = $obj->rowid;
1469
1470 $objectpagestatic->fetch($newid);
1471
1472 $aliasesarray = explode(',', $objectpagestatic->aliasalt);
1473
1474 $filetpl = $conf->website->dir_output.'/'.$object->ref.'/page'.$newid.'.tpl.php';
1475 $result = dolSavePageContent($filetpl, $object, $objectpagestatic);
1476 if (!$result) {
1477 $this->errors[] = 'Failed to write file '.basename($filetpl);
1478 $error++;
1479 }
1480
1481 // Add main alias to list of alternative aliases
1482 if (!empty($objectpagestatic->pageurl) && !in_array($objectpagestatic->pageurl, $aliasesarray)) {
1483 $aliasesarray[] = $objectpagestatic->pageurl;
1484 }
1485
1486 // Regenerate also all aliases pages (pages with a natural name) by calling dolSavePageAlias()
1487 if (is_array($aliasesarray)) {
1488 foreach ($aliasesarray as $aliasshortcuttocreate) {
1489 if (trim($aliasshortcuttocreate)) {
1490 $filealias = $conf->website->dir_output.'/'.$object->ref.'/'.trim($aliasshortcuttocreate).'.php';
1491 $result = dolSavePageAlias($filealias, $object, $objectpagestatic); // This includes also a copy into sublanguage directories.
1492 if (!$result) {
1493 $this->errors[] = 'Failed to write file '.basename($filealias);
1494 $error++;
1495 }
1496 }
1497 }
1498 }
1499
1500 $i++;
1501 }
1502
1503 if (!$error) {
1504 // Save index.php and wrapper.php
1505 $pathofwebsite = $conf->website->dir_output.'/'.$object->ref;
1506 $fileindex = $pathofwebsite.'/index.php';
1507 $filetpl = '';
1508 if ($object->fk_default_home > 0) {
1509 $filetpl = $pathofwebsite.'/page'.$object->fk_default_home.'.tpl.php';
1510 }
1511 $filewrapper = $pathofwebsite.'/wrapper.php';
1512 dolSaveIndexPage($pathofwebsite, $fileindex, $filetpl, $filewrapper, $object); // This includes also a version of index.php into sublanguage directories
1513 }
1514
1515 if ($error) {
1516 return -1;
1517 } else {
1518 return $num;
1519 }
1520 }
1521
1527 public function isMultiLang()
1528 {
1529 return !empty($this->otherlang);
1530 }
1531
1541 public function componentSelectLang($languagecodes, $weblangs, $morecss = '', $htmlname = '')
1542 {
1543 global $websitepagefile, $website;
1544 '@phan-var-force Website $website';
1545
1546 if (!is_object($weblangs)) {
1547 return 'ERROR componentSelectLang called with parameter $weblangs not defined';
1548 }
1549
1550 $arrayofspecialmainlanguages = array(
1551 'en' => 'en_US',
1552 'sq' => 'sq_AL',
1553 'ar' => 'ar_SA',
1554 'eu' => 'eu_ES',
1555 'bn' => 'bn_DB',
1556 'bs' => 'bs_BA',
1557 'ca' => 'ca_ES',
1558 'zh' => 'zh_CN',
1559 'cs' => 'cs_CZ',
1560 'da' => 'da_DK',
1561 'et' => 'et_EE',
1562 'ka' => 'ka_GE',
1563 'el' => 'el_GR',
1564 'he' => 'he_IL',
1565 'kn' => 'kn_IN',
1566 'km' => 'km_KH',
1567 'ko' => 'ko_KR',
1568 'lo' => 'lo_LA',
1569 'nb' => 'nb_NO',
1570 'fa' => 'fa_IR',
1571 'sr' => 'sr_RS',
1572 'sl' => 'sl_SI',
1573 'uk' => 'uk_UA',
1574 'vi' => 'vi_VN'
1575 );
1576
1577 // Load tmppage if we have $websitepagefile defined
1578 $tmppage = new WebsitePage($this->db);
1579
1580 $pageid = 0;
1581 if (!empty($websitepagefile)) {
1582 $websitepagefileshort = basename($websitepagefile);
1583 if ($websitepagefileshort == 'index.php') {
1584 $pageid = $website->fk_default_home;
1585 } else {
1586 $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), $websitepagefileshort);
1587 }
1588 if ($pageid > 0) {
1589 $tmppage->fetch($pageid);
1590 }
1591 }
1592
1593 // Fill $languagecodes array with existing translation, nothing if none
1594 if (!is_array($languagecodes) && $pageid > 0) {
1595 $languagecodes = array();
1596
1597 $sql = "SELECT wp.rowid, wp.lang, wp.pageurl, wp.fk_page";
1598 $sql .= " FROM ".MAIN_DB_PREFIX."website_page as wp";
1599 $sql .= " WHERE wp.fk_website = ".((int) $website->id);
1600 $sql .= " AND (wp.fk_page = ".((int) $pageid)." OR wp.rowid = ".((int) $pageid);
1601 if ($tmppage->fk_page > 0) {
1602 $sql .= " OR wp.fk_page = ".((int) $tmppage->fk_page)." OR wp.rowid = ".((int) $tmppage->fk_page);
1603 }
1604 $sql .= ")";
1605
1606 $resql = $this->db->query($sql);
1607 if ($resql) {
1608 while ($obj = $this->db->fetch_object($resql)) {
1609 $newlang = $obj->lang;
1610 if ($obj->rowid == $pageid) {
1611 $newlang = $obj->lang;
1612 }
1613 if (!in_array($newlang, $languagecodes)) {
1614 $languagecodes[] = $newlang;
1615 }
1616 }
1617 }
1618 }
1619 // Now $languagecodes is always an array. Example array('en', 'fr', 'es');
1620
1621 $languagecodeselected = substr($weblangs->defaultlang, 0, 2); // Because we must init with a value, but real value is the lang of main parent container
1622 if (!empty($websitepagefile)) {
1623 $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), basename($websitepagefile));
1624 if ($pageid > 0) {
1625 $pagelang = substr($tmppage->lang, 0, 2);
1626 $languagecodeselected = substr($pagelang, 0, 2);
1627 if (!in_array($pagelang, $languagecodes)) {
1628 $languagecodes[] = $pagelang; // We add language code of page into combo list
1629 }
1630 }
1631 }
1632
1633 $weblangs->load('languages');
1634 //var_dump($weblangs->defaultlang);
1635
1636 $url = $_SERVER["REQUEST_URI"];
1637 $url = preg_replace('/(\?|&)l=([a-zA-Z_]*)/', '', $url); // We remove param l from url
1638 //$url = preg_replace('/(\?|&)lang=([a-zA-Z_]*)/', '', $url); // We remove param lang from url
1639 $url .= (preg_match('/\?/', $url) ? '&' : '?').'l=';
1640 if (!preg_match('/^\//', $url)) {
1641 $url = '/'.$url;
1642 }
1643
1644 $HEIGHTOPTION = 40;
1645 $MAXHEIGHT = 4 * $HEIGHTOPTION;
1646 $nboflanguage = count($languagecodes);
1647
1648 $out = '<!-- componentSelectLang'.$htmlname.' -->'."\n";
1649
1650 $out .= '<style>';
1651 $out .= '.componentSelectLang'.$htmlname.':hover { height: '.min($MAXHEIGHT, ($HEIGHTOPTION * $nboflanguage)).'px; overflow-x: hidden; overflow-y: '.((($HEIGHTOPTION * $nboflanguage) > $MAXHEIGHT) ? ' scroll' : 'hidden').'; }'."\n";
1652 $out .= '.componentSelectLang'.$htmlname.' li { line-height: '.$HEIGHTOPTION.'px; }'."\n";
1653 $out .= '.componentSelectLang'.$htmlname.' {
1654 display: inline-block;
1655 padding: 0;
1656 height: '.$HEIGHTOPTION.'px;
1657 overflow: hidden;
1658 transition: all .3s ease;
1659 margin: 0 0 0 0;
1660 vertical-align: top;
1661 }
1662 .componentSelectLang'.$htmlname.':hover, .componentSelectLang'.$htmlname.':hover a { background-color: #fff; color: #000 !important; }
1663 ul.componentSelectLang'.$htmlname.' { width: 150px; }
1664 ul.componentSelectLang'.$htmlname.':hover .fa { visibility: hidden; }
1665 .componentSelectLang'.$htmlname.' a { text-decoration: none; width: 100%; }
1666 .componentSelectLang'.$htmlname.' li { display: block; padding: 0px 15px; margin-left: 0; margin-right: 0; }
1667 .componentSelectLang'.$htmlname.' li:hover { background-color: #EEE; }
1668 ';
1669 $out .= '</style>';
1670 $out .= '<ul class="componentSelectLang'.$htmlname.($morecss ? ' '.$morecss : '').'">';
1671
1672 if ($languagecodeselected) {
1673 // Convert $languagecodeselected into a long language code
1674 if (strlen($languagecodeselected) == 2) {
1675 $languagecodeselected = (empty($arrayofspecialmainlanguages[$languagecodeselected]) ? $languagecodeselected.'_'.strtoupper($languagecodeselected) : $arrayofspecialmainlanguages[$languagecodeselected]);
1676 }
1677
1678 $countrycode = strtolower(substr($languagecodeselected, -2));
1679 $label = $weblangs->trans("Language_".$languagecodeselected);
1680 if ($countrycode == 'us') {
1681 $label = preg_replace('/\s*\‍(.*\‍)/', '', $label);
1682 }
1683 $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>';
1684 $out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
1685 $out .= '</a></li>';
1686 }
1687 $i = 0;
1688 if (is_array($languagecodes)) {
1689 foreach ($languagecodes as $languagecode) {
1690 // Convert $languagecode into a long language code
1691 if (strlen($languagecode) == 2) {
1692 $languagecode = (empty($arrayofspecialmainlanguages[$languagecode]) ? $languagecode.'_'.strtoupper($languagecode) : $arrayofspecialmainlanguages[$languagecode]);
1693 }
1694
1695 if ($languagecode == $languagecodeselected) {
1696 continue; // Already output
1697 }
1698
1699 $countrycode = strtolower(substr($languagecode, -2));
1700 $label = $weblangs->trans("Language_".$languagecode);
1701 if ($countrycode == 'us') {
1702 $label = preg_replace('/\s*\‍(.*\‍)/', '', $label);
1703 }
1704 $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>';
1705 if (empty($i) && empty($languagecodeselected)) {
1706 $out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
1707 }
1708 $out .= '</a></li>';
1709 $i++;
1710 }
1711 }
1712 $out .= '</ul>';
1713
1714 return $out;
1715 }
1716
1724 public function overwriteTemplate(string $pathtotmpzip, $exportPath = '')
1725 {
1726 global $conf;
1727
1728 //$error = 0;
1729
1730 $website = $this;
1731 if (empty($website->id) || empty($website->ref)) {
1732 setEventMessages("Website id or ref is not defined", null, 'errors');
1733 return -1;
1734 }
1735 if (empty($website->name_template) && empty($exportPath)) {
1736 setEventMessages("To export the website template into a directory of the server, the name of the directory/template must be provided.", null, 'errors');
1737 return -1;
1738 }
1739 if (!is_writable($conf->website->dir_temp)) {
1740 setEventMessages("Temporary dir ".$conf->website->dir_temp." is not writable", null, 'errors');
1741 return -1;
1742 }
1743
1744 // Replace modified files into the doctemplates directory.
1745 if (getDolGlobalString('WEBSITE_ALLOW_OVERWRITE_GIT_SOURCE')) {
1746 // If the user has not specified a path
1747 if (empty($exportPath)) {
1748 $destdirrel = 'install/doctemplates/websites/'.$website->name_template;
1749 $destdir = DOL_DOCUMENT_ROOT.'/'.$destdirrel;
1750 } else {
1751 $exportPath = rtrim($exportPath, '/');
1752 if (strpos($exportPath, '..') !== false) {
1753 setEventMessages("Invalid path.", null, 'errors');
1754 return -1;
1755 }
1756 // if path start with / (absolute path)
1757 if (strpos($exportPath, '/') === 0 || preg_match('/^[a-zA-Z]:/', $exportPath)) {
1758 if (!is_dir($exportPath)) {
1759 setEventMessages("The specified absolute path does not exist.", null, 'errors');
1760 return -1;
1761 }
1762
1763 if (!is_writable($exportPath)) {
1764 setEventMessages("The specified absolute path is not writable.", null, 'errors');
1765 return -1;
1766 }
1767 $destdirrel = $exportPath;
1768 $destdir = $exportPath;
1769 } else {
1770 // relatif path
1771 $destdirrel = 'install/doctemplates/websites/'.$exportPath;
1772 $destdir = DOL_DOCUMENT_ROOT.'/'.$destdirrel;
1773 }
1774 }
1775 }
1776
1777 dol_mkdir($destdir);
1778
1779 if (!is_writable($destdir)) {
1780 setEventMessages("The specified path ".$destdir." is not writable.", null, 'errors');
1781 return -1;
1782 }
1783
1784 // Export on target sources
1785 $resultarray = dol_uncompress($pathtotmpzip, $destdir);
1786
1787 // Remove the file README and LICENSE from the $destdir/containers
1788 if (dol_is_file($destdir.'/containers/README.md')) {
1789 dol_move($destdir.'/containers/README.md', $destdir.'/README.md', '0', 1, 0, 0);
1790 }
1791 if (dol_is_file($destdir.'/containers/LICENSE')) {
1792 dol_move($destdir.'/containers/LICENSE', $destdir.'/LICENSE', '0', 1, 0, 0);
1793 }
1794 /*
1795 if (empty($exportPath)) {
1796 dol_delete_file($destdir.'/containers/README.md');
1797 dol_delete_file($destdir.'/containers/LICENSE');
1798 }
1799 */
1800
1801 // Remove non required files (will be re-generated during the import)
1802 dol_delete_file($destdir.'/containers/index.php');
1803 dol_delete_file($destdir.'/containers/master.inc.php');
1804
1805 // Now we remove the flag o+x on files
1806 // TODO
1807
1808 if (!empty($resultarray)) {
1809 setEventMessages("Error, failed to unzip the export into target dir ".$destdir.": ".implode(',', $resultarray), null, 'errors');
1810 } else {
1811 setEventMessages("Website content written into ".$destdirrel, null, 'mesgs');
1812 }
1813
1814 header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website->ref);
1815 exit();
1816 }
1817
1823 protected function extractNumberFromFilename($filename)
1824 {
1825 $matches = [];
1826 if (preg_match('/page(\d+)\.tpl\.php/', $filename, $matches)) {
1827 return (int) $matches[1];
1828 }
1829 return -1;
1830 }
1831
1837 public function setTemplateName($name_template)
1838 {
1839 $this->db->begin();
1840
1841 $sql = "UPDATE ".$this->db->prefix()."website SET";
1842 $sql .= " name_template = '".$this->db->escape($name_template)."'";
1843 $sql .= " WHERE rowid = ".(int) $this->id;
1844 $result = $this->db->query($sql);
1845
1846 if ($result) {
1847 $this->db->commit();
1848 return 1;
1849 } else {
1850 $this->db->rollback();
1851 return -1;
1852 }
1853 }
1854
1860 public function checkPreviousState($pathname)
1861 {
1862 if (!file_exists($pathname)) {
1863 if (touch($pathname)) {
1864 dolChmod($pathname, '0664');
1865 }
1866 return [];
1867 }
1868 return unserialize(file_get_contents($pathname));
1869 }
1870
1871
1878 public function saveState($etat, $pathname)
1879 {
1880 return file_put_contents($pathname, serialize($etat));
1881 }
1882
1890 public function compareFichierModifie($dossierSource, $dossierDestination, $fichierModifie)
1891 {
1892
1893 $fichiersSource = [];
1894 $fichiersDestination = [];
1895
1896 $fichierWithNoPage = [];
1897 $fichierWithNoPageInDest = [];
1898
1899 // Filter source files
1900 foreach (dol_dir_list($dossierSource, "files") as $file) {
1901 if (preg_match('/^page\d+/', $file['name']) && !str_contains($file['name'], '.old')) {
1902 $fichiersSource[] = $file;
1903 } else {
1904 $fichierWithNoPage[] = $file;
1905 }
1906 }
1907
1908 // Filter destination files
1909 foreach (dol_dir_list($dossierDestination, "all", 1) as $file) {
1910 if (preg_match('/^page\d+/', $file['name']) && !str_contains($file['name'], '.old')) {
1911 $fichiersDestination[] = $file;
1912 } else {
1913 $fichierWithNoPageInDest[] = $file;
1914 }
1915 }
1916
1917 // find index source and search it in folder destination
1918 $numOfPageSource = 0;
1919 foreach ($fichiersSource as $index => $file) {
1920 if ($file['name'] == basename($fichierModifie['fullname'])) {
1921 $numOfPageSource = $this->extractNumberFromFilename($file['name']);
1922 break;
1923 }
1924 }
1925
1926 //search numPage where was declared
1927 $filesFound = array();
1928 foreach ($fichierWithNoPage as $filesource) {
1929 $fileContent = file_get_contents($filesource['fullname']);
1930 if (strpos($fileContent, "require './page".$numOfPageSource.".tpl.php'") !== false) {
1931 $filesFound = $filesource;
1932 break;
1933 }
1934 }
1935 // find file with same name and extract num page in destination folder
1936 $numPagesFound = '';
1937 foreach ($fichierWithNoPageInDest as $filedest) {
1938 if ($filedest['name'] === $filesFound['name']) {
1939 $fileContent = file_get_contents($filedest['fullname']);
1940 if (preg_match("/page\d+\.tpl\.php/", $fileContent, $matches)) {
1941 $numPagesFound = $matches[0];
1942 break;
1943 }
1944 }
1945 }
1946 //search file with the number of pages found
1947 $fileNeeded = array();
1948 foreach ($fichiersDestination as $index => $file) {
1949 if ($file['name'] == $numPagesFound) {
1950 $fileNeeded = $file;
1951 break;
1952 }
1953 }
1954
1955 if (isset($fileNeeded)) {
1956 $sourceContent = file_get_contents($fichierModifie['fullname']);
1957 if (file_exists($fileNeeded['fullname'])) {
1958 $destContent = file_get_contents($fileNeeded['fullname']);
1959
1960 $numOfPageDest = $this->extractNumberFromFilename($fileNeeded['name']);
1961 $differences = $this->showDifferences($destContent, $sourceContent, array($numOfPageDest,$numOfPageSource));
1962 $differences['file_destination'] = $fileNeeded;
1963 } else {
1964 $differences = array();
1965 }
1966 return $differences;
1967 }
1968 return array();
1969 }
1970
1976 private function normalizeString($str)
1977 {
1978 $str = str_replace("\r\n", "\n", $str);
1979 $str = str_replace("\r", "\n", $str);
1980 return $str;
1981 }
1982
1990 protected function showDifferences($str1, $str2, $exceptNumPge = array())
1991 {
1992 $diff = array();
1993 $str1 = $this->normalizeString($str1);
1994 $str2 = $this->normalizeString($str2);
1995
1996 $lines1 = explode("\n", $str1);
1997 $lines2 = explode("\n", $str2);
1998
1999 $linesShouldChange = array();
2000 $linesShouldNotChange = array();
2001 $linefound = array();
2002 $countNumPage = count($exceptNumPge);
2003
2004 for ($i = 0;$i < $countNumPage; $i++) {
2005 $linefound[$i] = array();
2006 $linefound[$i]['meta'] = '/content="' . preg_quote((string) $exceptNumPge[$i], '/') . '" \/>/';
2007 $linefound[$i]['output'] = '/dolWebsiteOutput\‍(\$tmp, "html", ' . preg_quote((string) $exceptNumPge[$i], '/') . '\‍);/';
2008 }
2009
2010 if (isset($linefound[1])) {
2011 $maxLines = max(count($lines1), count($lines2));
2012 for ($lineNum = 0; $lineNum < $maxLines; $lineNum++) {
2013 $lineContent1 = $lines1[$lineNum] ?? '';
2014 $lineContent2 = $lines2[$lineNum] ?? '';
2015 if (preg_match($linefound[0]['output'], $lineContent1)) {
2016 $linesShouldChange[] = $lineContent1;
2017 }
2018 if (preg_match($linefound[0]['meta'], $lineContent1)) {
2019 $linesShouldChange[] = $lineContent1;
2020 }
2021 if (preg_match($linefound[1]['output'], $lineContent2)) {
2022 $linesShouldNotChange[] = $lineContent2;
2023 }
2024 if (preg_match($linefound[1]['meta'], $lineContent2)) {
2025 $linesShouldNotChange[] = $lineContent2;
2026 }
2027 if ($lineContent1 !== $lineContent2) {
2028 if (isset($lines1[$lineNum]) && !isset($lines2[$lineNum])) {
2029 // Ligne deleted de la source
2030 $diff["Supprimée à la ligne " . ($lineNum + 1)] = $lineContent1;
2031 } elseif (!isset($lines1[$lineNum]) && isset($lines2[$lineNum])) {
2032 // Nouvelle ligne added dans la destination
2033 $diff["Ajoutée à la ligne " . ($lineNum + 1)] = $lineContent2;
2034 } else {
2035 // Différence found it
2036 $diff["Modifiée à la ligne " . ($lineNum + 1)] = $lineContent2;
2037 }
2038 }
2039 }
2040 }
2041
2042
2043 if (empty($linesShouldChange)) {
2044 $linesShouldChange[0] = '<meta name="dolibarr:pageid" content="'.$exceptNumPge[0].'" />';
2045 $linesShouldChange[1] = '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "html", '.$exceptNumPge[0].');';
2046 }
2047
2048 $replacementMapping = array();
2049 if (!empty($linesShouldNotChange)) {
2050 $i = 0;
2051 foreach ($linesShouldNotChange as $numLigne => $ligneRemplacement) {
2052 if (isset($linesShouldChange[$numLigne])) {
2053 $replacementMapping[$ligneRemplacement] = $linesShouldChange[$numLigne];
2054 } else {
2055 $replacementMapping[$ligneRemplacement] = $linesShouldChange[$i];
2056 }
2057 $i++;
2058 }
2059 $diff['lignes_dont_change'] = $replacementMapping;
2060 }
2061 // search path of image and replace it with the correct path
2062 $pattern = '/medias\/image\/'.preg_quote($this->ref, '/').'\/([^\'"\s]+)/';
2063
2064 foreach ($diff as $key => $value) {
2065 // Ensure the value is a string
2066 if (is_string($value)) {
2067 if (preg_match($pattern, $value)) {
2068 $newValue = preg_replace($pattern, 'medias/image/'.$this->name_template.'/$1', $value);
2069 $diff[$key] = $newValue;
2070 }
2071 }
2072 }
2073 return $diff;
2074 }
2075
2083 protected function replaceLineUsingNum($inplaceFile, $differences)
2084 {
2085 if (file_exists($inplaceFile)) {
2086 dolChmod($inplaceFile, '0664');
2087 }
2088 if (!is_writable($inplaceFile)) {
2089 return -2;
2090 }
2091
2092 unset($differences['file_destination']);
2093 $contentDest = file($inplaceFile, FILE_IGNORE_NEW_LINES);
2094 foreach ($differences as $key => $ligneSource) {
2095 $matches = array();
2096 if (preg_match('/(Ajoutée|Modifiée) à la ligne (\d+)/', $key, $matches)) {
2097 $typeModification = $matches[1];
2098 $numLigne = (int) $matches[2] - 1;
2099
2100 if ($typeModification === 'Ajoutée') {
2101 array_splice($contentDest, $numLigne, 0, $ligneSource);
2102 } elseif ($typeModification === 'Modifiée') {
2103 $contentDest[$numLigne] = $ligneSource;
2104 }
2105 } elseif (preg_match('/Supprimée à la ligne (\d+)/', $key, $matches)) {
2106 $numLigne = (int) $matches[1] - 1;
2107 unset($contentDest[$numLigne]);
2108 }
2109 }
2110 // Reindex the table keys
2111 $contentDest = array_values($contentDest);
2112 $stringreplacement = implode("\n", $contentDest);
2113 file_put_contents($inplaceFile, $stringreplacement);
2114 foreach ($differences['lignes_dont_change'] as $linechanged => $line) {
2115 if (in_array($linechanged, $contentDest)) {
2116 dolReplaceInFile($inplaceFile, array($linechanged => $line));
2117 }
2118 }
2119
2120 return 0;
2121 }
2122}
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.
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)
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).