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