dolibarr  16.0.5
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 Frédéric France <frederic.france@netlogic.fr>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program. If not, see <https://www.gnu.org/licenses/>.
20  */
21 
28 // Put here all includes required by your class file
29 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
30 //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
31 //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
32 
36 class Website extends CommonObject
37 {
41  public $element = 'website';
42 
46  public $table_element = 'website';
47 
51  public $ismultientitymanaged = 1;
52 
56  public $picto = 'globe';
57 
61  public $entity;
62 
66  public $ref;
67 
71  public $description;
72 
76  public $lang;
77 
81  public $otherlang;
82 
86  public $status;
87 
91  public $date_creation;
92 
96  public $date_modification;
97 
101  public $fk_default_home;
102 
106  public $fk_user_creat;
107 
111  public $virtualhost;
112 
116  public $use_manifest;
117 
121  public $position;
122 
128  public $lines;
129 
130 
131  const STATUS_DRAFT = 0;
132  const STATUS_VALIDATED = 1;
133 
134 
140  public function __construct(DoliDB $db)
141  {
142  $this->db = $db;
143  return 1;
144  }
145 
154  public function create(User $user, $notrigger = false)
155  {
156  global $conf, $langs;
157 
158  dol_syslog(__METHOD__, LOG_DEBUG);
159 
160  $error = 0;
161  $now = dol_now();
162 
163  // Clean parameters
164  if (isset($this->entity)) {
165  $this->entity = (int) $this->entity;
166  }
167  if (isset($this->ref)) {
168  $this->ref = trim($this->ref);
169  }
170  if (isset($this->description)) {
171  $this->description = trim($this->description);
172  }
173  if (isset($this->status)) {
174  $this->status = (int) $this->status;
175  }
176  if (empty($this->date_creation)) {
177  $this->date_creation = $now;
178  }
179  if (empty($this->date_modification)) {
180  $this->date_modification = $now;
181  }
182  // Remove spaces and be sure we have main language only
183  $this->lang = preg_replace('/[_-].*$/', '', trim($this->lang)); // en_US or en-US -> en
184  $tmparray = explode(',', $this->otherlang);
185  if (is_array($tmparray)) {
186  foreach ($tmparray as $key => $val) {
187  // It possible we have empty val here if postparam WEBSITE_OTHERLANG is empty or set like this : 'en,,sv' or 'en,sv,'
188  if (empty(trim($val))) {
189  unset($tmparray[$key]);
190  continue;
191  }
192  $tmparray[$key] = preg_replace('/[_-].*$/', '', trim($val)); // en_US or en-US -> en
193  }
194  $this->otherlang = join(',', $tmparray);
195  }
196 
197  // Check parameters
198  if (empty($this->entity)) {
199  $this->entity = $conf->entity;
200  }
201  if (empty($this->lang)) {
202  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MainLanguage"));
203  return -1;
204  }
205 
206  // Insert request
207  $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.'(';
208  $sql .= 'entity,';
209  $sql .= 'ref,';
210  $sql .= 'description,';
211  $sql .= 'lang,';
212  $sql .= 'otherlang,';
213  $sql .= 'status,';
214  $sql .= 'fk_default_home,';
215  $sql .= 'virtualhost,';
216  $sql .= 'fk_user_creat,';
217  $sql .= 'date_creation,';
218  $sql .= 'position,';
219  $sql .= 'tms';
220  $sql .= ') VALUES (';
221  $sql .= ' '.((empty($this->entity) && $this->entity != '0') ? 'NULL' : $this->entity).',';
222  $sql .= ' '.(!isset($this->ref) ? 'NULL' : "'".$this->db->escape($this->ref)."'").',';
223  $sql .= ' '.(!isset($this->description) ? 'NULL' : "'".$this->db->escape($this->description)."'").',';
224  $sql .= ' '.(!isset($this->lang) ? 'NULL' : "'".$this->db->escape($this->lang)."'").',';
225  $sql .= ' '.(!isset($this->otherlang) ? 'NULL' : "'".$this->db->escape($this->otherlang)."'").',';
226  $sql .= ' '.(!isset($this->status) ? '1' : $this->status).',';
227  $sql .= ' '.(!isset($this->fk_default_home) ? 'NULL' : $this->fk_default_home).',';
228  $sql .= ' '.(!isset($this->virtualhost) ? 'NULL' : "'".$this->db->escape($this->virtualhost)."'").",";
229  $sql .= ' '.(!isset($this->fk_user_creat) ? $user->id : $this->fk_user_creat).',';
230  $sql .= ' '.(!isset($this->date_creation) || dol_strlen($this->date_creation) == 0 ? 'NULL' : "'".$this->db->idate($this->date_creation)."'").",";
231  $sql .= ' '.((int) $this->position).",";
232  $sql .= ' '.(!isset($this->date_modification) || dol_strlen($this->date_modification) == 0 ? 'NULL' : "'".$this->db->idate($this->date_modification)."'");
233  $sql .= ')';
234 
235  $this->db->begin();
236 
237  $resql = $this->db->query($sql);
238  if (!$resql) {
239  $error++;
240  $this->errors[] = 'Error '.$this->db->lasterror();
241  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
242  }
243 
244  if (!$error) {
245  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
246 
247  // Create subdirectory per language
248  $tmplangarray = explode(',', $this->otherlang);
249  if (is_array($tmplangarray)) {
250  dol_mkdir($conf->website->dir_output.'/'.$this->ref);
251  foreach ($tmplangarray as $val) {
252  if (trim($val) == $this->lang) {
253  continue;
254  }
255  dol_mkdir($conf->website->dir_output.'/'.$this->ref.'/'.trim($val));
256  }
257  }
258 
259  // Uncomment this and change WEBSITE to your own tag if you
260  // want this action to call a trigger.
261  // if (!$notrigger) {
262 
263  // // Call triggers
264  // $result = $this->call_trigger('WEBSITE_CREATE',$user);
265  // if ($result < 0) $error++;
266  // // End call triggers
267  // }
268  }
269 
270  if (!$error) {
271  $stringtodolibarrfile = "# Some properties for Dolibarr web site CMS\n";
272  $stringtodolibarrfile .= "param=value\n";
273  //print $conf->website->dir_output.'/'.$this->ref.'/.dolibarr';exit;
274  file_put_contents($conf->website->dir_output.'/'.$this->ref.'/.dolibarr', $stringtodolibarrfile);
275  }
276 
277  // Commit or rollback
278  if ($error) {
279  $this->db->rollback();
280 
281  return -1 * $error;
282  } else {
283  $this->db->commit();
284 
285  return $this->id;
286  }
287  }
288 
296  public function fetch($id, $ref = null)
297  {
298  dol_syslog(__METHOD__, LOG_DEBUG);
299 
300  $sql = "SELECT";
301  $sql .= " t.rowid,";
302  $sql .= " t.entity,";
303  $sql .= " t.ref,";
304  $sql .= " t.position,";
305  $sql .= " t.description,";
306  $sql .= " t.lang,";
307  $sql .= " t.otherlang,";
308  $sql .= " t.status,";
309  $sql .= " t.fk_default_home,";
310  $sql .= " t.use_manifest,";
311  $sql .= " t.virtualhost,";
312  $sql .= " t.fk_user_creat,";
313  $sql .= " t.fk_user_modif,";
314  $sql .= " t.date_creation,";
315  $sql .= " t.tms as date_modification";
316  $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
317  $sql .= " WHERE t.entity IN (".getEntity('website').")";
318  if (!empty($ref)) {
319  $sql .= " AND t.ref = '".$this->db->escape($ref)."'";
320  } else {
321  $sql .= " AND t.rowid = ".(int) $id;
322  }
323 
324  $resql = $this->db->query($sql);
325  if ($resql) {
326  $numrows = $this->db->num_rows($resql);
327  if ($numrows) {
328  $obj = $this->db->fetch_object($resql);
329 
330  $this->id = $obj->rowid;
331 
332  $this->entity = $obj->entity;
333  $this->ref = $obj->ref;
334  $this->position = $obj->position;
335  $this->description = $obj->description;
336  $this->lang = $obj->lang;
337  $this->otherlang = $obj->otherlang;
338  $this->status = $obj->status;
339  $this->fk_default_home = $obj->fk_default_home;
340  $this->virtualhost = $obj->virtualhost;
341  $this->use_manifest = $obj->use_manifest;
342  $this->fk_user_creat = $obj->fk_user_creat;
343  $this->fk_user_modif = $obj->fk_user_modif;
344  $this->date_creation = $this->db->jdate($obj->date_creation);
345  $this->date_modification = $this->db->jdate($obj->date_modification);
346  }
347  $this->db->free($resql);
348 
349  if ($numrows > 0) {
350  // Lines
351  $this->fetchLines();
352  }
353 
354  if ($numrows > 0) {
355  return 1;
356  } else {
357  return 0;
358  }
359  } else {
360  $this->errors[] = 'Error '.$this->db->lasterror();
361  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
362 
363  return -1;
364  }
365  }
366 
372  public function fetchLines()
373  {
374  $this->lines = array();
375 
376  // Load lines with object MyObjectLine
377 
378  return count($this->lines) ? 1 : 0;
379  }
380 
381 
394  public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
395  {
396  dol_syslog(__METHOD__, LOG_DEBUG);
397 
398  $sql = "SELECT";
399  $sql .= " t.rowid,";
400  $sql .= " t.entity,";
401  $sql .= " t.ref,";
402  $sql .= " t.description,";
403  $sql .= " t.lang,";
404  $sql .= " t.otherlang,";
405  $sql .= " t.status,";
406  $sql .= " t.fk_default_home,";
407  $sql .= " t.virtualhost,";
408  $sql .= " t.fk_user_creat,";
409  $sql .= " t.fk_user_modif,";
410  $sql .= " t.date_creation,";
411  $sql .= " t.tms as date_modification";
412  $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
413  $sql .= " WHERE t.entity IN (".getEntity('website').")";
414  // Manage filter
415  $sqlwhere = array();
416  if (count($filter) > 0) {
417  foreach ($filter as $key => $value) {
418  $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
419  }
420  }
421  if (count($sqlwhere) > 0) {
422  $sql .= ' AND '.implode(' '.$this->db->escape($filtermode).' ', $sqlwhere);
423  }
424 
425  if (!empty($sortfield)) {
426  $sql .= $this->db->order($sortfield, $sortorder);
427  }
428  if (!empty($limit)) {
429  $sql .= $this->db->plimit($limit, $offset);
430  }
431  $this->records = array();
432 
433  $resql = $this->db->query($sql);
434  if ($resql) {
435  $num = $this->db->num_rows($resql);
436 
437  while ($obj = $this->db->fetch_object($resql)) {
438  $line = new self($this->db);
439 
440  $line->id = $obj->rowid;
441 
442  $line->entity = $obj->entity;
443  $line->ref = $obj->ref;
444  $line->description = $obj->description;
445  $line->lang = $obj->lang;
446  $line->otherlang = $obj->otherlang;
447  $line->status = $obj->status;
448  $line->fk_default_home = $obj->fk_default_home;
449  $line->virtualhost = $obj->virtualhost;
450  $this->fk_user_creat = $obj->fk_user_creat;
451  $this->fk_user_modif = $obj->fk_user_modif;
452  $line->date_creation = $this->db->jdate($obj->date_creation);
453  $line->date_modification = $this->db->jdate($obj->date_modification);
454 
455  $this->records[$line->id] = $line;
456  }
457  $this->db->free($resql);
458 
459  return $num;
460  } else {
461  $this->errors[] = 'Error '.$this->db->lasterror();
462  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
463 
464  return -1;
465  }
466  }
467 
476  public function update(User $user, $notrigger = false)
477  {
478  global $conf, $langs;
479 
480  $error = 0;
481 
482  dol_syslog(__METHOD__, LOG_DEBUG);
483 
484  // Clean parameters
485 
486  if (isset($this->entity)) {
487  $this->entity = (int) $this->entity;
488  }
489  if (isset($this->ref)) {
490  $this->ref = trim($this->ref);
491  }
492  if (isset($this->description)) {
493  $this->description = trim($this->description);
494  }
495  if (isset($this->status)) {
496  $this->status = (int) $this->status;
497  }
498 
499  // Remove spaces and be sure we have main language only
500  $this->lang = preg_replace('/[_-].*$/', '', trim($this->lang)); // en_US or en-US -> en
501  $tmparray = explode(',', $this->otherlang);
502  if (is_array($tmparray)) {
503  foreach ($tmparray as $key => $val) {
504  // It possible we have empty val here if postparam WEBSITE_OTHERLANG is empty or set like this : 'en,,sv' or 'en,sv,'
505  if (empty(trim($val))) {
506  unset($tmparray[$key]);
507  continue;
508  }
509  $tmparray[$key] = preg_replace('/[_-].*$/', '', trim($val)); // en_US or en-US -> en
510  }
511  $this->otherlang = join(',', $tmparray);
512  }
513  if (empty($this->lang)) {
514  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MainLanguage"));
515  return -1;
516  }
517 
518  // Check parameters
519  // Put here code to add a control on parameters values
520 
521  // Update request
522  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
523  $sql .= ' entity = '.(isset($this->entity) ? $this->entity : "null").',';
524  $sql .= ' ref = '.(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").',';
525  $sql .= ' description = '.(isset($this->description) ? "'".$this->db->escape($this->description)."'" : "null").',';
526  $sql .= ' lang = '.(isset($this->lang) ? "'".$this->db->escape($this->lang)."'" : "null").',';
527  $sql .= ' otherlang = '.(isset($this->otherlang) ? "'".$this->db->escape($this->otherlang)."'" : "null").',';
528  $sql .= ' status = '.(isset($this->status) ? $this->status : "null").',';
529  $sql .= ' fk_default_home = '.(($this->fk_default_home > 0) ? $this->fk_default_home : "null").',';
530  $sql .= ' use_manifest = '.((int) $this->use_manifest).',';
531  $sql .= ' virtualhost = '.(($this->virtualhost != '') ? "'".$this->db->escape($this->virtualhost)."'" : "null").',';
532  $sql .= ' fk_user_modif = '.(!isset($this->fk_user_modif) ? $user->id : $this->fk_user_modif).',';
533  $sql .= ' date_creation = '.(!isset($this->date_creation) || dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').',';
534  $sql .= ' tms = '.(dol_strlen($this->date_modification) != 0 ? "'".$this->db->idate($this->date_modification)."'" : "'".$this->db->idate(dol_now())."'");
535  $sql .= ' WHERE rowid='.((int) $this->id);
536 
537  $this->db->begin();
538 
539  $resql = $this->db->query($sql);
540  if (!$resql) {
541  $error++;
542  $this->errors[] = 'Error '.$this->db->lasterror();
543  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
544  }
545 
546  if (!$error && !$notrigger) {
547  // Uncomment this and change MYOBJECT to your own tag if you
548  // want this action calls a trigger.
549 
550  // Create subdirectory per language
551  $tmplangarray = explode(',', $this->otherlang);
552  if (is_array($tmplangarray)) {
553  dol_mkdir($conf->website->dir_output.'/'.$this->ref);
554  foreach ($tmplangarray as $val) {
555  if (trim($val) == $this->lang) {
556  continue;
557  }
558  dol_mkdir($conf->website->dir_output.'/'.$this->ref.'/'.trim($val));
559  }
560  }
561 
563  //$result=$this->call_trigger('WEBSITE_MODIFY',$user);
564  //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
566  }
567 
568  // Commit or rollback
569  if ($error) {
570  $this->db->rollback();
571 
572  return -1 * $error;
573  } else {
574  $this->db->commit();
575 
576  return 1;
577  }
578  }
579 
588  public function delete(User $user, $notrigger = false)
589  {
590  global $conf;
591 
592  dol_syslog(__METHOD__, LOG_DEBUG);
593 
594  $error = 0;
595 
596  $this->db->begin();
597 
598  if (!$error) {
599  if (!$notrigger) {
600  // Uncomment this and change WEBSITE to your own tag if you
601  // want this action calls a trigger.
602 
604  //$result=$this->call_trigger('WEBSITE_DELETE',$user);
605  //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
607  }
608  }
609 
610  if (!$error) {
611  $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element;
612  $sql .= ' WHERE rowid='.((int) $this->id);
613 
614  $resql = $this->db->query($sql);
615  if (!$resql) {
616  $error++;
617  $this->errors[] = 'Error '.$this->db->lasterror();
618  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
619  }
620  }
621 
622  if (!$error && !empty($this->ref)) {
623  $pathofwebsite = DOL_DATA_ROOT.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.$this->ref;
624 
625  dol_delete_dir_recursive($pathofwebsite);
626  }
627 
628  // Commit or rollback
629  if ($error) {
630  $this->db->rollback();
631 
632  return -1 * $error;
633  } else {
634  $this->db->commit();
635 
636  return 1;
637  }
638  }
639 
650  public function createFromClone($user, $fromid, $newref, $newlang = '')
651  {
652  global $conf, $langs;
653  global $dolibarr_main_data_root;
654 
655  $now = dol_now();
656  $error = 0;
657 
658  dol_syslog(__METHOD__, LOG_DEBUG);
659 
660  $newref = dol_sanitizeFileName($newref);
661 
662  if (empty($newref)) {
663  $this->error = 'ErrorBadParameter';
664  return -1;
665  }
666 
667  $object = new self($this->db);
668 
669  // Check no site with ref exists
670  if ($object->fetch(0, $newref) > 0) {
671  $this->error = 'ErrorNewRefIsAlreadyUsed';
672  return -1;
673  }
674 
675  $this->db->begin();
676 
677  // Load source object
678  $object->fetch($fromid);
679 
680  $oldidforhome = $object->fk_default_home;
681  $oldref = $object->ref;
682 
683  $pathofwebsiteold = $dolibarr_main_data_root.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.dol_sanitizeFileName($oldref);
684  $pathofwebsitenew = $dolibarr_main_data_root.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.dol_sanitizeFileName($newref);
685  dol_delete_dir_recursive($pathofwebsitenew);
686 
687  $fileindex = $pathofwebsitenew.'/index.php';
688 
689  // Reset some properties
690  unset($object->id);
691  unset($object->fk_user_creat);
692  unset($object->import_key);
693 
694  // Clear fields
695  $object->ref = $newref;
696  $object->fk_default_home = 0;
697  $object->virtualhost = '';
698  $object->date_creation = $now;
699  $object->fk_user_creat = $user->id;
700  $object->position = ((int) $object->position) + 1;
701  $object->status = self::STATUS_DRAFT;
702  if (empty($object->lang)) {
703  $object->lang = substr($langs->defaultlang, 0, 2); // Should not happen. Protection for corrupted site with no languages
704  }
705 
706  // Create clone
707  $object->context['createfromclone'] = 'createfromclone';
708  $result = $object->create($user);
709  if ($result < 0) {
710  $error++;
711  $this->error = $object->error;
712  $this->errors = $object->errors;
713  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
714  }
715 
716  if (!$error) {
717  dolCopyDir($pathofwebsiteold, $pathofwebsitenew, $conf->global->MAIN_UMASK, 0, null, 2);
718 
719  // Check symlink to medias and restore it if ko
720  $pathtomedias = DOL_DATA_ROOT.'/medias'; // Target
721  $pathtomediasinwebsite = $pathofwebsitenew.'/medias'; // Source / Link name
722  if (!is_link(dol_osencode($pathtomediasinwebsite))) {
723  dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite);
724  dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists
725  $result = symlink($pathtomedias, $pathtomediasinwebsite);
726  }
727 
728  // Copy images and js dir
729  $pathofmediasjsold = DOL_DATA_ROOT.'/medias/js/'.$oldref;
730  $pathofmediasjsnew = DOL_DATA_ROOT.'/medias/js/'.$newref;
731  dolCopyDir($pathofmediasjsold, $pathofmediasjsnew, $conf->global->MAIN_UMASK, 0);
732 
733  $pathofmediasimageold = DOL_DATA_ROOT.'/medias/image/'.$oldref;
734  $pathofmediasimagenew = DOL_DATA_ROOT.'/medias/image/'.$newref;
735  dolCopyDir($pathofmediasimageold, $pathofmediasimagenew, $conf->global->MAIN_UMASK, 0);
736 
737  $newidforhome = 0;
738 
739  // Duplicate pages
740  $objectpages = new WebsitePage($this->db);
741  $listofpages = $objectpages->fetchAll($fromid);
742  foreach ($listofpages as $pageid => $objectpageold) {
743  // Delete old file
744  $filetplold = $pathofwebsitenew.'/page'.$pageid.'.tpl.php';
745  dol_delete_file($filetplold);
746 
747  // Create new file
748  $objectpagenew = $objectpageold->createFromClone($user, $pageid, $objectpageold->pageurl, '', 0, $object->id, 1);
749 
750  //print $pageid.' = '.$objectpageold->pageurl.' -> '.$objectpagenew->id.' = '.$objectpagenew->pageurl.'<br>';
751  if (is_object($objectpagenew) && $objectpagenew->pageurl) {
752  $filealias = $pathofwebsitenew.'/'.$objectpagenew->pageurl.'.php';
753  $filetplnew = $pathofwebsitenew.'/page'.$objectpagenew->id.'.tpl.php';
754 
755  // Save page alias
756  $result = dolSavePageAlias($filealias, $object, $objectpagenew);
757  if (!$result) {
758  setEventMessages('Failed to write file '.$filealias, null, 'errors');
759  }
760 
761  $result = dolSavePageContent($filetplnew, $object, $objectpagenew);
762  if (!$result) {
763  setEventMessages('Failed to write file '.$filetplnew, null, 'errors');
764  }
765 
766  if ($pageid == $oldidforhome) {
767  $newidforhome = $objectpagenew->id;
768  }
769  } else {
770  setEventMessages($objectpageold->error, $objectpageold->errors, 'errors');
771  $error++;
772  }
773  }
774  }
775 
776  if (!$error) {
777  // Restore id of home page
778  $object->fk_default_home = $newidforhome;
779  $res = $object->update($user);
780  if (!($res > 0)) {
781  $error++;
782  setEventMessages($object->error, $object->errors, 'errors');
783  }
784 
785  if (!$error) {
786  $filetpl = $pathofwebsitenew.'/page'.$newidforhome.'.tpl.php';
787  $filewrapper = $pathofwebsitenew.'/wrapper.php';
788 
789  // Re-generates the index.php page to be the home page, and re-generates the wrapper.php
790  //--------------------------------------------------------------------------------------
791  $result = dolSaveIndexPage($pathofwebsitenew, $fileindex, $filetpl, $filewrapper, $object);
792  }
793  }
794 
795  unset($object->context['createfromclone']);
796 
797  // End
798  if (!$error) {
799  $this->db->commit();
800 
801  return $object;
802  } else {
803  $this->db->rollback();
804 
805  return -1;
806  }
807  }
808 
820  public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $maxlen = 24, $morecss = '')
821  {
822  global $langs, $conf, $db;
823  global $dolibarr_main_authentication, $dolibarr_main_demo;
824  global $menumanager;
825 
826 
827  $result = '';
828  $companylink = '';
829 
830  $label = '<u>'.$langs->trans("WebSite").'</u>';
831  $label .= '<br>';
832  $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref.'<br>';
833  $label .= '<b>'.$langs->trans('MainLanguage').':</b> '.$this->lang;
834 
835  $linkstart = '<a href="'.DOL_URL_ROOT.'/website/card.php?id='.$this->id.'"';
836  $linkstart .= ($notooltip ? '' : ' title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip'.($morecss ? ' '.$morecss : '').'"');
837  $linkstart .= '>';
838  $linkend = '</a>';
839 
840  $linkstart = $linkend = '';
841 
842  if ($withpicto) {
843  $result .= ($linkstart.img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? '' : 'class="classfortooltip"')).$linkend);
844  if ($withpicto != 2) {
845  $result .= ' ';
846  }
847  }
848  $result .= $linkstart.$this->ref.$linkend;
849  return $result;
850  }
851 
858  public function getLibStatut($mode = 0)
859  {
860  return $this->LibStatut($this->status, $mode);
861  }
862 
863  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
871  public function LibStatut($status, $mode = 0)
872  {
873  // phpcs:enable
874  global $langs;
875 
876  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
877  global $langs;
878  //$langs->load("mymodule");
879  $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Disabled');
880  $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
881  $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Disabled');
882  $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
883  }
884 
885  $statusType = 'status5';
886  if ($status == self::STATUS_VALIDATED) {
887  $statusType = 'status4';
888  }
889 
890  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
891  }
892 
893 
900  public function initAsSpecimen()
901  {
902  global $user;
903 
904  $this->id = 0;
905  $this->specimen = 1;
906  $this->entity = 1;
907  $this->ref = 'myspecimenwebsite';
908  $this->description = 'A specimen website';
909  $this->lang = 'en';
910  $this->otherlang = 'fr,es';
911  $this->status = 1;
912  $this->fk_default_home = null;
913  $this->virtualhost = 'http://myvirtualhost';
914  $this->fk_user_creat = $user->id;
915  $this->fk_user_modif = $user->id;
916  $this->date_creation = dol_now();
917  $this->tms = dol_now();
918  }
919 
920 
926  public function exportWebSite()
927  {
928  global $conf, $mysoc;
929 
930  $website = $this;
931 
932  if (empty($website->id) || empty($website->ref)) {
933  setEventMessages("Website id or ref is not defined", null, 'errors');
934  return '';
935  }
936 
937  dol_syslog("Create temp dir ".$conf->website->dir_temp);
938  dol_mkdir($conf->website->dir_temp);
939  if (!is_writable($conf->website->dir_temp)) {
940  setEventMessages("Temporary dir ".$conf->website->dir_temp." is not writable", null, 'errors');
941  return '';
942  }
943 
944  $destdir = $conf->website->dir_temp.'/'.$website->ref;
945 
946  dol_syslog("Clear temp dir ".$destdir);
947  $count = 0; $countreallydeleted = 0;
948  $counttodelete = dol_delete_dir_recursive($destdir, $count, 1, 0, $countreallydeleted);
949  if ($counttodelete != $countreallydeleted) {
950  setEventMessages("Failed to clean temp directory ".$destdir, null, 'errors');
951  return '';
952  }
953 
954  $arrayreplacementinfilename = array();
955  $arrayreplacementincss = array();
956  $arrayreplacementincss['file=image/'.$website->ref.'/'] = "file=image/__WEBSITE_KEY__/";
957  $arrayreplacementincss['file=js/'.$website->ref.'/'] = "file=js/__WEBSITE_KEY__/";
958  $arrayreplacementincss['medias/image/'.$website->ref.'/'] = "medias/image/__WEBSITE_KEY__/";
959  $arrayreplacementincss['medias/js/'.$website->ref.'/'] = "medias/js/__WEBSITE_KEY__/";
960  if ($mysoc->logo_small) {
961  $arrayreplacementincss['file=logos%2Fthumbs%2F'.$mysoc->logo_small] = "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__";
962  }
963  if ($mysoc->logo_mini) {
964  $arrayreplacementincss['file=logos%2Fthumbs%2F'.$mysoc->logo_mini] = "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__";
965  }
966  if ($mysoc->logo) {
967  $arrayreplacementincss['file=logos%2Fthumbs%2F'.$mysoc->logo] = "file=logos%2Fthumbs%2F__LOGO_KEY__";
968  }
969 
970  // Create output directories
971  dol_syslog("Create containers dir");
972  dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/containers');
973  dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/medias/image/websitekey');
974  dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/medias/js/websitekey');
975 
976  // Copy files into 'containers'
977  $srcdir = $conf->website->dir_output.'/'.$website->ref;
978  $destdir = $conf->website->dir_temp.'/'.$website->ref.'/containers';
979 
980  dol_syslog("Copy content from ".$srcdir." into ".$destdir);
981  dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacementinfilename, 2);
982 
983  // Copy files into medias/image
984  $srcdir = DOL_DATA_ROOT.'/medias/image/'.$website->ref;
985  $destdir = $conf->website->dir_temp.'/'.$website->ref.'/medias/image/websitekey';
986 
987  dol_syslog("Copy content from ".$srcdir." into ".$destdir);
988  dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacementinfilename);
989 
990  // Copy files into medias/js
991  $srcdir = DOL_DATA_ROOT.'/medias/js/'.$website->ref;
992  $destdir = $conf->website->dir_temp.'/'.$website->ref.'/medias/js/websitekey';
993 
994  dol_syslog("Copy content from ".$srcdir." into ".$destdir);
995  dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacementinfilename);
996 
997  // Make some replacement into some files
998  $cssindestdir = $conf->website->dir_temp.'/'.$website->ref.'/containers/styles.css.php';
999  dolReplaceInFile($cssindestdir, $arrayreplacementincss);
1000 
1001  $htmldeaderindestdir = $conf->website->dir_temp.'/'.$website->ref.'/containers/htmlheader.html';
1002  dolReplaceInFile($htmldeaderindestdir, $arrayreplacementincss);
1003 
1004  // Build sql file
1005  $filesql = $conf->website->dir_temp.'/'.$website->ref.'/website_pages.sql';
1006  $fp = fopen($filesql, "w");
1007  if (empty($fp)) {
1008  setEventMessages("Failed to create file ".$filesql, null, 'errors');
1009  return '';
1010  }
1011 
1012  $objectpages = new WebsitePage($this->db);
1013  $listofpages = $objectpages->fetchAll($website->id);
1014 
1015  // Assign ->newid and ->newfk_page
1016  $i = 1;
1017  foreach ($listofpages as $pageid => $objectpageold) {
1018  $objectpageold->newid = $i;
1019  $i++;
1020  }
1021  $i = 1;
1022  foreach ($listofpages as $pageid => $objectpageold) {
1023  // Search newid
1024  $newfk_page = 0;
1025  foreach ($listofpages as $pageid2 => $objectpageold2) {
1026  if ($pageid2 == $objectpageold->fk_page) {
1027  $newfk_page = $objectpageold2->newid;
1028  break;
1029  }
1030  }
1031  $objectpageold->newfk_page = $newfk_page;
1032  $i++;
1033  }
1034  foreach ($listofpages as $pageid => $objectpageold) {
1035  $allaliases = $objectpageold->pageurl;
1036  $allaliases .= ($objectpageold->aliasalt ? ','.$objectpageold->aliasalt : '');
1037 
1038  $line = '-- Page ID '.$objectpageold->id.' -> '.$objectpageold->newid.'__+MAX_llx_website_page__ - Aliases '.$allaliases.' --;'; // newid start at 1, 2...
1039  $line .= "\n";
1040  fputs($fp, $line);
1041 
1042  // Warning: We must keep llx_ here. It is a generic SQL.
1043  $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)';
1044 
1045  $line .= " VALUES(";
1046  $line .= $objectpageold->newid."__+MAX_llx_website_page__, ";
1047  $line .= ($objectpageold->newfk_page ? $this->db->escape($objectpageold->newfk_page)."__+MAX_llx_website_page__" : "null").", ";
1048  $line .= "__WEBSITE_ID__, ";
1049  $line .= "'".$this->db->escape($objectpageold->pageurl)."', ";
1050  $line .= "'".$this->db->escape($objectpageold->aliasalt)."', ";
1051  $line .= "'".$this->db->escape($objectpageold->title)."', ";
1052  $line .= "'".$this->db->escape($objectpageold->description)."', ";
1053  $line .= "'".$this->db->escape($objectpageold->lang)."', ";
1054  $line .= "'".$this->db->escape($objectpageold->image)."', ";
1055  $line .= "'".$this->db->escape($objectpageold->keywords)."', ";
1056  $line .= "'".$this->db->escape($objectpageold->status)."', ";
1057  $line .= "'".$this->db->idate($objectpageold->date_creation)."', ";
1058  $line .= "'".$this->db->idate($objectpageold->date_modification)."', ";
1059  $line .= ($objectpageold->import_key ? "'".$this->db->escape($objectpageold->import_key)."'" : "null").", ";
1060  $line .= "'".$this->db->escape($objectpageold->grabbed_from)."', ";
1061  $line .= "'".$this->db->escape($objectpageold->type_container)."', ";
1062 
1063  $stringtoexport = $objectpageold->htmlheader;
1064  $stringtoexport = str_replace(array("\r\n", "\r", "\n"), "__N__", $stringtoexport);
1065  $stringtoexport = str_replace('file=image/'.$website->ref.'/', "file=image/__WEBSITE_KEY__/", $stringtoexport);
1066  $stringtoexport = str_replace('file=js/'.$website->ref.'/', "file=js/__WEBSITE_KEY__/", $stringtoexport);
1067  $stringtoexport = str_replace('medias/image/'.$website->ref.'/', "medias/image/__WEBSITE_KEY__/", $stringtoexport);
1068  $stringtoexport = str_replace('medias/js/'.$website->ref.'/', "medias/js/__WEBSITE_KEY__/", $stringtoexport);
1069  $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_small, "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__", $stringtoexport);
1070  $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_mini, "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__", $stringtoexport);
1071  $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo, "file=logos%2Fthumbs%2F__LOGO_KEY__", $stringtoexport);
1072  $line .= "'".$this->db->escape(str_replace(array("\r\n", "\r", "\n"), "__N__", $stringtoexport))."', "; // Replace \r \n to have record on 1 line
1073 
1074  $stringtoexport = $objectpageold->content;
1075  $stringtoexport = str_replace(array("\r\n", "\r", "\n"), "__N__", $stringtoexport);
1076  $stringtoexport = str_replace('file=image/'.$website->ref.'/', "file=image/__WEBSITE_KEY__/", $stringtoexport);
1077  $stringtoexport = str_replace('file=js/'.$website->ref.'/', "file=js/__WEBSITE_KEY__/", $stringtoexport);
1078  $stringtoexport = str_replace('medias/image/'.$website->ref.'/', "medias/image/__WEBSITE_KEY__/", $stringtoexport);
1079  $stringtoexport = str_replace('medias/js/'.$website->ref.'/', "medias/js/__WEBSITE_KEY__/", $stringtoexport);
1080  $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_small, "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__", $stringtoexport);
1081  $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_mini, "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__", $stringtoexport);
1082  $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo, "file=logos%2Fthumbs%2F__LOGO_KEY__", $stringtoexport);
1083 
1084  // When we have a link src="image/websiteref/file.png" into html content
1085  $stringtoexport = str_replace('="image/'.$website->ref.'/', '="image/__WEBSITE_KEY__/', $stringtoexport);
1086 
1087  $line .= "'".$this->db->escape($stringtoexport)."', "; // Replace \r \n to have record on 1 line
1088  $line .= "'".$this->db->escape($objectpageold->author_alias)."', ";
1089  $line .= (int) $objectpageold->allowed_in_frames;
1090  $line .= ");";
1091  $line .= "\n";
1092 
1093  fputs($fp, $line);
1094 
1095  // Add line to update home page id during import
1096  //var_dump($this->fk_default_home.' - '.$objectpageold->id.' - '.$objectpageold->newid);exit;
1097  if ($this->fk_default_home > 0 && ($objectpageold->id == $this->fk_default_home) && ($objectpageold->newid > 0)) { // This is the record with home page
1098  // Warning: We must keep llx_ here. It is a generic SQL.
1099  $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__;";
1100  $line .= "\n";
1101  fputs($fp, $line);
1102  }
1103  }
1104 
1105  $line = "\n-- For Dolibarr v14+ --;\n";
1106  $line .= "UPDATE llx_website SET lang = '".$this->db->escape($this->lang)."' WHERE rowid = __WEBSITE_ID__;\n";
1107  $line .= "UPDATE llx_website SET otherlang = '".$this->db->escape($this->otherlang)."' WHERE rowid = __WEBSITE_ID__;\n";
1108  $line .= "\n";
1109  fputs($fp, $line);
1110 
1111  fclose($fp);
1112  if (!empty($conf->global->MAIN_UMASK)) {
1113  @chmod($filesql, octdec($conf->global->MAIN_UMASK));
1114  }
1115 
1116  // Build zip file
1117  $filedir = $conf->website->dir_temp.'/'.$website->ref.'/.';
1118  $fileglob = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-*.zip';
1119  $filename = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-'.dol_print_date(dol_now(), 'dayhourlog').'-V'.((float) DOL_VERSION).'.zip';
1120 
1121  dol_delete_file($fileglob, 0);
1122  $result = dol_compress_file($filedir, $filename, 'zip');
1123 
1124  if ($result > 0) {
1125  return $filename;
1126  } else {
1127  global $errormsg;
1128  $this->error = $errormsg;
1129  return '';
1130  }
1131  }
1132 
1133 
1140  public function importWebSite($pathtofile)
1141  {
1142  global $conf, $mysoc;
1143 
1144  $error = 0;
1145 
1146  $object = $this;
1147  if (empty($object->ref)) {
1148  $this->error = 'Function importWebSite called on object not loaded (object->ref is empty)';
1149  return -2;
1150  }
1151 
1152  dol_delete_dir_recursive($conf->website->dir_temp."/".$object->ref);
1153  dol_mkdir($conf->website->dir_temp.'/'.$object->ref);
1154 
1155  $filename = basename($pathtofile);
1156  if (!preg_match('/^website_(.*)-(.*)$/', $filename, $reg)) {
1157  $this->errors[] = 'Bad format for filename '.$filename.'. Must be website_XXX-VERSION.';
1158  return -3;
1159  }
1160 
1161  $result = dol_uncompress($pathtofile, $conf->website->dir_temp.'/'.$object->ref);
1162 
1163  if (!empty($result['error'])) {
1164  $this->errors[] = 'Failed to unzip file '.$pathtofile.'.';
1165  return -4;
1166  }
1167 
1168  $arrayreplacement = array();
1169  $arrayreplacement['__WEBSITE_ID__'] = $object->id;
1170  $arrayreplacement['__WEBSITE_KEY__'] = $object->ref;
1171  $arrayreplacement['__N__'] = $this->db->escape("\n"); // Restore \n
1172  $arrayreplacement['__LOGO_SMALL_KEY__'] = $this->db->escape($mysoc->logo_small);
1173  $arrayreplacement['__LOGO_MINI_KEY__'] = $this->db->escape($mysoc->logo_mini);
1174  $arrayreplacement['__LOGO_KEY__'] = $this->db->escape($mysoc->logo);
1175 
1176  // Copy containers
1177  dolCopyDir($conf->website->dir_temp.'/'.$object->ref.'/containers', $conf->website->dir_output.'/'.$object->ref, 0, 1); // Overwrite if exists
1178 
1179  // Make replacement into css and htmlheader file
1180  $cssindestdir = $conf->website->dir_output.'/'.$object->ref.'/styles.css.php';
1181  $result = dolReplaceInFile($cssindestdir, $arrayreplacement);
1182 
1183  $htmldeaderindestdir = $conf->website->dir_output.'/'.$object->ref.'/htmlheader.html';
1184  $result = dolReplaceInFile($htmldeaderindestdir, $arrayreplacement);
1185 
1186  // Now generate the master.inc.php page
1187  $filemaster = $conf->website->dir_output.'/'.$object->ref.'/master.inc.php';
1188  $result = dolSaveMasterFile($filemaster);
1189  if (!$result) {
1190  $this->errors[] = 'Failed to write file '.$filemaster;
1191  $error++;
1192  }
1193 
1194  dolCopyDir($conf->website->dir_temp.'/'.$object->ref.'/medias/image/websitekey', $conf->website->dir_output.'/'.$object->ref.'/medias/image/'.$object->ref, 0, 1); // Medias can be shared, do not overwrite if exists
1195  dolCopyDir($conf->website->dir_temp.'/'.$object->ref.'/medias/js/websitekey', $conf->website->dir_output.'/'.$object->ref.'/medias/js/'.$object->ref, 0, 1); // Medias can be shared, do not overwrite if exists
1196 
1197  $sqlfile = $conf->website->dir_temp."/".$object->ref.'/website_pages.sql';
1198 
1199  $result = dolReplaceInFile($sqlfile, $arrayreplacement);
1200 
1201  $this->db->begin();
1202 
1203  // Search the $maxrowid because we need it later
1204  $sqlgetrowid = 'SELECT MAX(rowid) as max from '.MAIN_DB_PREFIX.'website_page';
1205  $resql = $this->db->query($sqlgetrowid);
1206  if ($resql) {
1207  $obj = $this->db->fetch_object($resql);
1208  $maxrowid = $obj->max;
1209  }
1210 
1211  // Load sql record
1212  $runsql = run_sql($sqlfile, 1, '', 0, '', 'none', 0, 1, 0, 0, 1); // The maxrowid of table is searched into this function two
1213  if ($runsql <= 0) {
1214  $this->errors[] = 'Failed to load sql file '.$sqlfile.' (ret='.((int) $runsql).')';
1215  $error++;
1216  }
1217 
1218  $objectpagestatic = new WebsitePage($this->db);
1219 
1220  // Make replacement of IDs
1221  $fp = fopen($sqlfile, "r");
1222  if ($fp) {
1223  while (!feof($fp)) {
1224  $reg = array();
1225 
1226  // Warning fgets with second parameter that is null or 0 hang.
1227  $buf = fgets($fp, 65000);
1228  if (preg_match('/^-- Page ID (\d+)\s[^\s]+\s(\d+).*Aliases\s(.*)\s--;/i', $buf, $reg)) {
1229  $oldid = $reg[1];
1230  $newid = ($reg[2] + $maxrowid);
1231  $aliasesarray = explode(',', $reg[3]);
1232 
1233  dol_syslog("Found ID ".$oldid." to replace with ID ".$newid." and shortcut aliases to create: ".$reg[3]);
1234 
1235  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);
1236 
1237  $objectpagestatic->fetch($newid);
1238 
1239  // The move is not enough, so we regenerate page
1240  $filetpl = $conf->website->dir_output.'/'.$object->ref.'/page'.$newid.'.tpl.php';
1241  $result = dolSavePageContent($filetpl, $object, $objectpagestatic);
1242  if (!$result) {
1243  $this->errors[] = 'Failed to write file '.basename($filetpl);
1244  $error++;
1245  }
1246 
1247  // Regenerate alternative aliases pages
1248  if (is_array($aliasesarray)) {
1249  foreach ($aliasesarray as $aliasshortcuttocreate) {
1250  if (trim($aliasshortcuttocreate)) {
1251  $filealias = $conf->website->dir_output.'/'.$object->ref.'/'.trim($aliasshortcuttocreate).'.php';
1252  $result = dolSavePageAlias($filealias, $object, $objectpagestatic);
1253  if (!$result) {
1254  $this->errors[] = 'Failed to write file '.basename($filealias);
1255  $error++;
1256  }
1257  }
1258  }
1259  }
1260  }
1261  }
1262  }
1263 
1264  // Read record of website that has been updated by the run_sql function previously called so we can get the
1265  // value of fk_default_home that is ID of home page
1266  $sql = "SELECT fk_default_home FROM ".MAIN_DB_PREFIX."website WHERE rowid = ".((int) $object->id);
1267  $resql = $this->db->query($sql);
1268  if ($resql) {
1269  $obj = $this->db->fetch_object($resql);
1270  if ($obj) {
1271  $object->fk_default_home = $obj->fk_default_home;
1272  } else {
1273  //$this->errors[] = 'Failed to get the Home page';
1274  //$error++;
1275  }
1276  }
1277 
1278  // Regenerate index page to point to the new index page
1279  $pathofwebsite = $conf->website->dir_output.'/'.$object->ref;
1280  dolSaveIndexPage($pathofwebsite, $pathofwebsite.'/index.php', $pathofwebsite.'/page'.$object->fk_default_home.'.tpl.php', $pathofwebsite.'/wrapper.php', $object);
1281 
1282  if ($error) {
1283  $this->db->rollback();
1284  return -1;
1285  } else {
1286  $this->db->commit();
1287  return $object->id;
1288  }
1289  }
1290 
1297  public function rebuildWebSiteFiles()
1298  {
1299  global $conf;
1300 
1301  $error = 0;
1302 
1303  $object = $this;
1304  if (empty($object->ref)) {
1305  $this->error = 'Function rebuildWebSiteFiles called on object not loaded (object->ref is empty)';
1306  return -1;
1307  }
1308 
1309  $objectpagestatic = new WebsitePage($this->db);
1310 
1311  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."website_page WHERE fk_website = ".((int) $this->id);
1312 
1313  $resql = $this->db->query($sql);
1314  if (!$resql) {
1315  $this->error = $this->db->lasterror();
1316  return -1;
1317  }
1318 
1319  $num = $this->db->num_rows($resql);
1320 
1321  // Loop on each container/page
1322  $i = 0;
1323  while ($i < $num) {
1324  $obj = $this->db->fetch_object($resql);
1325 
1326  $newid = $obj->rowid;
1327 
1328  $objectpagestatic->fetch($newid);
1329 
1330  $aliasesarray = explode(',', $objectpagestatic->aliasalt);
1331 
1332  $filetpl = $conf->website->dir_output.'/'.$object->ref.'/page'.$newid.'.tpl.php';
1333  $result = dolSavePageContent($filetpl, $object, $objectpagestatic);
1334  if (!$result) {
1335  $this->errors[] = 'Failed to write file '.basename($filetpl);
1336  $error++;
1337  }
1338 
1339  // Add main alias to list of alternative aliases
1340  if (!empty($objectpagestatic->pageurl) && !in_array($objectpagestatic->pageurl, $aliasesarray)) {
1341  $aliasesarray[] = $objectpagestatic->pageurl;
1342  }
1343 
1344  // Regenerate also all aliases pages (pages with a natural name) by calling dolSavePageAlias()
1345  if (is_array($aliasesarray)) {
1346  foreach ($aliasesarray as $aliasshortcuttocreate) {
1347  if (trim($aliasshortcuttocreate)) {
1348  $filealias = $conf->website->dir_output.'/'.$object->ref.'/'.trim($aliasshortcuttocreate).'.php';
1349  $result = dolSavePageAlias($filealias, $object, $objectpagestatic); // This includes also a copy into sublanguage directories.
1350  if (!$result) {
1351  $this->errors[] = 'Failed to write file '.basename($filealias);
1352  $error++;
1353  }
1354  }
1355  }
1356  }
1357 
1358  $i++;
1359  }
1360 
1361  if (!$error) {
1362  // Save index.php and wrapper.php
1363  $pathofwebsite = $conf->website->dir_output.'/'.$object->ref;
1364  $fileindex = $pathofwebsite.'/index.php';
1365  $filetpl = '';
1366  if ($object->fk_default_home > 0) {
1367  $filetpl = $pathofwebsite.'/page'.$object->fk_default_home.'.tpl.php';
1368  }
1369  $filewrapper = $pathofwebsite.'/wrapper.php';
1370  dolSaveIndexPage($pathofwebsite, $fileindex, $filetpl, $filewrapper, $object); // This includes also a version of index.php into sublanguage directories
1371  }
1372 
1373  if ($error) {
1374  return -1;
1375  } else {
1376  return $num;
1377  }
1378  }
1379 
1385  public function isMultiLang()
1386  {
1387  return (empty($this->otherlang) ? false : true);
1388  }
1389 
1399  public function componentSelectLang($languagecodes, $weblangs, $morecss = '', $htmlname = '')
1400  {
1401  global $websitepagefile, $website;
1402 
1403  if (!is_object($weblangs)) {
1404  return 'ERROR componentSelectLang called with parameter $weblangs not defined';
1405  }
1406 
1407  $arrayofspecialmainlanguages = array(
1408  'en'=>'en_US',
1409  'sq'=>'sq_AL',
1410  'ar'=>'ar_SA',
1411  'eu'=>'eu_ES',
1412  'bn'=>'bn_DB',
1413  'bs'=>'bs_BA',
1414  'ca'=>'ca_ES',
1415  'zh'=>'zh_CN',
1416  'cs'=>'cs_CZ',
1417  'da'=>'da_DK',
1418  'et'=>'et_EE',
1419  'ka'=>'ka_GE',
1420  'el'=>'el_GR',
1421  'he'=>'he_IL',
1422  'kn'=>'kn_IN',
1423  'km'=>'km_KH',
1424  'ko'=>'ko_KR',
1425  'lo'=>'lo_LA',
1426  'nb'=>'nb_NO',
1427  'fa'=>'fa_IR',
1428  'sr'=>'sr_RS',
1429  'sl'=>'sl_SI',
1430  'uk'=>'uk_UA',
1431  'vi'=>'vi_VN'
1432  );
1433 
1434  // Load tmppage if we have $websitepagefile defined
1435  $tmppage = new WebsitePage($this->db);
1436 
1437  $pageid = 0;
1438  if (!empty($websitepagefile)) {
1439  $websitepagefileshort = basename($websitepagefile);
1440  if ($websitepagefileshort == 'index.php') {
1441  $pageid = $website->fk_default_home;
1442  } else {
1443  $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), $websitepagefileshort);
1444  }
1445  if ($pageid > 0) {
1446  $tmppage->fetch($pageid);
1447  }
1448  }
1449 
1450  // Fill $languagecodes array with existing translation, nothing if none
1451  if (!is_array($languagecodes) && $pageid > 0) {
1452  $languagecodes = array();
1453 
1454  $sql = "SELECT wp.rowid, wp.lang, wp.pageurl, wp.fk_page";
1455  $sql .= " FROM ".MAIN_DB_PREFIX."website_page as wp";
1456  $sql .= " WHERE wp.fk_website = ".((int) $website->id);
1457  $sql .= " AND (wp.fk_page = ".((int) $pageid)." OR wp.rowid = ".((int) $pageid);
1458  if ($tmppage->fk_page > 0) {
1459  $sql .= " OR wp.fk_page = ".((int) $tmppage->fk_page)." OR wp.rowid = ".((int) $tmppage->fk_page);
1460  }
1461  $sql .= ")";
1462 
1463  $resql = $this->db->query($sql);
1464  if ($resql) {
1465  while ($obj = $this->db->fetch_object($resql)) {
1466  $newlang = $obj->lang;
1467  if ($obj->rowid == $pageid) {
1468  $newlang = $obj->lang;
1469  }
1470  if (!in_array($newlang, $languagecodes)) {
1471  $languagecodes[] = $newlang;
1472  }
1473  }
1474  }
1475  }
1476  // Now $languagecodes is always an array. Example array('en', 'fr', 'es');
1477 
1478  $languagecodeselected = substr($weblangs->defaultlang, 0, 2); // Because we must init with a value, but real value is the lang of main parent container
1479  if (!empty($websitepagefile)) {
1480  $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), basename($websitepagefile));
1481  if ($pageid > 0) {
1482  $pagelang = substr($tmppage->lang, 0, 2);
1483  $languagecodeselected = substr($pagelang, 0, 2);
1484  if (!in_array($pagelang, $languagecodes)) {
1485  $languagecodes[] = $pagelang; // We add language code of page into combo list
1486  }
1487  }
1488  }
1489 
1490  $weblangs->load('languages');
1491  //var_dump($weblangs->defaultlang);
1492 
1493  $url = $_SERVER["REQUEST_URI"];
1494  $url = preg_replace('/(\?|&)l=([a-zA-Z_]*)/', '', $url); // We remove param l from url
1495  //$url = preg_replace('/(\?|&)lang=([a-zA-Z_]*)/', '', $url); // We remove param lang from url
1496  $url .= (preg_match('/\?/', $url) ? '&' : '?').'l=';
1497  if (!preg_match('/^\//', $url)) {
1498  $url = '/'.$url;
1499  }
1500 
1501  $HEIGHTOPTION = 40;
1502  $MAXHEIGHT = 4 * $HEIGHTOPTION;
1503  $nboflanguage = count($languagecodes);
1504 
1505  $out = '<!-- componentSelectLang'.$htmlname.' -->'."\n";
1506 
1507  $out .= '<style>';
1508  $out .= '.componentSelectLang'.$htmlname.':hover { height: '.min($MAXHEIGHT, ($HEIGHTOPTION * $nboflanguage)).'px; overflow-x: hidden; overflow-y: '.((($HEIGHTOPTION * $nboflanguage) > $MAXHEIGHT) ? ' scroll' : 'hidden').'; }'."\n";
1509  $out .= '.componentSelectLang'.$htmlname.' li { line-height: '.$HEIGHTOPTION.'px; }'."\n";
1510  $out .= '.componentSelectLang'.$htmlname.' {
1511  display: inline-block;
1512  padding: 0;
1513  height: '.$HEIGHTOPTION.'px;
1514  overflow: hidden;
1515  transition: all .3s ease;
1516  margin: 0 0 0 0;
1517  vertical-align: top;
1518  }
1519  .componentSelectLang'.$htmlname.':hover, .componentSelectLang'.$htmlname.':hover a { background-color: #fff; color: #000 !important; }
1520  ul.componentSelectLang'.$htmlname.' { width: 150px; }
1521  ul.componentSelectLang'.$htmlname.':hover .fa { visibility: hidden; }
1522  .componentSelectLang'.$htmlname.' a { text-decoration: none; width: 100%; }
1523  .componentSelectLang'.$htmlname.' li { display: block; padding: 0px 15px; margin-left: 0; margin-right: 0; }
1524  .componentSelectLang'.$htmlname.' li:hover { background-color: #EEE; }
1525  ';
1526  $out .= '</style>';
1527  $out .= '<ul class="componentSelectLang'.$htmlname.($morecss ? ' '.$morecss : '').'">';
1528 
1529  if ($languagecodeselected) {
1530  // Convert $languagecodeselected into a long language code
1531  if (strlen($languagecodeselected) == 2) {
1532  $languagecodeselected = (empty($arrayofspecialmainlanguages[$languagecodeselected]) ? $languagecodeselected.'_'.strtoupper($languagecodeselected) : $arrayofspecialmainlanguages[$languagecodeselected]);
1533  }
1534 
1535  $countrycode = strtolower(substr($languagecodeselected, -2));
1536  $label = $weblangs->trans("Language_".$languagecodeselected);
1537  if ($countrycode == 'us') {
1538  $label = preg_replace('/\s*\(.*\)/', '', $label);
1539  }
1540  $out .= '<a href="'.$url.substr($languagecodeselected, 0, 2).'"><li><img height="12px" src="/medias/image/common/flags/'.$countrycode.'.png" style="margin-right: 5px;"/><span class="websitecomponentlilang">'.$label.'</span>';
1541  $out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
1542  $out .= '</li></a>';
1543  }
1544  $i = 0;
1545  if (is_array($languagecodes)) {
1546  foreach ($languagecodes as $languagecode) {
1547  // Convert $languagecode into a long language code
1548  if (strlen($languagecode) == 2) {
1549  $languagecode = (empty($arrayofspecialmainlanguages[$languagecode]) ? $languagecode.'_'.strtoupper($languagecode) : $arrayofspecialmainlanguages[$languagecode]);
1550  }
1551 
1552  if ($languagecode == $languagecodeselected) {
1553  continue; // Already output
1554  }
1555 
1556  $countrycode = strtolower(substr($languagecode, -2));
1557  $label = $weblangs->trans("Language_".$languagecode);
1558  if ($countrycode == 'us') {
1559  $label = preg_replace('/\s*\(.*\)/', '', $label);
1560  }
1561  $out .= '<a href="'.$url.substr($languagecode, 0, 2).'"><li><img height="12px" src="/medias/image/common/flags/'.$countrycode.'.png" style="margin-right: 5px;"/><span class="websitecomponentlilang">'.$label.'</span>';
1562  if (empty($i) && empty($languagecodeselected)) {
1563  $out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
1564  }
1565  $out .= '</li></a>';
1566  $i++;
1567  }
1568  }
1569  $out .= '</ul>';
1570 
1571  return $out;
1572  }
1573 }
Website\importWebSite
importWebSite($pathtofile)
Open a zip with all data of web site and load it into database.
Definition: website.class.php:1140
db
$conf db
API class for accounts.
Definition: inc.php:41
dolSavePageContent
dolSavePageContent($filetpl, Website $object, WebsitePage $objectpage, $backupold=0)
Save content of a page on disk (page name is generally ID_of_page.php).
Definition: website2.lib.php:147
WebsitePage
Class Websitepage.
Definition: websitepage.class.php:36
Website\exportWebSite
exportWebSite()
Generate a zip with all data of web site.
Definition: website.class.php:926
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1226
description
print *****$script_file(".$version.") pid cd cd cd description as description
Definition: email_expire_services_to_customers.php:83
Website\LibStatut
LibStatut($status, $mode=0)
Renvoi le libelle d'un status donne.
Definition: website.class.php:871
dol_delete_dir_recursive
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:1383
DoliDB
Class to manage Dolibarr database access.
Definition: DoliDB.class.php:30
dol_osencode
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
Definition: functions.lib.php:8499
Website\getNomUrl
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,...
Definition: website.class.php:820
Website\isMultiLang
isMultiLang()
Return if web site is a multilanguage web site.
Definition: website.class.php:1385
dol_uncompress
dol_uncompress($inputfile, $outputdir)
Uncompress a file.
Definition: files.lib.php:2155
dolReplaceInFile
dolReplaceInFile($srcfile, $arrayreplacement, $destfile='', $newmask=0, $indexdatabase=0, $arrayreplacementisregex=0)
Make replacement of strings into a file.
Definition: files.lib.php:623
Website\componentSelectLang
componentSelectLang($languagecodes, $weblangs, $morecss='', $htmlname='')
Component to select language inside a container (Full CSS Only)
Definition: website.class.php:1399
ref
$object ref
Definition: info.php:77
CommonObject
Parent class of all other business classes (invoices, contracts, proposals, orders,...
Definition: commonobject.class.php:44
dolSaveMasterFile
dolSaveMasterFile($filemaster)
Save content of a page on disk.
Definition: website2.lib.php:32
dolSaveIndexPage
dolSaveIndexPage($pathofwebsite, $fileindex, $filetpl, $filewrapper, $object=null)
Save content of the index.php and/or the wrapper.php page.
Definition: website2.lib.php:297
dol_print_date
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Definition: functions.lib.php:2514
dol_delete_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.
Definition: files.lib.php:1231
Website\update
update(User $user, $notrigger=false)
Update object into database.
Definition: website.class.php:476
Website\rebuildWebSiteFiles
rebuildWebSiteFiles()
Rebuild all files of all the pages/containers of a website.
Definition: website.class.php:1297
Website\create
create(User $user, $notrigger=false)
Create object into database.
Definition: website.class.php:154
Website\initAsSpecimen
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
Definition: website.class.php:900
dolCopyDir
dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement=null, $excludesubdir=0)
Copy a dir to another dir.
Definition: files.lib.php:762
Website\fetchLines
fetchLines()
Load object lines in memory from the database.
Definition: website.class.php:372
Website\createFromClone
createFromClone($user, $fromid, $newref, $newlang='')
Load a website its id and create a new one in database.
Definition: website.class.php:650
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
Website\fetch
fetch($id, $ref=null)
Load object in memory from the database.
Definition: website.class.php:296
dol_strlen
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Definition: functions.lib.php:3747
Website
Class Website.
Definition: website.class.php:36
User
Class to manage Dolibarr users.
Definition: user.class.php:44
dolSavePageAlias
dolSavePageAlias($filealias, $object, $objectpage)
Save an alias page on disk (A page that include the reference page).
Definition: website2.lib.php:65
Website\getLibStatut
getLibStatut($mode=0)
Retourne le libelle du status d'un user (actif, inactif)
Definition: website.class.php:858
dolGetStatus
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
Definition: functions.lib.php:10338
Website\fetchAll
fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, array $filter=array(), $filtermode='AND')
Load all object in memory ($this->records) from the database.
Definition: website.class.php:394
run_sql
run_sql($sqlfile, $silent=1, $entity='', $usesavepoint=1, $handler='', $okerror='default', $linelengthlimit=32768, $nocommentremoval=0, $offsetforchartofaccount=0, $colspan=0, $onlysqltoimportwebsite=0)
Launch a sql file.
Definition: admin.lib.php:167
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2845
$resql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice') && $user->rights->supplier_invoice->lire)) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
Definition: functions.lib.php:8137
dol_mkdir
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
Definition: functions.lib.php:6603
Website\__construct
__construct(DoliDB $db)
Constructor.
Definition: website.class.php:140
dol_move
dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=1)
Move a file into another name.
Definition: files.lib.php:855
float
div float
Buy price without taxes.
Definition: style.css.php:809