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