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