dolibarr  19.0.0-dev
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 
33 
37 class Website extends CommonObject
38 {
42  public $element = 'website';
43 
47  public $table_element = 'website';
48 
52  public $ismultientitymanaged = 1;
53 
54 
55  protected $childtablesoncascade = array();
56 
57 
61  public $picto = 'globe';
62 
66  public $entity;
67 
71  public $ref;
72 
76  public $description;
77 
81  public $lang;
82 
86  public $otherlang;
87 
91  public $status;
92 
96  public $date_creation;
97 
101  public $date_modification;
102  public $tms;
103 
107  public $fk_default_home;
108 
112  public $fk_user_creat;
113 
117  public $fk_user_modif;
118 
122  public $virtualhost;
123 
127  public $use_manifest;
128 
132  public $position;
133 
139  public $lines;
140 
141 
142  const STATUS_DRAFT = 0;
143  const STATUS_VALIDATED = 1;
144 
145 
151  public function __construct(DoliDB $db)
152  {
153  $this->db = $db;
154  return 1;
155  }
156 
165  public function create(User $user, $notrigger = false)
166  {
167  global $conf, $langs;
168 
169  dol_syslog(__METHOD__, LOG_DEBUG);
170 
171  $error = 0;
172  $now = dol_now();
173 
174  // Clean parameters
175  if (isset($this->entity)) {
176  $this->entity = (int) $this->entity;
177  }
178  if (isset($this->ref)) {
179  $this->ref = trim($this->ref);
180  }
181  if (isset($this->description)) {
182  $this->description = trim($this->description);
183  }
184  if (isset($this->status)) {
185  $this->status = (int) $this->status;
186  }
187  if (empty($this->date_creation)) {
188  $this->date_creation = $now;
189  }
190  if (empty($this->date_modification)) {
191  $this->date_modification = $now;
192  }
193  // Remove spaces and be sure we have main language only
194  $this->lang = preg_replace('/[_-].*$/', '', trim($this->lang)); // en_US or en-US -> en
195  $tmparray = explode(',', $this->otherlang);
196  if (is_array($tmparray)) {
197  foreach ($tmparray as $key => $val) {
198  // It possible we have empty val here if postparam WEBSITE_OTHERLANG is empty or set like this : 'en,,sv' or 'en,sv,'
199  if (empty(trim($val))) {
200  unset($tmparray[$key]);
201  continue;
202  }
203  $tmparray[$key] = preg_replace('/[_-].*$/', '', trim($val)); // en_US or en-US -> en
204  }
205  $this->otherlang = join(',', $tmparray);
206  }
207 
208  // Check parameters
209  if (empty($this->entity)) {
210  $this->entity = $conf->entity;
211  }
212  if (empty($this->lang)) {
213  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MainLanguage"));
214  return -1;
215  }
216 
217  // Insert request
218  $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.'(';
219  $sql .= 'entity,';
220  $sql .= 'ref,';
221  $sql .= 'description,';
222  $sql .= 'lang,';
223  $sql .= 'otherlang,';
224  $sql .= 'status,';
225  $sql .= 'fk_default_home,';
226  $sql .= 'virtualhost,';
227  $sql .= 'fk_user_creat,';
228  $sql .= 'date_creation,';
229  $sql .= 'position,';
230  $sql .= 'tms';
231  $sql .= ') VALUES (';
232  $sql .= ' '.((empty($this->entity) && $this->entity != '0') ? 'NULL' : $this->entity).',';
233  $sql .= ' '.(!isset($this->ref) ? 'NULL' : "'".$this->db->escape($this->ref)."'").',';
234  $sql .= ' '.(!isset($this->description) ? 'NULL' : "'".$this->db->escape($this->description)."'").',';
235  $sql .= ' '.(!isset($this->lang) ? 'NULL' : "'".$this->db->escape($this->lang)."'").',';
236  $sql .= ' '.(!isset($this->otherlang) ? 'NULL' : "'".$this->db->escape($this->otherlang)."'").',';
237  $sql .= ' '.(!isset($this->status) ? '1' : $this->status).',';
238  $sql .= ' '.(!isset($this->fk_default_home) ? 'NULL' : $this->fk_default_home).',';
239  $sql .= ' '.(!isset($this->virtualhost) ? 'NULL' : "'".$this->db->escape($this->virtualhost)."'").",";
240  $sql .= ' '.(!isset($this->fk_user_creat) ? $user->id : $this->fk_user_creat).',';
241  $sql .= ' '.(!isset($this->date_creation) || dol_strlen($this->date_creation) == 0 ? 'NULL' : "'".$this->db->idate($this->date_creation)."'").",";
242  $sql .= ' '.((int) $this->position).",";
243  $sql .= ' '.(!isset($this->date_modification) || dol_strlen($this->date_modification) == 0 ? 'NULL' : "'".$this->db->idate($this->date_modification)."'");
244  $sql .= ')';
245 
246  $this->db->begin();
247 
248  $resql = $this->db->query($sql);
249  if (!$resql) {
250  $error++;
251  $this->errors[] = 'Error '.$this->db->lasterror();
252  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
253  }
254 
255  if (!$error) {
256  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
257 
258  // Create subdirectory per language
259  $tmplangarray = explode(',', $this->otherlang);
260  if (is_array($tmplangarray)) {
261  dol_mkdir($conf->website->dir_output.'/'.$this->ref);
262  foreach ($tmplangarray as $val) {
263  if (trim($val) == $this->lang) {
264  continue;
265  }
266  dol_mkdir($conf->website->dir_output.'/'.$this->ref.'/'.trim($val));
267  }
268  }
269 
270  // Uncomment this and change WEBSITE to your own tag if you
271  // want this action to call a trigger.
272  // if (!$notrigger) {
273 
274  // // Call triggers
275  // $result = $this->call_trigger('WEBSITE_CREATE',$user);
276  // if ($result < 0) $error++;
277  // // End call triggers
278  // }
279  }
280 
281  if (!$error) {
282  $stringtodolibarrfile = "# Some properties for Dolibarr web site CMS\n";
283  $stringtodolibarrfile .= "param=value\n";
284  //print $conf->website->dir_output.'/'.$this->ref.'/.dolibarr';exit;
285  file_put_contents($conf->website->dir_output.'/'.$this->ref.'/.dolibarr', $stringtodolibarrfile);
286  }
287 
288  // Commit or rollback
289  if ($error) {
290  $this->db->rollback();
291  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
292  return 0;
293  } else {
294  return -1 * $error;
295  }
296  } else {
297  $this->db->commit();
298 
299  return $this->id;
300  }
301  }
302 
310  public function fetch($id, $ref = null)
311  {
312  dol_syslog(__METHOD__, LOG_DEBUG);
313 
314  $sql = "SELECT";
315  $sql .= " t.rowid,";
316  $sql .= " t.entity,";
317  $sql .= " t.ref,";
318  $sql .= " t.position,";
319  $sql .= " t.description,";
320  $sql .= " t.lang,";
321  $sql .= " t.otherlang,";
322  $sql .= " t.status,";
323  $sql .= " t.fk_default_home,";
324  $sql .= " t.use_manifest,";
325  $sql .= " t.virtualhost,";
326  $sql .= " t.fk_user_creat,";
327  $sql .= " t.fk_user_modif,";
328  $sql .= " t.date_creation,";
329  $sql .= " t.tms as date_modification";
330  $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
331  $sql .= " WHERE t.entity IN (".getEntity('website').")";
332  if (!empty($ref)) {
333  $sql .= " AND t.ref = '".$this->db->escape($ref)."'";
334  } else {
335  $sql .= " AND t.rowid = ".(int) $id;
336  }
337 
338  $resql = $this->db->query($sql);
339  if ($resql) {
340  $numrows = $this->db->num_rows($resql);
341  if ($numrows) {
342  $obj = $this->db->fetch_object($resql);
343 
344  $this->id = $obj->rowid;
345 
346  $this->entity = $obj->entity;
347  $this->ref = $obj->ref;
348  $this->position = $obj->position;
349  $this->description = $obj->description;
350  $this->lang = $obj->lang;
351  $this->otherlang = $obj->otherlang;
352  $this->status = $obj->status;
353  $this->fk_default_home = $obj->fk_default_home;
354  $this->virtualhost = $obj->virtualhost;
355  $this->use_manifest = $obj->use_manifest;
356  $this->fk_user_creat = $obj->fk_user_creat;
357  $this->fk_user_modif = $obj->fk_user_modif;
358  $this->date_creation = $this->db->jdate($obj->date_creation);
359  $this->date_modification = $this->db->jdate($obj->date_modification);
360  }
361  $this->db->free($resql);
362 
363  if ($numrows > 0) {
364  // Lines
365  $this->fetchLines();
366  }
367 
368  if ($numrows > 0) {
369  return 1;
370  } else {
371  return 0;
372  }
373  } else {
374  $this->errors[] = 'Error '.$this->db->lasterror();
375  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
376 
377  return -1;
378  }
379  }
380 
386  public function fetchLines()
387  {
388  $this->lines = array();
389 
390  // Load lines with object MyObjectLine
391 
392  return count($this->lines) ? 1 : 0;
393  }
394 
395 
408  public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
409  {
410  dol_syslog(__METHOD__, LOG_DEBUG);
411 
412  $sql = "SELECT";
413  $sql .= " t.rowid,";
414  $sql .= " t.entity,";
415  $sql .= " t.ref,";
416  $sql .= " t.description,";
417  $sql .= " t.lang,";
418  $sql .= " t.otherlang,";
419  $sql .= " t.status,";
420  $sql .= " t.fk_default_home,";
421  $sql .= " t.virtualhost,";
422  $sql .= " t.fk_user_creat,";
423  $sql .= " t.fk_user_modif,";
424  $sql .= " t.date_creation,";
425  $sql .= " t.tms as date_modification";
426  $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
427  $sql .= " WHERE t.entity IN (".getEntity('website').")";
428  // Manage filter
429  $sqlwhere = array();
430  if (count($filter) > 0) {
431  foreach ($filter as $key => $value) {
432  $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
433  }
434  }
435  if (count($sqlwhere) > 0) {
436  $sql .= ' AND '.implode(' '.$this->db->escape($filtermode).' ', $sqlwhere);
437  }
438 
439  if (!empty($sortfield)) {
440  $sql .= $this->db->order($sortfield, $sortorder);
441  }
442  if (!empty($limit)) {
443  $sql .= $this->db->plimit($limit, $offset);
444  }
445  $this->lines = array();
446 
447  $resql = $this->db->query($sql);
448  if ($resql) {
449  $num = $this->db->num_rows($resql);
450 
451  while ($obj = $this->db->fetch_object($resql)) {
452  $line = new self($this->db);
453 
454  $line->id = $obj->rowid;
455 
456  $line->entity = $obj->entity;
457  $line->ref = $obj->ref;
458  $line->description = $obj->description;
459  $line->lang = $obj->lang;
460  $line->otherlang = $obj->otherlang;
461  $line->status = $obj->status;
462  $line->fk_default_home = $obj->fk_default_home;
463  $line->virtualhost = $obj->virtualhost;
464  $this->fk_user_creat = $obj->fk_user_creat;
465  $this->fk_user_modif = $obj->fk_user_modif;
466  $line->date_creation = $this->db->jdate($obj->date_creation);
467  $line->date_modification = $this->db->jdate($obj->date_modification);
468 
469  $this->lines[$line->id] = $line;
470  }
471  $this->db->free($resql);
472 
473  return $num;
474  } else {
475  $this->errors[] = 'Error '.$this->db->lasterror();
476  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
477 
478  return -1;
479  }
480  }
481 
490  public function update(User $user, $notrigger = false)
491  {
492  global $conf, $langs;
493 
494  $error = 0;
495 
496  dol_syslog(__METHOD__, LOG_DEBUG);
497 
498  // Clean parameters
499 
500  if (isset($this->entity)) {
501  $this->entity = (int) $this->entity;
502  }
503  if (isset($this->ref)) {
504  $this->ref = trim($this->ref);
505  }
506  if (isset($this->description)) {
507  $this->description = trim($this->description);
508  }
509  if (isset($this->status)) {
510  $this->status = (int) $this->status;
511  }
512 
513  // Remove spaces and be sure we have main language only
514  $this->lang = preg_replace('/[_-].*$/', '', trim($this->lang)); // en_US or en-US -> en
515  $tmparray = explode(',', $this->otherlang);
516  if (is_array($tmparray)) {
517  foreach ($tmparray as $key => $val) {
518  // It possible we have empty val here if postparam WEBSITE_OTHERLANG is empty or set like this : 'en,,sv' or 'en,sv,'
519  if (empty(trim($val))) {
520  unset($tmparray[$key]);
521  continue;
522  }
523  $tmparray[$key] = preg_replace('/[_-].*$/', '', trim($val)); // en_US or en-US -> en
524  }
525  $this->otherlang = join(',', $tmparray);
526  }
527  if (empty($this->lang)) {
528  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MainLanguage"));
529  return -1;
530  }
531 
532  // Check parameters
533  // Put here code to add a control on parameters values
534 
535  // Update request
536  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
537  $sql .= ' entity = '.(isset($this->entity) ? $this->entity : "null").',';
538  $sql .= ' ref = '.(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").',';
539  $sql .= ' description = '.(isset($this->description) ? "'".$this->db->escape($this->description)."'" : "null").',';
540  $sql .= ' lang = '.(isset($this->lang) ? "'".$this->db->escape($this->lang)."'" : "null").',';
541  $sql .= ' otherlang = '.(isset($this->otherlang) ? "'".$this->db->escape($this->otherlang)."'" : "null").',';
542  $sql .= ' status = '.(isset($this->status) ? $this->status : "null").',';
543  $sql .= ' fk_default_home = '.(($this->fk_default_home > 0) ? $this->fk_default_home : "null").',';
544  $sql .= ' use_manifest = '.((int) $this->use_manifest).',';
545  $sql .= ' virtualhost = '.(($this->virtualhost != '') ? "'".$this->db->escape($this->virtualhost)."'" : "null").',';
546  $sql .= ' fk_user_modif = '.(!isset($this->fk_user_modif) ? $user->id : $this->fk_user_modif).',';
547  $sql .= ' date_creation = '.(!isset($this->date_creation) || dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').',';
548  $sql .= ' tms = '.(dol_strlen($this->date_modification) != 0 ? "'".$this->db->idate($this->date_modification)."'" : "'".$this->db->idate(dol_now())."'");
549  $sql .= ' WHERE rowid='.((int) $this->id);
550 
551  $this->db->begin();
552 
553  $resql = $this->db->query($sql);
554  if (!$resql) {
555  $error++;
556  $this->errors[] = 'Error '.$this->db->lasterror();
557  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
558  }
559 
560  if (!$error && !$notrigger) {
561  // Uncomment this and change MYOBJECT to your own tag if you
562  // want this action calls a trigger.
563 
564  // Create subdirectory per language
565  $tmplangarray = explode(',', $this->otherlang);
566  if (is_array($tmplangarray)) {
567  dol_mkdir($conf->website->dir_output.'/'.$this->ref);
568  foreach ($tmplangarray as $val) {
569  if (trim($val) == $this->lang) {
570  continue;
571  }
572  dol_mkdir($conf->website->dir_output.'/'.$this->ref.'/'.trim($val));
573  }
574  }
575 
577  //$result=$this->call_trigger('WEBSITE_MODIFY',$user);
578  //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
580  }
581 
582  // Commit or rollback
583  if ($error) {
584  $this->db->rollback();
585 
586  return -1 * $error;
587  } else {
588  $this->db->commit();
589 
590  return 1;
591  }
592  }
593 
602  public function delete(User $user, $notrigger = false)
603  {
604  global $conf;
605 
606  dol_syslog(__METHOD__, LOG_DEBUG);
607 
608  $error = 0;
609 
610  $this->db->begin();
611 
612  if (!$error) {
613  $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'website_page';
614  $sql .= ' WHERE fk_website = '.((int) $this->id);
615 
616  $resql = $this->db->query($sql);
617  if (!$resql) {
618  $error++;
619  $this->errors[] = 'Error '.$this->db->lasterror();
620  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
621  }
622  }
623 
624  // Delete common code. This include execution of trigger.
625  $result = $this->deleteCommon($user, $notrigger);
626  if ($result <= 0) {
627  $error++;
628  }
629 
630  if (!$error && !empty($this->ref)) {
631  $pathofwebsite = DOL_DATA_ROOT.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.$this->ref;
632 
633  dol_delete_dir_recursive($pathofwebsite);
634  }
635 
636  // Commit or rollback
637  if ($error) {
638  $this->db->rollback();
639 
640  return -1 * $error;
641  } else {
642  $this->db->commit();
643 
644  return 1;
645  }
646  }
647 
658  public function createFromClone($user, $fromid, $newref, $newlang = '')
659  {
660  global $conf, $langs;
661  global $dolibarr_main_data_root;
662 
663  $now = dol_now();
664  $error = 0;
665 
666  dol_syslog(__METHOD__, LOG_DEBUG);
667 
668  $newref = dol_sanitizeFileName($newref);
669 
670  if (empty($newref)) {
671  $this->error = 'ErrorBadParameter';
672  return -1;
673  }
674 
675  $object = new self($this->db);
676 
677  // Check no site with ref exists
678  if ($object->fetch(0, $newref) > 0) {
679  $this->error = 'ErrorNewRefIsAlreadyUsed';
680  return -1;
681  }
682 
683  $this->db->begin();
684 
685  // Load source object
686  $object->fetch($fromid);
687 
688  $oldidforhome = $object->fk_default_home;
689  $oldref = $object->ref;
690 
691  $pathofwebsiteold = $dolibarr_main_data_root.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.dol_sanitizeFileName($oldref);
692  $pathofwebsitenew = $dolibarr_main_data_root.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.dol_sanitizeFileName($newref);
693  dol_delete_dir_recursive($pathofwebsitenew);
694 
695  $fileindex = $pathofwebsitenew.'/index.php';
696 
697  // Reset some properties
698  unset($object->id);
699  unset($object->fk_user_creat);
700  unset($object->import_key);
701 
702  // Clear fields
703  $object->ref = $newref;
704  $object->fk_default_home = 0;
705  $object->virtualhost = '';
706  $object->date_creation = $now;
707  $object->fk_user_creat = $user->id;
708  $object->position = ((int) $object->position) + 1;
709  $object->status = self::STATUS_DRAFT;
710  if (empty($object->lang)) {
711  $object->lang = substr($langs->defaultlang, 0, 2); // Should not happen. Protection for corrupted site with no languages
712  }
713 
714  // Create clone
715  $object->context['createfromclone'] = 'createfromclone';
716  $result = $object->create($user);
717  if ($result < 0) {
718  $error++;
719  $this->error = $object->error;
720  $this->errors = $object->errors;
721  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
722  }
723 
724  if (!$error) {
725  dolCopyDir($pathofwebsiteold, $pathofwebsitenew, $conf->global->MAIN_UMASK, 0, null, 2);
726 
727  // Check symlink to medias and restore it if ko
728  $pathtomedias = DOL_DATA_ROOT.'/medias'; // Target
729  $pathtomediasinwebsite = $pathofwebsitenew.'/medias'; // Source / Link name
730  if (!is_link(dol_osencode($pathtomediasinwebsite))) {
731  dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite);
732  dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists
733  $result = symlink($pathtomedias, $pathtomediasinwebsite);
734  }
735 
736  // Copy images and js dir
737  $pathofmediasjsold = DOL_DATA_ROOT.'/medias/js/'.$oldref;
738  $pathofmediasjsnew = DOL_DATA_ROOT.'/medias/js/'.$newref;
739  dolCopyDir($pathofmediasjsold, $pathofmediasjsnew, $conf->global->MAIN_UMASK, 0);
740 
741  $pathofmediasimageold = DOL_DATA_ROOT.'/medias/image/'.$oldref;
742  $pathofmediasimagenew = DOL_DATA_ROOT.'/medias/image/'.$newref;
743  dolCopyDir($pathofmediasimageold, $pathofmediasimagenew, $conf->global->MAIN_UMASK, 0);
744 
745  $newidforhome = 0;
746 
747  // Duplicate pages
748  $objectpages = new WebsitePage($this->db);
749  $listofpages = $objectpages->fetchAll($fromid);
750  foreach ($listofpages as $pageid => $objectpageold) {
751  // Delete old file
752  $filetplold = $pathofwebsitenew.'/page'.$pageid.'.tpl.php';
753  dol_delete_file($filetplold);
754 
755  // Create new file
756  $objectpagenew = $objectpageold->createFromClone($user, $pageid, $objectpageold->pageurl, '', 0, $object->id, 1);
757 
758  //print $pageid.' = '.$objectpageold->pageurl.' -> '.$objectpagenew->id.' = '.$objectpagenew->pageurl.'<br>';
759  if (is_object($objectpagenew) && $objectpagenew->pageurl) {
760  $filealias = $pathofwebsitenew.'/'.$objectpagenew->pageurl.'.php';
761  $filetplnew = $pathofwebsitenew.'/page'.$objectpagenew->id.'.tpl.php';
762 
763  // Save page alias
764  $result = dolSavePageAlias($filealias, $object, $objectpagenew);
765  if (!$result) {
766  setEventMessages('Failed to write file '.$filealias, null, 'errors');
767  }
768 
769  $result = dolSavePageContent($filetplnew, $object, $objectpagenew);
770  if (!$result) {
771  setEventMessages('Failed to write file '.$filetplnew, null, 'errors');
772  }
773 
774  if ($pageid == $oldidforhome) {
775  $newidforhome = $objectpagenew->id;
776  }
777  } else {
778  setEventMessages($objectpageold->error, $objectpageold->errors, 'errors');
779  $error++;
780  }
781  }
782  }
783 
784  if (!$error) {
785  // Restore id of home page
786  $object->fk_default_home = $newidforhome;
787  $res = $object->update($user);
788  if (!($res > 0)) {
789  $error++;
790  setEventMessages($object->error, $object->errors, 'errors');
791  }
792 
793  if (!$error) {
794  $filetpl = $pathofwebsitenew.'/page'.$newidforhome.'.tpl.php';
795  $filewrapper = $pathofwebsitenew.'/wrapper.php';
796 
797  // Re-generates the index.php page to be the home page, and re-generates the wrapper.php
798  //--------------------------------------------------------------------------------------
799  $result = dolSaveIndexPage($pathofwebsitenew, $fileindex, $filetpl, $filewrapper, $object);
800  }
801  }
802 
803  unset($object->context['createfromclone']);
804 
805  // End
806  if (!$error) {
807  $this->db->commit();
808 
809  return $object;
810  } else {
811  $this->db->rollback();
812 
813  return -1;
814  }
815  }
816 
828  public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $maxlen = 24, $morecss = '')
829  {
830  global $langs, $conf, $db;
831  global $dolibarr_main_authentication, $dolibarr_main_demo;
832  global $menumanager;
833 
834 
835  $result = '';
836  $companylink = '';
837 
838  $label = '<u>'.$langs->trans("WebSite").'</u>';
839  $label .= '<br>';
840  $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref.'<br>';
841  $label .= '<b>'.$langs->trans('MainLanguage').':</b> '.$this->lang;
842 
843  $linkstart = '<a href="'.DOL_URL_ROOT.'/website/card.php?id='.$this->id.'"';
844  $linkstart .= ($notooltip ? '' : ' title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip'.($morecss ? ' '.$morecss : '').'"');
845  $linkstart .= '>';
846  $linkend = '</a>';
847 
848  $linkstart = $linkend = '';
849 
850  if ($withpicto) {
851  $result .= ($linkstart.img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? '' : 'class="classfortooltip"')).$linkend);
852  if ($withpicto != 2) {
853  $result .= ' ';
854  }
855  }
856  $result .= $linkstart.$this->ref.$linkend;
857  return $result;
858  }
859 
866  public function getLibStatut($mode = 0)
867  {
868  return $this->LibStatut($this->status, $mode);
869  }
870 
871  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
879  public function LibStatut($status, $mode = 0)
880  {
881  // phpcs:enable
882  global $langs;
883 
884  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
885  global $langs;
886  //$langs->load("mymodule");
887  $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Offline');
888  $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Online');
889  $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Offline');
890  $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Online');
891  }
892 
893  $statusType = 'status5';
894  if ($status == self::STATUS_VALIDATED) {
895  $statusType = 'status4';
896  }
897 
898  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
899  }
900 
901 
908  public function initAsSpecimen()
909  {
910  global $user;
911 
912  $this->id = 0;
913  $this->specimen = 1;
914  $this->entity = 1;
915  $this->ref = 'myspecimenwebsite';
916  $this->description = 'A specimen website';
917  $this->lang = 'en';
918  $this->otherlang = 'fr,es';
919  $this->status = 1;
920  $this->fk_default_home = null;
921  $this->virtualhost = 'http://myvirtualhost';
922  $this->fk_user_creat = $user->id;
923  $this->fk_user_modif = $user->id;
924  $this->date_creation = dol_now();
925  $this->tms = dol_now();
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 
954  dol_syslog("Clear temp dir ".$destdir);
955  $count = 0; $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'));
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 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  // Assign ->newid and ->newfk_page
1036  $i = 1;
1037  foreach ($listofpages as $pageid => $objectpageold) {
1038  $objectpageold->newid = $i;
1039  $i++;
1040  }
1041  $i = 1;
1042  foreach ($listofpages as $pageid => $objectpageold) {
1043  // Search newid
1044  $newfk_page = 0;
1045  foreach ($listofpages as $pageid2 => $objectpageold2) {
1046  if ($pageid2 == $objectpageold->fk_page) {
1047  $newfk_page = $objectpageold2->newid;
1048  break;
1049  }
1050  }
1051  $objectpageold->newfk_page = $newfk_page;
1052  $i++;
1053  }
1054  foreach ($listofpages as $pageid => $objectpageold) {
1055  $allaliases = $objectpageold->pageurl;
1056  $allaliases .= ($objectpageold->aliasalt ? ','.$objectpageold->aliasalt : '');
1057 
1058  $line = '-- File generated by Dolibarr '.DOL_VERSION.' -- '.dol_print_date(dol_now('gmt'), 'standard', 'gmt').' UTC --;';
1059  $line .= "\n";
1060 
1061  $line .= '-- Page ID '.$objectpageold->id.' -> '.$objectpageold->newid.'__+MAX_llx_website_page__ - Aliases '.$allaliases.' --;'; // newid start at 1, 2...
1062  $line .= "\n";
1063  fputs($fp, $line);
1064 
1065  // Warning: We must keep llx_ here. It is a generic SQL.
1066  $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)';
1067 
1068  $line .= " VALUES(";
1069  $line .= $objectpageold->newid."__+MAX_llx_website_page__, ";
1070  $line .= ($objectpageold->newfk_page ? $this->db->escape($objectpageold->newfk_page)."__+MAX_llx_website_page__" : "null").", ";
1071  $line .= "__WEBSITE_ID__, ";
1072  $line .= "'".$this->db->escape($objectpageold->pageurl)."', ";
1073  $line .= "'".$this->db->escape($objectpageold->aliasalt)."', ";
1074  $line .= "'".$this->db->escape($objectpageold->title)."', ";
1075  $line .= "'".$this->db->escape($objectpageold->description)."', ";
1076  $line .= "'".$this->db->escape($objectpageold->lang)."', ";
1077  $line .= "'".$this->db->escape($objectpageold->image)."', ";
1078  $line .= "'".$this->db->escape($objectpageold->keywords)."', ";
1079  $line .= "'".$this->db->escape($objectpageold->status)."', ";
1080  $line .= "'".$this->db->idate($objectpageold->date_creation)."', ";
1081  $line .= "'".$this->db->idate($objectpageold->date_modification)."', ";
1082  $line .= ($objectpageold->import_key ? "'".$this->db->escape($objectpageold->import_key)."'" : "null").", ";
1083  $line .= "'".$this->db->escape($objectpageold->grabbed_from)."', ";
1084  $line .= "'".$this->db->escape($objectpageold->type_container)."', ";
1085 
1086  // Make substitution with a generic path into htmlheader content
1087  $stringtoexport = $objectpageold->htmlheader;
1088  $stringtoexport = str_replace(array("\r\n", "\r", "\n"), "__N__", $stringtoexport);
1089  $stringtoexport = str_replace('file=image/'.$website->ref.'/', "file=image/__WEBSITE_KEY__/", $stringtoexport);
1090  $stringtoexport = str_replace('file=js/'.$website->ref.'/', "file=js/__WEBSITE_KEY__/", $stringtoexport);
1091  $stringtoexport = str_replace('medias/image/'.$website->ref.'/', "medias/image/__WEBSITE_KEY__/", $stringtoexport);
1092  $stringtoexport = str_replace('medias/js/'.$website->ref.'/', "medias/js/__WEBSITE_KEY__/", $stringtoexport);
1093 
1094  $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_small, "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__", $stringtoexport);
1095  $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_mini, "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__", $stringtoexport);
1096  $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo, "file=logos%2Fthumbs%2F__LOGO_KEY__", $stringtoexport);
1097  $line .= "'".$this->db->escape(str_replace(array("\r\n", "\r", "\n"), "__N__", $stringtoexport))."', "; // Replace \r \n to have record on 1 line
1098 
1099  // Make substitution with a generic path into page content
1100  $stringtoexport = $objectpageold->content;
1101  $stringtoexport = str_replace(array("\r\n", "\r", "\n"), "__N__", $stringtoexport);
1102  $stringtoexport = str_replace('file=image/'.$website->ref.'/', "file=image/__WEBSITE_KEY__/", $stringtoexport);
1103  $stringtoexport = str_replace('file=js/'.$website->ref.'/', "file=js/__WEBSITE_KEY__/", $stringtoexport);
1104  $stringtoexport = str_replace('medias/image/'.$website->ref.'/', "medias/image/__WEBSITE_KEY__/", $stringtoexport);
1105  $stringtoexport = str_replace('medias/js/'.$website->ref.'/', "medias/js/__WEBSITE_KEY__/", $stringtoexport);
1106  $stringtoexport = str_replace('"image/'.$website->ref.'/', '"image/__WEBSITE_KEY__/', $stringtoexport); // When we have a link src="image/websiteref/file.png" into html content
1107  $stringtoexport = str_replace('"/image/'.$website->ref.'/', '"/image/__WEBSITE_KEY__/', $stringtoexport); // When we have a link src="/image/websiteref/file.png" into html content
1108  $stringtoexport = str_replace('"js/'.$website->ref.'/', '"js/__WEBSITE_KEY__/', $stringtoexport);
1109  $stringtoexport = str_replace('"/js/'.$website->ref.'/', '"/js/__WEBSITE_KEY__/', $stringtoexport);
1110 
1111  $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_small, "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__", $stringtoexport);
1112  $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_mini, "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__", $stringtoexport);
1113  $stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo, "file=logos%2Fthumbs%2F__LOGO_KEY__", $stringtoexport);
1114 
1115 
1116  $line .= "'".$this->db->escape($stringtoexport)."', "; // Replace \r \n to have record on 1 line
1117  $line .= "'".$this->db->escape($objectpageold->author_alias)."', ";
1118  $line .= (int) $objectpageold->allowed_in_frames;
1119  $line .= ");";
1120  $line .= "\n";
1121 
1122  fputs($fp, $line);
1123 
1124  // Add line to update home page id during import
1125  //var_dump($this->fk_default_home.' - '.$objectpageold->id.' - '.$objectpageold->newid);exit;
1126  if ($this->fk_default_home > 0 && ($objectpageold->id == $this->fk_default_home) && ($objectpageold->newid > 0)) { // This is the record with home page
1127  // Warning: We must keep llx_ here. It is a generic SQL.
1128  $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__;";
1129  $line .= "\n";
1130  fputs($fp, $line);
1131  }
1132  }
1133 
1134  $line = "\n-- For Dolibarr v14+ --;\n";
1135  $line .= "UPDATE llx_website SET lang = '".$this->db->escape($this->lang)."' WHERE rowid = __WEBSITE_ID__;\n";
1136  $line .= "UPDATE llx_website SET otherlang = '".$this->db->escape($this->otherlang)."' WHERE rowid = __WEBSITE_ID__;\n";
1137  $line .= "\n";
1138  fputs($fp, $line);
1139 
1140  fclose($fp);
1141  dolChmod($filesql);
1142 
1143  // Build zip file
1144  $filedir = $conf->website->dir_temp.'/'.$website->ref.'/.';
1145  $fileglob = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-*.zip';
1146  $filename = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-'.dol_print_date(dol_now(), 'dayhourlog').'-V'.((float) DOL_VERSION).'.zip';
1147 
1148  dol_delete_file($fileglob, 0);
1149  $result = dol_compress_file($filedir, $filename, 'zip');
1150 
1151  if ($result > 0) {
1152  return $filename;
1153  } else {
1154  global $errormsg;
1155  $this->error = $errormsg;
1156  return '';
1157  }
1158  }
1159 
1160 
1167  public function importWebSite($pathtofile)
1168  {
1169  global $conf, $mysoc;
1170 
1171  $error = 0;
1172 
1173  $pathtofile = dol_sanitizePathName($pathtofile);
1174 
1175  $object = $this;
1176  if (empty($object->ref)) {
1177  $this->error = 'Function importWebSite called on object not loaded (object->ref is empty)';
1178  return -2;
1179  }
1180 
1181  dol_delete_dir_recursive($conf->website->dir_temp."/".$object->ref);
1182  dol_mkdir($conf->website->dir_temp.'/'.$object->ref);
1183 
1184  $filename = basename($pathtofile);
1185  if (!preg_match('/^website_(.*)-(.*)$/', $filename, $reg)) {
1186  $this->errors[] = 'Bad format for filename '.$filename.'. Must be website_XXX-VERSION.';
1187  return -3;
1188  }
1189 
1190  $result = dol_uncompress($pathtofile, $conf->website->dir_temp.'/'.$object->ref);
1191 
1192  if (!empty($result['error'])) {
1193  $this->errors[] = 'Failed to unzip file '.$pathtofile.'.';
1194  return -4;
1195  }
1196 
1197  $arrayreplacement = array();
1198  $arrayreplacement['__WEBSITE_ID__'] = $object->id;
1199  $arrayreplacement['__WEBSITE_KEY__'] = $object->ref;
1200  $arrayreplacement['__N__'] = $this->db->escape("\n"); // Restore \n
1201  $arrayreplacement['__LOGO_SMALL_KEY__'] = $this->db->escape($mysoc->logo_small);
1202  $arrayreplacement['__LOGO_MINI_KEY__'] = $this->db->escape($mysoc->logo_mini);
1203  $arrayreplacement['__LOGO_KEY__'] = $this->db->escape($mysoc->logo);
1204 
1205  // Copy containers
1206  dolCopyDir($conf->website->dir_temp.'/'.$object->ref.'/containers', $conf->website->dir_output.'/'.$object->ref, 0, 1); // Overwrite if exists
1207 
1208  // Make replacement into css and htmlheader file
1209  $cssindestdir = $conf->website->dir_output.'/'.$object->ref.'/styles.css.php';
1210  $result = dolReplaceInFile($cssindestdir, $arrayreplacement);
1211 
1212  $htmldeaderindestdir = $conf->website->dir_output.'/'.$object->ref.'/htmlheader.html';
1213  $result = dolReplaceInFile($htmldeaderindestdir, $arrayreplacement);
1214 
1215  // Now generate the master.inc.php page
1216  $filemaster = $conf->website->dir_output.'/'.$object->ref.'/master.inc.php';
1217  $result = dolSaveMasterFile($filemaster);
1218  if (!$result) {
1219  $this->errors[] = 'Failed to write file '.$filemaster;
1220  $error++;
1221  }
1222 
1223  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
1224  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
1225 
1226  $sqlfile = $conf->website->dir_temp."/".$object->ref.'/website_pages.sql';
1227 
1228  $result = dolReplaceInFile($sqlfile, $arrayreplacement);
1229 
1230  $this->db->begin();
1231 
1232  // Search the $maxrowid because we need it later
1233  $sqlgetrowid = 'SELECT MAX(rowid) as max from '.MAIN_DB_PREFIX.'website_page';
1234  $resql = $this->db->query($sqlgetrowid);
1235  if ($resql) {
1236  $obj = $this->db->fetch_object($resql);
1237  $maxrowid = $obj->max;
1238  }
1239 
1240  // Load sql record
1241  $runsql = run_sql($sqlfile, 1, '', 0, '', 'none', 0, 1, 0, 0, 1); // The maxrowid of table is searched into this function two
1242  if ($runsql <= 0) {
1243  $this->errors[] = 'Failed to load sql file '.$sqlfile.' (ret='.((int) $runsql).')';
1244  $error++;
1245  }
1246 
1247  $objectpagestatic = new WebsitePage($this->db);
1248 
1249  // Make replacement of IDs
1250  $fp = fopen($sqlfile, "r");
1251  if ($fp) {
1252  while (!feof($fp)) {
1253  $reg = array();
1254 
1255  // Warning fgets with second parameter that is null or 0 hang.
1256  $buf = fgets($fp, 65000);
1257  if (preg_match('/^-- Page ID (\d+)\s[^\s]+\s(\d+).*Aliases\s(.*)\s--;/i', $buf, $reg)) {
1258  $oldid = $reg[1];
1259  $newid = ($reg[2] + $maxrowid);
1260  $aliasesarray = explode(',', $reg[3]);
1261 
1262  dol_syslog("Found ID ".$oldid." to replace with ID ".$newid." and shortcut aliases to create: ".$reg[3]);
1263 
1264  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);
1265 
1266  $objectpagestatic->fetch($newid);
1267 
1268  // The move is not enough, so we regenerate page
1269  $filetpl = $conf->website->dir_output.'/'.$object->ref.'/page'.$newid.'.tpl.php';
1270  $result = dolSavePageContent($filetpl, $object, $objectpagestatic);
1271  if (!$result) {
1272  $this->errors[] = 'Failed to write file '.basename($filetpl);
1273  $error++;
1274  }
1275 
1276  // Regenerate alternative aliases pages
1277  if (is_array($aliasesarray)) {
1278  foreach ($aliasesarray as $aliasshortcuttocreate) {
1279  if (trim($aliasshortcuttocreate)) {
1280  $filealias = $conf->website->dir_output.'/'.$object->ref.'/'.trim($aliasshortcuttocreate).'.php';
1281  $result = dolSavePageAlias($filealias, $object, $objectpagestatic);
1282  if (!$result) {
1283  $this->errors[] = 'Failed to write file '.basename($filealias);
1284  $error++;
1285  }
1286  }
1287  }
1288  }
1289  }
1290  }
1291  }
1292 
1293  // Read record of website that has been updated by the run_sql function previously called so we can get the
1294  // value of fk_default_home that is ID of home page
1295  $sql = "SELECT fk_default_home FROM ".MAIN_DB_PREFIX."website WHERE rowid = ".((int) $object->id);
1296  $resql = $this->db->query($sql);
1297  if ($resql) {
1298  $obj = $this->db->fetch_object($resql);
1299  if ($obj) {
1300  $object->fk_default_home = $obj->fk_default_home;
1301  } else {
1302  //$this->errors[] = 'Failed to get the Home page';
1303  //$error++;
1304  }
1305  }
1306 
1307  // Regenerate index page to point to the new index page
1308  $pathofwebsite = $conf->website->dir_output.'/'.$object->ref;
1309  dolSaveIndexPage($pathofwebsite, $pathofwebsite.'/index.php', $pathofwebsite.'/page'.$object->fk_default_home.'.tpl.php', $pathofwebsite.'/wrapper.php', $object);
1310 
1311  if ($error) {
1312  $this->db->rollback();
1313  return -1;
1314  } else {
1315  $this->db->commit();
1316  return $object->id;
1317  }
1318  }
1319 
1326  public function rebuildWebSiteFiles()
1327  {
1328  global $conf;
1329 
1330  $error = 0;
1331 
1332  $object = $this;
1333  if (empty($object->ref)) {
1334  $this->error = 'Function rebuildWebSiteFiles called on object not loaded (object->ref is empty)';
1335  return -1;
1336  }
1337 
1338  $objectpagestatic = new WebsitePage($this->db);
1339 
1340  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."website_page WHERE fk_website = ".((int) $this->id);
1341 
1342  $resql = $this->db->query($sql);
1343  if (!$resql) {
1344  $this->error = $this->db->lasterror();
1345  return -1;
1346  }
1347 
1348  $num = $this->db->num_rows($resql);
1349 
1350  // Loop on each container/page
1351  $i = 0;
1352  while ($i < $num) {
1353  $obj = $this->db->fetch_object($resql);
1354 
1355  $newid = $obj->rowid;
1356 
1357  $objectpagestatic->fetch($newid);
1358 
1359  $aliasesarray = explode(',', $objectpagestatic->aliasalt);
1360 
1361  $filetpl = $conf->website->dir_output.'/'.$object->ref.'/page'.$newid.'.tpl.php';
1362  $result = dolSavePageContent($filetpl, $object, $objectpagestatic);
1363  if (!$result) {
1364  $this->errors[] = 'Failed to write file '.basename($filetpl);
1365  $error++;
1366  }
1367 
1368  // Add main alias to list of alternative aliases
1369  if (!empty($objectpagestatic->pageurl) && !in_array($objectpagestatic->pageurl, $aliasesarray)) {
1370  $aliasesarray[] = $objectpagestatic->pageurl;
1371  }
1372 
1373  // Regenerate also all aliases pages (pages with a natural name) by calling dolSavePageAlias()
1374  if (is_array($aliasesarray)) {
1375  foreach ($aliasesarray as $aliasshortcuttocreate) {
1376  if (trim($aliasshortcuttocreate)) {
1377  $filealias = $conf->website->dir_output.'/'.$object->ref.'/'.trim($aliasshortcuttocreate).'.php';
1378  $result = dolSavePageAlias($filealias, $object, $objectpagestatic); // This includes also a copy into sublanguage directories.
1379  if (!$result) {
1380  $this->errors[] = 'Failed to write file '.basename($filealias);
1381  $error++;
1382  }
1383  }
1384  }
1385  }
1386 
1387  $i++;
1388  }
1389 
1390  if (!$error) {
1391  // Save index.php and wrapper.php
1392  $pathofwebsite = $conf->website->dir_output.'/'.$object->ref;
1393  $fileindex = $pathofwebsite.'/index.php';
1394  $filetpl = '';
1395  if ($object->fk_default_home > 0) {
1396  $filetpl = $pathofwebsite.'/page'.$object->fk_default_home.'.tpl.php';
1397  }
1398  $filewrapper = $pathofwebsite.'/wrapper.php';
1399  dolSaveIndexPage($pathofwebsite, $fileindex, $filetpl, $filewrapper, $object); // This includes also a version of index.php into sublanguage directories
1400  }
1401 
1402  if ($error) {
1403  return -1;
1404  } else {
1405  return $num;
1406  }
1407  }
1408 
1414  public function isMultiLang()
1415  {
1416  return (empty($this->otherlang) ? false : true);
1417  }
1418 
1428  public function componentSelectLang($languagecodes, $weblangs, $morecss = '', $htmlname = '')
1429  {
1430  global $websitepagefile, $website;
1431 
1432  if (!is_object($weblangs)) {
1433  return 'ERROR componentSelectLang called with parameter $weblangs not defined';
1434  }
1435 
1436  $arrayofspecialmainlanguages = array(
1437  'en'=>'en_US',
1438  'sq'=>'sq_AL',
1439  'ar'=>'ar_SA',
1440  'eu'=>'eu_ES',
1441  'bn'=>'bn_DB',
1442  'bs'=>'bs_BA',
1443  'ca'=>'ca_ES',
1444  'zh'=>'zh_CN',
1445  'cs'=>'cs_CZ',
1446  'da'=>'da_DK',
1447  'et'=>'et_EE',
1448  'ka'=>'ka_GE',
1449  'el'=>'el_GR',
1450  'he'=>'he_IL',
1451  'kn'=>'kn_IN',
1452  'km'=>'km_KH',
1453  'ko'=>'ko_KR',
1454  'lo'=>'lo_LA',
1455  'nb'=>'nb_NO',
1456  'fa'=>'fa_IR',
1457  'sr'=>'sr_RS',
1458  'sl'=>'sl_SI',
1459  'uk'=>'uk_UA',
1460  'vi'=>'vi_VN'
1461  );
1462 
1463  // Load tmppage if we have $websitepagefile defined
1464  $tmppage = new WebsitePage($this->db);
1465 
1466  $pageid = 0;
1467  if (!empty($websitepagefile)) {
1468  $websitepagefileshort = basename($websitepagefile);
1469  if ($websitepagefileshort == 'index.php') {
1470  $pageid = $website->fk_default_home;
1471  } else {
1472  $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), $websitepagefileshort);
1473  }
1474  if ($pageid > 0) {
1475  $tmppage->fetch($pageid);
1476  }
1477  }
1478 
1479  // Fill $languagecodes array with existing translation, nothing if none
1480  if (!is_array($languagecodes) && $pageid > 0) {
1481  $languagecodes = array();
1482 
1483  $sql = "SELECT wp.rowid, wp.lang, wp.pageurl, wp.fk_page";
1484  $sql .= " FROM ".MAIN_DB_PREFIX."website_page as wp";
1485  $sql .= " WHERE wp.fk_website = ".((int) $website->id);
1486  $sql .= " AND (wp.fk_page = ".((int) $pageid)." OR wp.rowid = ".((int) $pageid);
1487  if ($tmppage->fk_page > 0) {
1488  $sql .= " OR wp.fk_page = ".((int) $tmppage->fk_page)." OR wp.rowid = ".((int) $tmppage->fk_page);
1489  }
1490  $sql .= ")";
1491 
1492  $resql = $this->db->query($sql);
1493  if ($resql) {
1494  while ($obj = $this->db->fetch_object($resql)) {
1495  $newlang = $obj->lang;
1496  if ($obj->rowid == $pageid) {
1497  $newlang = $obj->lang;
1498  }
1499  if (!in_array($newlang, $languagecodes)) {
1500  $languagecodes[] = $newlang;
1501  }
1502  }
1503  }
1504  }
1505  // Now $languagecodes is always an array. Example array('en', 'fr', 'es');
1506 
1507  $languagecodeselected = substr($weblangs->defaultlang, 0, 2); // Because we must init with a value, but real value is the lang of main parent container
1508  if (!empty($websitepagefile)) {
1509  $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), basename($websitepagefile));
1510  if ($pageid > 0) {
1511  $pagelang = substr($tmppage->lang, 0, 2);
1512  $languagecodeselected = substr($pagelang, 0, 2);
1513  if (!in_array($pagelang, $languagecodes)) {
1514  $languagecodes[] = $pagelang; // We add language code of page into combo list
1515  }
1516  }
1517  }
1518 
1519  $weblangs->load('languages');
1520  //var_dump($weblangs->defaultlang);
1521 
1522  $url = $_SERVER["REQUEST_URI"];
1523  $url = preg_replace('/(\?|&)l=([a-zA-Z_]*)/', '', $url); // We remove param l from url
1524  //$url = preg_replace('/(\?|&)lang=([a-zA-Z_]*)/', '', $url); // We remove param lang from url
1525  $url .= (preg_match('/\?/', $url) ? '&' : '?').'l=';
1526  if (!preg_match('/^\//', $url)) {
1527  $url = '/'.$url;
1528  }
1529 
1530  $HEIGHTOPTION = 40;
1531  $MAXHEIGHT = 4 * $HEIGHTOPTION;
1532  $nboflanguage = count($languagecodes);
1533 
1534  $out = '<!-- componentSelectLang'.$htmlname.' -->'."\n";
1535 
1536  $out .= '<style>';
1537  $out .= '.componentSelectLang'.$htmlname.':hover { height: '.min($MAXHEIGHT, ($HEIGHTOPTION * $nboflanguage)).'px; overflow-x: hidden; overflow-y: '.((($HEIGHTOPTION * $nboflanguage) > $MAXHEIGHT) ? ' scroll' : 'hidden').'; }'."\n";
1538  $out .= '.componentSelectLang'.$htmlname.' li { line-height: '.$HEIGHTOPTION.'px; }'."\n";
1539  $out .= '.componentSelectLang'.$htmlname.' {
1540  display: inline-block;
1541  padding: 0;
1542  height: '.$HEIGHTOPTION.'px;
1543  overflow: hidden;
1544  transition: all .3s ease;
1545  margin: 0 0 0 0;
1546  vertical-align: top;
1547  }
1548  .componentSelectLang'.$htmlname.':hover, .componentSelectLang'.$htmlname.':hover a { background-color: #fff; color: #000 !important; }
1549  ul.componentSelectLang'.$htmlname.' { width: 150px; }
1550  ul.componentSelectLang'.$htmlname.':hover .fa { visibility: hidden; }
1551  .componentSelectLang'.$htmlname.' a { text-decoration: none; width: 100%; }
1552  .componentSelectLang'.$htmlname.' li { display: block; padding: 0px 15px; margin-left: 0; margin-right: 0; }
1553  .componentSelectLang'.$htmlname.' li:hover { background-color: #EEE; }
1554  ';
1555  $out .= '</style>';
1556  $out .= '<ul class="componentSelectLang'.$htmlname.($morecss ? ' '.$morecss : '').'">';
1557 
1558  if ($languagecodeselected) {
1559  // Convert $languagecodeselected into a long language code
1560  if (strlen($languagecodeselected) == 2) {
1561  $languagecodeselected = (empty($arrayofspecialmainlanguages[$languagecodeselected]) ? $languagecodeselected.'_'.strtoupper($languagecodeselected) : $arrayofspecialmainlanguages[$languagecodeselected]);
1562  }
1563 
1564  $countrycode = strtolower(substr($languagecodeselected, -2));
1565  $label = $weblangs->trans("Language_".$languagecodeselected);
1566  if ($countrycode == 'us') {
1567  $label = preg_replace('/\s*\(.*\)/', '', $label);
1568  }
1569  $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>';
1570  $out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
1571  $out .= '</a></li>';
1572  }
1573  $i = 0;
1574  if (is_array($languagecodes)) {
1575  foreach ($languagecodes as $languagecode) {
1576  // Convert $languagecode into a long language code
1577  if (strlen($languagecode) == 2) {
1578  $languagecode = (empty($arrayofspecialmainlanguages[$languagecode]) ? $languagecode.'_'.strtoupper($languagecode) : $arrayofspecialmainlanguages[$languagecode]);
1579  }
1580 
1581  if ($languagecode == $languagecodeselected) {
1582  continue; // Already output
1583  }
1584 
1585  $countrycode = strtolower(substr($languagecode, -2));
1586  $label = $weblangs->trans("Language_".$languagecode);
1587  if ($countrycode == 'us') {
1588  $label = preg_replace('/\s*\(.*\)/', '', $label);
1589  }
1590  $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>';
1591  if (empty($i) && empty($languagecodeselected)) {
1592  $out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
1593  }
1594  $out .= '</a></li>';
1595  $i++;
1596  }
1597  }
1598  $out .= '</ul>';
1599 
1600  return $out;
1601  }
1602 }
Website\importWebSite
importWebSite($pathtofile)
Open a zip with all data of web site and load it into database.
Definition: website.class.php:1167
CommonObject\deleteCommon
deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
Delete object in database.
Definition: commonobject.class.php:9605
dol_sanitizePathName
dol_sanitizePathName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a path name.
Definition: functions.lib.php:1349
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:139
WebsitePage
Class Websitepage.
Definition: websitepage.class.php:36
Website\exportWebSite
exportWebSite()
Generate a zip with all data of web site.
Definition: website.class.php:934
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1323
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)
Return the label of a given status.
Definition: website.class.php:879
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:1485
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:9055
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:828
Website\isMultiLang
isMultiLang()
Return if web site is a multilanguage web site.
Definition: website.class.php:1414
dol_uncompress
dol_uncompress($inputfile, $outputdir)
Uncompress a file.
Definition: files.lib.php:2278
dolReplaceInFile
dolReplaceInFile($srcfile, $arrayreplacement, $destfile='', $newmask=0, $indexdatabase=0, $arrayreplacementisregex=0)
Make replacement of strings into a file.
Definition: files.lib.php:629
Website\componentSelectLang
componentSelectLang($languagecodes, $weblangs, $morecss='', $htmlname='')
Component to select language inside a container (Full CSS Only)
Definition: website.class.php:1428
CommonObject
Parent class of all other business classes (invoices, contracts, proposals, orders,...
Definition: commonobject.class.php:45
dolSaveMasterFile
dolSaveMasterFile($filemaster)
Save content of a page on disk.
Definition: website2.lib.php:32
dol_copy
dol_copy($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=0)
Copy a file to another file.
Definition: files.lib.php:717
dol_is_file
dol_is_file($pathoffile)
Return if path is a file.
Definition: files.lib.php:483
dolSaveIndexPage
dolSaveIndexPage($pathofwebsite, $fileindex, $filetpl, $filewrapper, $object=null)
Save content of the index.php and/or the wrapper.php page.
Definition: website2.lib.php:288
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:2675
dolChmod
dolChmod($filepath, $newmask='')
Change mod of a file.
Definition: functions.lib.php:7007
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:1334
Website\update
update(User $user, $notrigger=false)
Update object into database.
Definition: website.class.php:490
Website\rebuildWebSiteFiles
rebuildWebSiteFiles()
Rebuild all files of all the pages/containers of a website.
Definition: website.class.php:1326
Website\create
create(User $user, $notrigger=false)
Create object into database.
Definition: website.class.php:165
position
rtl background position
Definition: get_menudiv.php:132
Website\initAsSpecimen
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
Definition: website.class.php:908
Website\fetchLines
fetchLines()
Load object lines in memory from the database.
Definition: website.class.php:386
Website\createFromClone
createFromClone($user, $fromid, $newref, $newlang='')
Load a website its id and create a new one in database.
Definition: website.class.php:658
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1741
dolCopyDir
dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement=null, $excludesubdir=0, $excludefileext=null)
Copy a dir to another dir.
Definition: files.lib.php:845
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
Definition: functions.lib.php:8673
Website\fetch
fetch($id, $ref=null)
Load object in memory from the database.
Definition: website.class.php:310
$sql
if(isModEnabled('facture') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&empty($conf->global->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') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
dol_strlen
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Definition: functions.lib.php:3997
run_sql
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:169
ref
$object ref
Definition: info.php:78
Website
Class Website.
Definition: website.class.php:37
User
Class to manage Dolibarr users.
Definition: user.class.php:47
dolSavePageAlias
dolSavePageAlias($filealias, $object, $objectpage)
Save an alias page on disk (A page that include the reference page).
Definition: website2.lib.php:63
Website\getLibStatut
getLibStatut($mode=0)
Return the label of the status.
Definition: website.class.php:866
dolGetStatus
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
Definition: functions.lib.php:10967
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:408
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:3056
dol_mkdir
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
Definition: functions.lib.php:6936
Website\__construct
__construct(DoliDB $db)
Constructor.
Definition: website.class.php:151
dol_move
dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=1)
Move a file into another name.
Definition: files.lib.php:947
float
div float
Buy price without taxes.
Definition: style.css.php:921