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