Passed
Branch develop (8190a6)
by
unknown
25:05
created

Website::isMultiLang()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
/* Copyright (C) 2007-2018  Laurent Destailleur <[email protected]>
3
 * Copyright (C) 2014       Juanjo Menent       <[email protected]>
4
 * Copyright (C) 2015       Florian Henry       <[email protected]>
5
 * Copyright (C) 2015       Raphaël Doursenaud  <[email protected]>
6
 * Copyright (C) 2018       Frédéric France         <[email protected]>
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
22
/**
23
 * \file    website/website.class.php
24
 * \ingroup website
25
 * \brief   File for the CRUD class of website (Create/Read/Update/Delete)
26
 */
27
28
// Put here all includes required by your class file
29
require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
30
//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
31
//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
32
33
/**
34
 * Class Website
35
 */
36
class Website extends CommonObject
37
{
38
	/**
39
	 * @var string Id to identify managed objects
40
	 */
41
	public $element = 'website';
42
43
	/**
44
	 * @var string Name of table without prefix where object is stored
45
	 */
46
	public $table_element = 'website';
47
48
	/**
49
	 * @var array  Does website support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
50
	 */
51
	public $ismultientitymanaged = 1;
52
53
	/**
54
	 * @var string String with name of icon for website. Must be the part after the 'object_' into object_myobject.png
55
	 */
56
	public $picto = 'globe';
57
58
	/**
59
	 * @var int Entity
60
	 */
61
	public $entity;
62
63
	/**
64
	 * @var string Ref
65
	 */
66
	public $ref;
67
68
	/**
69
	 * @var string description
70
	 */
71
	public $description;
72
73
	/**
74
	 * @var int Status
75
	 */
76
	public $status;
77
78
	/**
79
	 * @var integer|string date_creation
80
	 */
81
	public $date_creation;
82
83
	/**
84
	 * @var integer|string date_modification
85
	 */
86
	public $date_modification;
87
88
	/**
89
	 * @var integer
90
	 */
91
	public $fk_default_home;
92
	public $fk_user_creat;
93
94
	/**
95
	 * @var string
96
	 */
97
	public $virtualhost;
98
99
	/**
100
	 * @var int
101
	 */
102
	public $use_manifest;
103
104
	/**
105
	 * List of containers
106
	 *
107
	 * @var array
108
	 */
109
	public $lines;
110
111
112
	const STATUS_DRAFT = 0;
113
	const STATUS_VALIDATED = 1;
114
115
116
	/**
117
	 * Constructor
118
	 *
119
	 * @param DoliDb $db Database handler
120
	 */
121
	public function __construct(DoliDB $db)
122
	{
123
		$this->db = $db;
124
		return 1;
125
	}
126
127
	/**
128
	 * Create object into database
129
	 *
130
	 * @param  User $user      User that creates
131
	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
132
	 *
133
	 * @return int <0 if KO, Id of created object if OK
134
	 */
135
	public function create(User $user, $notrigger = false)
136
	{
137
		global $conf;
138
139
		dol_syslog(__METHOD__, LOG_DEBUG);
140
141
		$error = 0;
142
		$now = dol_now();
143
144
		// Clean parameters
145
		if (isset($this->entity)) {
146
			 $this->entity = (int) $this->entity;
147
		}
148
		if (isset($this->ref)) {
149
			 $this->ref = trim($this->ref);
150
		}
151
		if (isset($this->description)) {
152
			 $this->description = trim($this->description);
153
		}
154
		if (isset($this->status)) {
155
			 $this->status = (int) $this->status;
156
		}
157
        if (empty($this->date_creation)) {
158
            $this->date_creation = $now;
159
        }
160
        if (empty($this->date_modification)) {
161
            $this->date_modification = $now;
162
        }
163
164
        // Check parameters
165
        if (empty($this->entity)) {
166
            $this->entity = $conf->entity;
167
        }
168
169
		// Insert request
170
		$sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.'(';
171
		$sql .= 'entity,';
172
		$sql .= 'ref,';
173
		$sql .= 'description,';
174
		$sql .= 'status,';
175
		$sql .= 'fk_default_home,';
176
		$sql .= 'virtualhost,';
177
		$sql .= 'fk_user_creat,';
178
		$sql .= 'date_creation,';
179
		$sql .= 'tms';
180
		$sql .= ') VALUES (';
181
		$sql .= ' '.((empty($this->entity) && $this->entity != '0') ? 'NULL' : $this->entity).',';
182
		$sql .= ' '.(!isset($this->ref) ? 'NULL' : "'".$this->db->escape($this->ref)."'").',';
183
		$sql .= ' '.(!isset($this->description) ? 'NULL' : "'".$this->db->escape($this->description)."'").',';
184
		$sql .= ' '.(!isset($this->status) ? '1' : $this->status).',';
185
		$sql .= ' '.(!isset($this->fk_default_home) ? 'NULL' : $this->fk_default_home).',';
186
		$sql .= ' '.(!isset($this->virtualhost) ? 'NULL' : "'".$this->db->escape($this->virtualhost)."'").",";
187
		$sql .= ' '.(!isset($this->fk_user_creat) ? $user->id : $this->fk_user_creat).',';
188
		$sql .= ' '.(!isset($this->date_creation) || dol_strlen($this->date_creation) == 0 ? 'NULL' : "'".$this->db->idate($this->date_creation)."'").",";
189
		$sql .= ' '.(!isset($this->date_modification) || dol_strlen($this->date_modification) == 0 ? 'NULL' : "'".$this->db->idate($this->date_modification)."'");
190
		$sql .= ')';
191
192
		$this->db->begin();
193
194
		$resql = $this->db->query($sql);
195
		if (!$resql) {
196
			$error++;
197
			$this->errors[] = 'Error '.$this->db->lasterror();
198
			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
199
		}
200
201
		if (!$error) {
202
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
203
204
            // Uncomment this and change MYOBJECT to your own tag if you
205
            // want this action to call a trigger.
206
            // if (!$notrigger) {
207
208
            //     // Call triggers
209
            //     $result = $this->call_trigger('MYOBJECT_CREATE',$user);
210
            //     if ($result < 0) $error++;
211
            //     // End call triggers
212
            // }
213
        }
214
215
		// Commit or rollback
216
		if ($error) {
217
			$this->db->rollback();
218
219
			return -1 * $error;
220
		} else {
221
			$this->db->commit();
222
223
			return $this->id;
224
		}
225
	}
226
227
	/**
228
	 * Load object in memory from the database
229
	 *
230
	 * @param 	int    $id  	Id object
231
	 * @param 	string $ref 	Ref
232
	 * @return 	int 			<0 if KO, 0 if not found, >0 if OK
233
	 */
234
	public function fetch($id, $ref = null)
235
	{
236
		dol_syslog(__METHOD__, LOG_DEBUG);
237
238
		$sql = 'SELECT';
239
		$sql .= ' t.rowid,';
240
		$sql .= " t.entity,";
241
		$sql .= " t.ref,";
242
		$sql .= " t.description,";
243
		$sql .= " t.status,";
244
		$sql .= " t.fk_default_home,";
245
		$sql .= " t.use_manifest,";
246
		$sql .= " t.virtualhost,";
247
		$sql .= " t.fk_user_creat,";
248
		$sql .= " t.fk_user_modif,";
249
		$sql .= " t.date_creation,";
250
		$sql .= " t.tms as date_modification";
251
		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
252
		$sql .= ' WHERE t.entity IN ('.getEntity('website').')';
253
		if (!empty($ref)) {
254
			$sql .= " AND t.ref = '".$this->db->escape($ref)."'";
255
		} else {
256
			$sql .= ' AND t.rowid = '.(int) $id;
257
		}
258
259
		$resql = $this->db->query($sql);
260
		if ($resql) {
261
			$numrows = $this->db->num_rows($resql);
262
			if ($numrows) {
263
				$obj = $this->db->fetch_object($resql);
264
265
				$this->id = $obj->rowid;
266
267
				$this->entity = $obj->entity;
268
				$this->ref = $obj->ref;
269
				$this->description = $obj->description;
270
				$this->status = $obj->status;
271
				$this->fk_default_home = $obj->fk_default_home;
272
				$this->virtualhost = $obj->virtualhost;
273
				$this->use_manifest = $obj->use_manifest;
274
				$this->fk_user_creat = $obj->fk_user_creat;
275
				$this->fk_user_modif = $obj->fk_user_modif;
276
				$this->date_creation = $this->db->jdate($obj->date_creation);
277
				$this->date_modification = $this->db->jdate($obj->date_modification);
278
			}
279
			$this->db->free($resql);
280
281
			if ($numrows > 0) {
282
				// Lines
283
				$this->fetchLines();
284
			}
285
286
			if ($numrows > 0) {
287
				return 1;
288
			} else {
289
				return 0;
290
			}
291
		} else {
292
			$this->errors[] = 'Error '.$this->db->lasterror();
293
			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
294
295
			return -1;
296
		}
297
	}
298
299
	/**
300
	 * Load object lines in memory from the database
301
	 *
302
	 * @return int         <0 if KO, 0 if not found, >0 if OK
303
	 */
304
	public function fetchLines()
305
	{
306
		$this->lines = array();
307
308
		// Load lines with object MyObjectLine
309
310
		return count($this->lines) ? 1 : 0;
311
	}
312
313
314
	/**
315
	 * Load object in memory from the database
316
	 *
317
	 * @param string $sortorder Sort Order
318
	 * @param string $sortfield Sort field
319
	 * @param int    $limit     offset limit
320
	 * @param int    $offset    offset limit
321
	 * @param array  $filter    filter array
322
	 * @param string $filtermode filter mode (AND or OR)
323
	 *
324
	 * @return int <0 if KO, >0 if OK
325
	 */
326
	public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
327
	{
328
		dol_syslog(__METHOD__, LOG_DEBUG);
329
330
		$sql = 'SELECT';
331
		$sql .= ' t.rowid,';
332
		$sql .= " t.entity,";
333
		$sql .= " t.ref,";
334
		$sql .= " t.description,";
335
		$sql .= " t.status,";
336
		$sql .= " t.fk_default_home,";
337
		$sql .= " t.virtualhost,";
338
		$sql .= " t.fk_user_creat,";
339
		$sql .= " t.fk_user_modif,";
340
		$sql .= " t.date_creation,";
341
		$sql .= " t.tms as date_modification";
342
		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
343
		$sql .= ' WHERE t.entity IN ('.getEntity('website').')';
344
		// Manage filter
345
		$sqlwhere = array();
346
		if (count($filter) > 0) {
347
			foreach ($filter as $key => $value) {
348
				$sqlwhere [] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
349
			}
350
		}
351
		if (count($sqlwhere) > 0) {
352
			$sql .= ' AND '.implode(' '.$filtermode.' ', $sqlwhere);
353
		}
354
355
		if (!empty($sortfield)) {
356
			$sql .= $this->db->order($sortfield, $sortorder);
357
		}
358
		if (!empty($limit)) {
359
		    $sql .= ' '.$this->db->plimit($limit, $offset);
360
		}
361
		$this->records = array();
362
363
		$resql = $this->db->query($sql);
364
		if ($resql) {
365
			$num = $this->db->num_rows($resql);
366
367
			while ($obj = $this->db->fetch_object($resql)) {
368
				$line = new self($this->db);
369
370
				$line->id = $obj->rowid;
371
372
				$line->entity = $obj->entity;
373
				$line->ref = $obj->ref;
374
				$line->description = $obj->description;
375
				$line->status = $obj->status;
376
				$line->fk_default_home = $obj->fk_default_home;
377
				$line->virtualhost = $obj->virtualhost;
378
				$this->fk_user_creat = $obj->fk_user_creat;
379
				$this->fk_user_modif = $obj->fk_user_modif;
380
				$line->date_creation = $this->db->jdate($obj->date_creation);
381
				$line->date_modification = $this->db->jdate($obj->date_modification);
382
383
				$this->records[$line->id] = $line;
384
			}
385
			$this->db->free($resql);
386
387
			return $num;
388
		} else {
389
			$this->errors[] = 'Error '.$this->db->lasterror();
390
			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
391
392
			return -1;
393
		}
394
	}
395
396
	/**
397
	 * Update object into database
398
	 *
399
	 * @param  User $user      User that modifies
400
	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
401
	 *
402
	 * @return int <0 if KO, >0 if OK
403
	 */
404
	public function update(User $user, $notrigger = false)
405
	{
406
		$error = 0;
407
408
		dol_syslog(__METHOD__, LOG_DEBUG);
409
410
		// Clean parameters
411
412
		if (isset($this->entity)) {
413
			 $this->entity = (int) $this->entity;
414
		}
415
		if (isset($this->ref)) {
416
			 $this->ref = trim($this->ref);
417
		}
418
		if (isset($this->description)) {
419
			 $this->description = trim($this->description);
420
		}
421
		if (isset($this->status)) {
422
			 $this->status = (int) $this->status;
423
		}
424
425
		// Check parameters
426
		// Put here code to add a control on parameters values
427
428
		// Update request
429
		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
430
		$sql .= ' entity = '.(isset($this->entity) ? $this->entity : "null").',';
431
		$sql .= ' ref = '.(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").',';
432
		$sql .= ' description = '.(isset($this->description) ? "'".$this->db->escape($this->description)."'" : "null").',';
433
		$sql .= ' status = '.(isset($this->status) ? $this->status : "null").',';
434
		$sql .= ' fk_default_home = '.(($this->fk_default_home > 0) ? $this->fk_default_home : "null").',';
435
		$sql .= ' use_manifest = '.((int) $this->use_manifest).',';
436
		$sql .= ' virtualhost = '.(($this->virtualhost != '') ? "'".$this->db->escape($this->virtualhost)."'" : "null").',';
437
		$sql .= ' fk_user_modif = '.(!isset($this->fk_user_modif) ? $user->id : $this->fk_user_modif).',';
438
		$sql .= ' date_creation = '.(!isset($this->date_creation) || dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').',';
439
		$sql .= ' tms = '.(dol_strlen($this->date_modification) != 0 ? "'".$this->db->idate($this->date_modification)."'" : "'".$this->db->idate(dol_now())."'");
440
		$sql .= ' WHERE rowid='.$this->id;
441
442
		$this->db->begin();
443
444
		$resql = $this->db->query($sql);
445
		if (!$resql) {
446
			$error++;
447
			$this->errors[] = 'Error '.$this->db->lasterror();
448
			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
449
		}
450
451
		if (!$error && !$notrigger) {
452
			// Uncomment this and change MYOBJECT to your own tag if you
453
			// want this action calls a trigger.
454
455
			//// Call triggers
456
			//$result=$this->call_trigger('MYOBJECT_MODIFY',$user);
457
			//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
458
			//// End call triggers
459
		}
460
461
		// Commit or rollback
462
		if ($error) {
463
			$this->db->rollback();
464
465
			return -1 * $error;
466
		} else {
467
			$this->db->commit();
468
469
			return 1;
470
		}
471
	}
472
473
	/**
474
	 * Delete object in database
475
	 *
476
	 * @param User $user      User that deletes
477
	 * @param bool $notrigger false=launch triggers after, true=disable triggers
478
	 *
479
	 * @return int <0 if KO, >0 if OK
480
	 */
481
	public function delete(User $user, $notrigger = false)
482
	{
483
		dol_syslog(__METHOD__, LOG_DEBUG);
484
485
		$error = 0;
486
487
		$this->db->begin();
488
489
		if (!$error) {
490
			if (!$notrigger) {
491
				// Uncomment this and change MYOBJECT to your own tag if you
492
				// want this action calls a trigger.
493
494
				//// Call triggers
495
				//$result=$this->call_trigger('MYOBJECT_DELETE',$user);
496
				//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
497
				//// End call triggers
498
			}
499
		}
500
501
		if (!$error) {
502
			$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element;
503
			$sql .= ' WHERE rowid='.$this->id;
504
505
			$resql = $this->db->query($sql);
506
			if (!$resql) {
507
				$error++;
508
				$this->errors[] = 'Error '.$this->db->lasterror();
509
				dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
510
			}
511
		}
512
513
		if (!$error && !empty($this->ref))
514
		{
515
			$pathofwebsite = DOL_DATA_ROOT.'/website/'.$this->ref;
516
517
			dol_delete_dir_recursive($pathofwebsite);
518
		}
519
520
		// Commit or rollback
521
		if ($error) {
522
			$this->db->rollback();
523
524
			return -1 * $error;
525
		} else {
526
			$this->db->commit();
527
528
			return 1;
529
		}
530
	}
531
532
	/**
533
	 * Load an object from its id and create a new one in database.
534
	 * This copy website directories, regenerate all the pages + alias pages and recreate the medias link.
535
	 *
536
	 * @param	User	$user		User making the clone
537
	 * @param 	int 	$fromid 	Id of object to clone
538
	 * @param	string	$newref		New ref
539
	 * @param	string	$newlang	New language
540
	 * @return 	mixed 				New object created, <0 if KO
541
	 */
542
	public function createFromClone($user, $fromid, $newref, $newlang = '')
543
	{
544
        global $conf;
545
		global $dolibarr_main_data_root;
546
547
		$now = dol_now();
548
		$error = 0;
549
550
        dol_syslog(__METHOD__, LOG_DEBUG);
551
552
		$object = new self($this->db);
553
554
        // Check no site with ref exists
555
		if ($object->fetch(0, $newref) > 0)
556
		{
557
			$this->error = 'ErrorNewRefIsAlreadyUsed';
558
			return -1;
559
		}
560
561
		$this->db->begin();
562
563
		// Load source object
564
		$object->fetch($fromid);
565
566
		$oldidforhome = $object->fk_default_home;
567
		$oldref = $object->ref;
568
569
		$pathofwebsiteold = $dolibarr_main_data_root.'/website/'.$oldref;
570
		$pathofwebsitenew = $dolibarr_main_data_root.'/website/'.$newref;
571
		dol_delete_dir_recursive($pathofwebsitenew);
572
573
		$fileindex = $pathofwebsitenew.'/index.php';
574
575
		// Reset some properties
576
		unset($object->id);
577
		unset($object->fk_user_creat);
578
		unset($object->import_key);
579
580
		// Clear fields
581
		$object->ref = $newref;
582
		$object->fk_default_home = 0;
583
		$object->virtualhost = '';
584
		$object->date_creation = $now;
585
		$object->fk_user_creat = $user->id;
586
587
		// Create clone
588
		$object->context['createfromclone'] = 'createfromclone';
589
		$result = $object->create($user);
590
		if ($result < 0) {
591
			$error++;
592
			$this->errors = $object->errors;
593
			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
594
		}
595
596
		if (!$error)
597
		{
598
			dolCopyDir($pathofwebsiteold, $pathofwebsitenew, $conf->global->MAIN_UMASK, 0);
599
600
			// Check symlink to medias and restore it if ko
601
			$pathtomedias = DOL_DATA_ROOT.'/medias'; // Target
602
			$pathtomediasinwebsite = $pathofwebsitenew.'/medias'; // Source / Link name
603
			if (!is_link(dol_osencode($pathtomediasinwebsite)))
604
			{
605
				dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite);
606
				dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists
607
				$result = symlink($pathtomedias, $pathtomediasinwebsite);
608
			}
609
610
			// Copy images and js dir
611
			$pathofmediasjsold = DOL_DATA_ROOT.'/medias/js/'.$oldref;
612
			$pathofmediasjsnew = DOL_DATA_ROOT.'/medias/js/'.$newref;
613
			dolCopyDir($pathofmediasjsold, $pathofmediasjsnew, $conf->global->MAIN_UMASK, 0);
614
615
			$pathofmediasimageold = DOL_DATA_ROOT.'/medias/image/'.$oldref;
616
			$pathofmediasimagenew = DOL_DATA_ROOT.'/medias/image/'.$newref;
617
			dolCopyDir($pathofmediasimageold, $pathofmediasimagenew, $conf->global->MAIN_UMASK, 0);
618
619
			$newidforhome = 0;
620
621
			// Duplicate pages
622
			$objectpages = new WebsitePage($this->db);
623
			$listofpages = $objectpages->fetchAll($fromid);
624
			foreach ($listofpages as $pageid => $objectpageold)
0 ignored issues
show
Bug introduced by
The expression $listofpages of type integer is not traversable.
Loading history...
625
			{
626
				// Delete old file
627
				$filetplold = $pathofwebsitenew.'/page'.$pageid.'.tpl.php';
628
				dol_delete_file($filetplold);
629
630
				// Create new file
631
				$objectpagenew = $objectpageold->createFromClone($user, $pageid, $objectpageold->pageurl, '', 0, $object->id, 1);
632
633
				//print $pageid.' = '.$objectpageold->pageurl.' -> '.$objectpagenew->id.' = '.$objectpagenew->pageurl.'<br>';
634
				if (is_object($objectpagenew) && $objectpagenew->pageurl)
635
				{
636
		            $filealias = $pathofwebsitenew.'/'.$objectpagenew->pageurl.'.php';
637
					$filetplnew = $pathofwebsitenew.'/page'.$objectpagenew->id.'.tpl.php';
638
639
					// Save page alias
640
					$result = dolSavePageAlias($filealias, $object, $objectpagenew);
641
					if (!$result) setEventMessages('Failed to write file '.$filealias, null, 'errors');
642
643
					$result = dolSavePageContent($filetplnew, $object, $objectpagenew);
644
					if (!$result) setEventMessages('Failed to write file '.$filetplnew, null, 'errors');
645
646
					if ($pageid == $oldidforhome)
647
					{
648
						$newidforhome = $objectpagenew->id;
649
					}
650
				}
651
				else
652
				{
653
					setEventMessages($objectpageold->error, $objectpageold->errors, 'errors');
654
					$error++;
655
				}
656
			}
657
		}
658
659
		if (!$error)
660
		{
661
			// Restore id of home page
662
			$object->fk_default_home = $newidforhome;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $newidforhome does not seem to be defined for all execution paths leading up to this point.
Loading history...
663
		    $res = $object->update($user);
664
		    if (!$res > 0)
665
		    {
666
		        $error++;
667
		        setEventMessages($object->error, $object->errors, 'errors');
668
		    }
669
670
		    if (!$error)
671
		    {
672
		    	$filetpl = $pathofwebsitenew.'/page'.$newidforhome.'.tpl.php';
673
		    	$filewrapper = $pathofwebsitenew.'/wrapper.php';
674
675
		    	// Generate the index.php page to be the home page
676
		    	//-------------------------------------------------
677
		    	$result = dolSaveIndexPage($pathofwebsitenew, $fileindex, $filetpl, $filewrapper);
678
		    }
679
		}
680
681
		unset($object->context['createfromclone']);
682
683
		// End
684
		if (!$error) {
685
			$this->db->commit();
686
687
			return $object;
688
		} else {
689
			$this->db->rollback();
690
691
			return -1;
692
		}
693
	}
694
695
	/**
696
	 *  Return a link to the user card (with optionally the picto)
697
	 * 	Use this->id,this->lastname, this->firstname
698
	 *
699
	 *	@param	int		$withpicto			Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
700
	 *	@param	string	$option				On what the link point to
701
     *  @param	integer	$notooltip			1=Disable tooltip
702
     *  @param	int		$maxlen				Max length of visible user name
703
     *  @param  string  $morecss            Add more css on link
704
	 *	@return	string						String with URL
705
	 */
706
	public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $maxlen = 24, $morecss = '')
707
	{
708
		global $langs, $conf, $db;
709
        global $dolibarr_main_authentication, $dolibarr_main_demo;
710
        global $menumanager;
711
712
713
        $result = '';
714
        $companylink = '';
715
716
        $label = '<u>'.$langs->trans("WebSite").'</u>';
717
        $label .= '<br>';
718
        $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
719
720
        $linkstart = '<a href="'.DOL_URL_ROOT.'/website/card.php?id='.$this->id.'"';
721
        $linkstart .= ($notooltip ? '' : ' title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip'.($morecss ? ' '.$morecss : '').'"');
722
        $linkstart .= '>';
723
		$linkend = '</a>';
724
725
		$linkstart = $linkend = '';
726
727
        if ($withpicto)
728
        {
729
            $result .= ($linkstart.img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? '' : 'class="classfortooltip"')).$linkend);
730
            if ($withpicto != 2) $result .= ' ';
731
		}
732
		$result .= $linkstart.$this->ref.$linkend;
733
		return $result;
734
	}
735
736
	/**
737
	 *  Retourne le libelle du status d'un user (actif, inactif)
738
	 *
739
	 *  @param	int		$mode          0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
740
	 *  @return	string 			       Label of status
741
	 */
742
	public function getLibStatut($mode = 0)
743
	{
744
		return $this->LibStatut($this->status, $mode);
745
	}
746
747
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
748
	/**
749
	 *  Renvoi le libelle d'un status donne
750
	 *
751
	 *  @param	int		$status        	Id status
752
	 *  @param  int		$mode          	0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
753
	 *  @return string 			       	Label of status
754
	 */
755
	public function LibStatut($status, $mode = 0)
756
	{
757
        // phpcs:enable
758
		global $langs;
759
760
		if (empty($this->labelStatus) || empty($this->labelStatusShort))
761
		{
762
			global $langs;
763
			//$langs->load("mymodule");
764
			$this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Disabled');
765
			$this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Enabled');
766
			$this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Disabled');
767
			$this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Enabled');
768
		}
769
770
		$statusType = 'status5';
771
		if ($status == self::STATUS_VALIDATED) $statusType = 'status4';
772
773
		return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
774
	}
775
776
777
	/**
778
	 * Initialise object with example values
779
	 * Id must be 0 if object instance is a specimen
780
	 *
781
	 * @return void
782
	 */
783
	public function initAsSpecimen()
784
	{
785
	    global $user;
786
787
		$this->id = 0;
788
789
		$this->entity = 1;
790
		$this->ref = 'myspecimenwebsite';
791
		$this->description = 'A specimen website';
792
		$this->status = '';
793
		$this->fk_default_home = null;
794
		$this->virtualhost = 'http://myvirtualhost';
795
		$this->fk_user_creat = $user->id;
796
		$this->fk_user_modif = $user->id;
797
		$this->date_creation = dol_now();
798
		$this->tms = dol_now();
799
	}
800
801
802
	/**
803
	 * Generate a zip with all data of web site.
804
	 *
805
	 * @return  string						Path to file with zip or '' if error
806
	 */
807
	public function exportWebSite()
808
	{
809
		global $conf, $mysoc;
810
811
		$website = $this;
812
813
		if (empty($website->id) || empty($website->ref))
814
		{
815
			setEventMessages("Website id or ref is not defined", null, 'errors');
816
			return '';
817
		}
818
819
		dol_syslog("Create temp dir ".$conf->website->dir_temp);
820
		dol_mkdir($conf->website->dir_temp);
821
		if (!is_writable($conf->website->dir_temp))
822
		{
823
			setEventMessages("Temporary dir ".$conf->website->dir_temp." is not writable", null, 'errors');
824
			return '';
825
		}
826
827
		$destdir = $conf->website->dir_temp.'/'.$website->ref;
828
829
		dol_syslog("Clear temp dir ".$destdir);
830
		$count = 0; $countreallydeleted = 0;
831
		$counttodelete = dol_delete_dir_recursive($destdir, $count, 1, 0, $countreallydeleted);
832
		if ($counttodelete != $countreallydeleted)
833
		{
834
			setEventMessages("Failed to clean temp directory ".$destdir, null, 'errors');
835
			return '';
836
		}
837
838
		$arrayreplacementinfilename = array();
839
		$arrayreplacementincss = array();
840
		$arrayreplacementincss['file=image/'.$website->ref.'/'] = "file=image/__WEBSITE_KEY__/";
841
		$arrayreplacementincss['file=js/'.$website->ref.'/'] = "file=js/__WEBSITE_KEY__/";
842
		$arrayreplacementincss['medias/image/'.$website->ref.'/'] = "medias/image/__WEBSITE_KEY__/";
843
		$arrayreplacementincss['medias/js/'.$website->ref.'/'] = "medias/js/__WEBSITE_KEY__/";
844
		if ($mysoc->logo_small) {
845
		    $arrayreplacementincss['file=logos%2Fthumbs%2F'.$mysoc->logo_small] = "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__";
846
		}
847
		if ($mysoc->logo_mini) {
848
		    $arrayreplacementincss['file=logos%2Fthumbs%2F'.$mysoc->logo_mini] = "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__";
849
		}
850
		if ($mysoc->logo) {
851
		    $arrayreplacementincss['file=logos%2Fthumbs%2F'.$mysoc->logo] = "file=logos%2Fthumbs%2F__LOGO_KEY__";
852
		}
853
854
		$srcdir = $conf->website->dir_output.'/'.$website->ref;
855
		$destdir = $conf->website->dir_temp.'/'.$website->ref.'/containers';
856
857
		// Create containers dir
858
		dol_syslog("Create containers dir");
859
		dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/containers');
860
861
		// Copy files into medias
862
		dol_syslog("Copy content from ".$srcdir." into ".$destdir);
863
		dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacementinfilename);
864
865
		$srcdir = DOL_DATA_ROOT.'/medias/image/'.$website->ref;
866
		$destdir = $conf->website->dir_temp.'/'.$website->ref.'/medias/image/websitekey';
867
868
		dol_syslog("Copy content from ".$srcdir." into ".$destdir);
869
		dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacementinfilename);
870
871
		$srcdir = DOL_DATA_ROOT.'/medias/js/'.$website->ref;
872
		$destdir = $conf->website->dir_temp.'/'.$website->ref.'/medias/js/websitekey';
873
874
		// Copy containers files
875
		dol_syslog("Copy content from ".$srcdir." into ".$destdir);
876
		dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacementinfilename);
877
878
		$cssindestdir = $conf->website->dir_temp.'/'.$website->ref.'/containers/styles.css.php';
879
		dolReplaceInFile($cssindestdir, $arrayreplacementincss);
880
881
		$htmldeaderindestdir = $conf->website->dir_temp.'/'.$website->ref.'/containers/htmlheader.html';
882
		dolReplaceInFile($htmldeaderindestdir, $arrayreplacementincss);
883
884
		// Build sql file
885
		$filesql = $conf->website->dir_temp.'/'.$website->ref.'/website_pages.sql';
886
		$fp = fopen($filesql, "w");
887
		if (empty($fp))
888
		{
889
			setEventMessages("Failed to create file ".$filesql, null, 'errors');
890
			return '';
891
		}
892
893
		$objectpages = new WebsitePage($this->db);
894
		$listofpages = $objectpages->fetchAll($website->id);
895
896
		// Assign ->newid and ->newfk_page
897
		$i = 1;
898
		foreach ($listofpages as $pageid => $objectpageold)
0 ignored issues
show
Bug introduced by
The expression $listofpages of type integer is not traversable.
Loading history...
899
		{
900
			$objectpageold->newid = $i;
901
			$i++;
902
		}
903
		$i = 1;
904
		foreach ($listofpages as $pageid => $objectpageold)
0 ignored issues
show
Bug introduced by
The expression $listofpages of type integer is not traversable.
Loading history...
905
		{
906
			// Search newid
907
			$newfk_page = 0;
908
			foreach ($listofpages as $pageid2 => $objectpageold2)
0 ignored issues
show
Bug introduced by
The expression $listofpages of type integer is not traversable.
Loading history...
909
			{
910
				if ($pageid2 == $objectpageold->fk_page)
911
				{
912
					$newfk_page = $objectpageold2->newid;
913
					break;
914
				}
915
			}
916
			$objectpageold->newfk_page = $newfk_page;
917
			$i++;
918
		}
919
		foreach ($listofpages as $pageid => $objectpageold)
0 ignored issues
show
Bug introduced by
The expression $listofpages of type integer is not traversable.
Loading history...
920
		{
921
			$allaliases = $objectpageold->pageurl;
922
			$allaliases .= ($objectpageold->aliasalt ? ','.$objectpageold->aliasalt : '');
923
924
			$line = '-- Page ID '.$objectpageold->id.' -> '.$objectpageold->newid.'__+MAX_llx_website_page__ - Aliases '.$allaliases.' --;'; // newid start at 1, 2...
925
			$line .= "\n";
926
			fputs($fp, $line);
927
928
			// Warning: We must keep llx_ here. It is a generic SQL.
929
			$line = 'INSERT INTO llx_website_page(rowid, fk_page, fk_website, pageurl, aliasalt, title, description, image, keywords, status, date_creation, tms, lang, import_key, grabbed_from, type_container, htmlheader, content)';
930
931
			$line .= " VALUES(";
932
			$line .= $objectpageold->newid."__+MAX_llx_website_page__, ";
933
			$line .= ($objectpageold->newfk_page ? $this->db->escape($objectpageold->newfk_page)."__+MAX_llx_website_page__" : "null").", ";
934
			$line .= "__WEBSITE_ID__, ";
935
			$line .= "'".$this->db->escape($objectpageold->pageurl)."', ";
936
			$line .= "'".$this->db->escape($objectpageold->aliasalt)."', ";
937
			$line .= "'".$this->db->escape($objectpageold->title)."', ";
938
			$line .= "'".$this->db->escape($objectpageold->description)."', ";
939
			$line .= "'".$this->db->escape($objectpageold->image)."', ";
940
			$line .= "'".$this->db->escape($objectpageold->keywords)."', ";
941
			$line .= "'".$this->db->escape($objectpageold->status)."', ";
942
			$line .= "'".$this->db->idate($objectpageold->date_creation)."', ";
943
			$line .= "'".$this->db->idate($objectpageold->date_modification)."', ";
944
			$line .= "'".$this->db->escape($objectpageold->lang)."', ";
945
			$line .= ($objectpageold->import_key ? "'".$this->db->escape($objectpageold->import_key)."'" : "null").", ";
946
			$line .= "'".$this->db->escape($objectpageold->grabbed_from)."', ";
947
			$line .= "'".$this->db->escape($objectpageold->type_container)."', ";
948
949
			$stringtoexport = $objectpageold->htmlheader;
950
			$stringtoexport = str_replace(array("\r\n", "\r", "\n"), "__N__", $stringtoexport);
951
			$stringtoexport = str_replace('file=image/'.$website->ref.'/', "file=image/__WEBSITE_KEY__/", $stringtoexport);
952
			$stringtoexport = str_replace('file=js/'.$website->ref.'/', "file=js/__WEBSITE_KEY__/", $stringtoexport);
953
			$stringtoexport = str_replace('medias/image/'.$website->ref.'/', "medias/image/__WEBSITE_KEY__/", $stringtoexport);
954
			$stringtoexport = str_replace('medias/js/'.$website->ref.'/', "medias/js/__WEBSITE_KEY__/", $stringtoexport);
955
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_small, "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__", $stringtoexport);
956
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_mini, "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__", $stringtoexport);
957
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo, "file=logos%2Fthumbs%2F__LOGO_KEY__", $stringtoexport);
958
			$line .= "'".$this->db->escape(str_replace(array("\r\n", "\r", "\n"), "__N__", $stringtoexport))."', "; // Replace \r \n to have record on 1 line
959
960
			$stringtoexport = $objectpageold->content;
961
			$stringtoexport = str_replace(array("\r\n", "\r", "\n"), "__N__", $stringtoexport);
962
			$stringtoexport = str_replace('file=image/'.$website->ref.'/', "file=image/__WEBSITE_KEY__/", $stringtoexport);
963
			$stringtoexport = str_replace('file=js/'.$website->ref.'/', "file=js/__WEBSITE_KEY__/", $stringtoexport);
964
			$stringtoexport = str_replace('medias/image/'.$website->ref.'/', "medias/image/__WEBSITE_KEY__/", $stringtoexport);
965
			$stringtoexport = str_replace('medias/js/'.$website->ref.'/', "medias/js/__WEBSITE_KEY__/", $stringtoexport);
966
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_small, "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__", $stringtoexport);
967
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_mini, "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__", $stringtoexport);
968
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo, "file=logos%2Fthumbs%2F__LOGO_KEY__", $stringtoexport);
969
970
			// When we have a link src="image/websiteref/file.png" into html content
971
			$stringtoexport = str_replace('="image/'.$website->ref.'/', '="image/__WEBSITE_KEY__/', $stringtoexport);
972
973
			$line .= "'".$this->db->escape($stringtoexport)."'"; // Replace \r \n to have record on 1 line
974
			$line .= ");";
975
			$line .= "\n";
976
			fputs($fp, $line);
977
978
			// Add line to update home page id during import
979
			//var_dump($this->fk_default_home.' - '.$objectpageold->id.' - '.$objectpageold->newid);exit;
980
			if ($this->fk_default_home > 0 && ($objectpageold->id == $this->fk_default_home) && ($objectpageold->newid > 0))	// This is the record with home page
981
			{
982
			    // Warning: We must keep llx_ here. It is a generic SQL.
983
			    $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__;";
984
				$line .= "\n";
985
				fputs($fp, $line);
986
			}
987
		}
988
989
		fclose($fp);
990
		if (!empty($conf->global->MAIN_UMASK))
991
			@chmod($filesql, octdec($conf->global->MAIN_UMASK));
992
993
		// Build zip file
994
		$filedir  = $conf->website->dir_temp.'/'.$website->ref.'/.';
995
		$fileglob = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-*.zip';
996
		$filename = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-'.dol_print_date(dol_now(), 'dayhourlog').'.zip';
997
998
		dol_delete_file($fileglob, 0);
999
		$result = dol_compress_file($filedir, $filename, 'zip');
1000
1001
		if ($result > 0)
1002
		{
1003
			return $filename;
1004
		}
1005
		else
1006
		{
1007
			global $errormsg;
1008
			$this->error = $errormsg;
1009
			return '';
1010
		}
1011
	}
1012
1013
1014
	/**
1015
	 * Open a zip with all data of web site and load it into database.
1016
	 *
1017
	 * @param 	string		$pathtofile		Path of zip file
1018
	 * @return  int							<0 if KO, Id of new website if OK
1019
	 */
1020
	public function importWebSite($pathtofile)
1021
	{
1022
		global $conf, $mysoc;
1023
1024
		$error = 0;
1025
1026
		$object = $this;
1027
		if (empty($object->ref))
1028
		{
1029
			$this->error = 'Function importWebSite called on object not loaded (object->ref is empty)';
1030
			return -1;
1031
		}
1032
1033
		dol_delete_dir_recursive($conf->website->dir_temp.'/'.$object->ref);
1034
		dol_mkdir($conf->website->dir_temp.'/'.$object->ref);
1035
1036
		$filename = basename($pathtofile);
1037
		if (!preg_match('/^website_(.*)-(.*)$/', $filename, $reg))
1038
		{
1039
			$this->errors[] = 'Bad format for filename '.$filename.'. Must be website_XXX-VERSION.';
1040
			return -1;
1041
		}
1042
1043
		$result = dol_uncompress($pathtofile, $conf->website->dir_temp.'/'.$object->ref);
1044
1045
		if (!empty($result['error']))
1046
		{
1047
			$this->errors[] = 'Failed to unzip file '.$pathtofile.'.';
1048
			return -1;
1049
		}
1050
1051
		$arrayreplacement = array();
1052
		$arrayreplacement['__WEBSITE_ID__'] = $object->id;
1053
		$arrayreplacement['__WEBSITE_KEY__'] = $object->ref;
1054
		$arrayreplacement['__N__'] = $this->db->escape("\n"); // Restore \n
1055
		$arrayreplacement['__LOGO_SMALL_KEY__'] = $this->db->escape($mysoc->logo_small);
1056
		$arrayreplacement['__LOGO_MINI_KEY__'] = $this->db->escape($mysoc->logo_mini);
1057
		$arrayreplacement['__LOGO_KEY__'] = $this->db->escape($mysoc->logo);
1058
1059
		// Copy containers
1060
		dolCopyDir($conf->website->dir_temp.'/'.$object->ref.'/containers', $conf->website->dir_output.'/'.$object->ref, 0, 1); // Overwrite if exists
1061
1062
		// Make replacement into css and htmlheader file
1063
		$cssindestdir = $conf->website->dir_output.'/'.$object->ref.'/styles.css.php';
1064
		$result = dolReplaceInFile($cssindestdir, $arrayreplacement);
1065
1066
		$htmldeaderindestdir = $conf->website->dir_output.'/'.$object->ref.'/htmlheader.html';
1067
		$result = dolReplaceInFile($htmldeaderindestdir, $arrayreplacement);
1068
1069
		// Now generate the master.inc.php page
1070
		$filemaster = $conf->website->dir_output.'/'.$object->ref.'/master.inc.php';
1071
		$result = dolSaveMasterFile($filemaster);
1072
		if (!$result)
1073
		{
1074
			$this->errors[] = 'Failed to write file '.$filemaster;
1075
			$error++;
1076
		}
1077
1078
		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
1079
		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
1080
1081
		$sqlfile = $conf->website->dir_temp.'/'.$object->ref.'/website_pages.sql';
1082
1083
		$result = dolReplaceInFile($sqlfile, $arrayreplacement);
1084
1085
		$this->db->begin();
1086
1087
		// Search the $maxrowid because we need it later
1088
		$sqlgetrowid = 'SELECT MAX(rowid) as max from '.MAIN_DB_PREFIX.'website_page';
1089
		$resql = $this->db->query($sqlgetrowid);
1090
		if ($resql)
1091
		{
1092
			$obj = $this->db->fetch_object($resql);
1093
			$maxrowid = $obj->max;
1094
		}
1095
1096
		// Load sql record
1097
		$runsql = run_sql($sqlfile, 1, '', 0, '', 'none', 0, 1); // The maxrowid of table is searched into this function two
1098
		if ($runsql <= 0)
1099
		{
1100
			$this->errors[] = 'Failed to load sql file '.$sqlfile;
1101
			$error++;
1102
		}
1103
1104
		$objectpagestatic = new WebsitePage($this->db);
1105
1106
		// Make replacement of IDs
1107
		$fp = fopen($sqlfile, "r");
1108
		if ($fp)
1109
		{
1110
			while (!feof($fp))
1111
			{
1112
				$reg = array();
1113
1114
				// Warning fgets with second parameter that is null or 0 hang.
1115
				$buf = fgets($fp, 65000);
1116
				if (preg_match('/^-- Page ID (\d+)\s[^\s]+\s(\d+).*Aliases\s(.*)\s--;/i', $buf, $reg))
1117
				{
1118
					$oldid = $reg[1];
1119
					$newid = ($reg[2] + $maxrowid);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $maxrowid does not seem to be defined for all execution paths leading up to this point.
Loading history...
1120
					$aliasesarray = explode(',', $reg[3]);
1121
1122
					$objectpagestatic->fetch($newid);
1123
1124
					dol_syslog("Found ID ".$oldid." to replace with ID ".$newid." and shortcut aliases to create: ".$reg[3]);
1125
1126
					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);
1127
1128
					// The move is not enough, so we regenerate page
1129
					$filetpl = $conf->website->dir_output.'/'.$object->ref.'/page'.$newid.'.tpl.php';
1130
					dolSavePageContent($filetpl, $object, $objectpagestatic);
1131
1132
					// Regenerate alternative aliases pages
1133
					if (is_array($aliasesarray))
1134
					{
1135
						foreach ($aliasesarray as $aliasshortcuttocreate)
1136
						{
1137
							if (trim($aliasshortcuttocreate))
1138
							{
1139
								$filealias = $conf->website->dir_output.'/'.$object->ref.'/'.trim($aliasshortcuttocreate).'.php';
1140
								dolSavePageAlias($filealias, $object, $objectpagestatic);
1141
							}
1142
						}
1143
					}
1144
				}
1145
			}
1146
		}
1147
1148
		// Regenerate index page to point to new index page
1149
		$pathofwebsite = $conf->website->dir_output.'/'.$object->ref;
1150
		dolSaveIndexPage($pathofwebsite, $pathofwebsite.'/index.php', $pathofwebsite.'/page'.$object->fk_default_home.'.tpl.php', $pathofwebsite.'/wrapper.php');
1151
1152
		if ($error)
1153
		{
1154
			$this->db->rollback();
1155
			return -1;
1156
		}
1157
		else
1158
		{
1159
			$this->db->commit();
1160
			return $object->id;
1161
		}
1162
	}
1163
1164
	/**
1165
	 * Return if web site is a multilanguage web site. Return false if there is only 0 or 1 language.
1166
	 *
1167
	 * @return boolean			True if web site is a multilanguage web site
1168
	 */
1169
	public function isMultiLang()
1170
	{
1171
		// TODO Can edit list of languages of web site. Return false if there is only 0 or 1 language.
1172
1173
		return true;
1174
	}
1175
1176
	/**
1177
	 * Component to select language inside a container (Full CSS Only)
1178
	 *
1179
	 * @param	array|string	$languagecodes			'auto' to show all languages available for page, or language codes array like array('en_US','fr_FR','de_DE','es_ES')
1180
	 * @param	Translate		$weblangs				Language Object
1181
	 * @param	string			$morecss				More CSS class on component
1182
	 * @param	string			$htmlname				Suffix for HTML name
1183
	 * @return 	string									HTML select component
1184
	 */
1185
	public function componentSelectLang($languagecodes, $weblangs, $morecss = '', $htmlname = '')
1186
	{
1187
		global $websitepagefile, $website;
1188
1189
		if (!is_object($weblangs)) return 'ERROR componentSelectLang called with parameter $weblangs not defined';
1190
1191
		// Load tmppage if we have $websitepagefile defined
1192
		$tmppage = new WebsitePage($this->db);
1193
1194
		$pageid = 0;
1195
		if (!empty($websitepagefile))
1196
		{
1197
		    $websitepagefileshort = basename($websitepagefile);
1198
		    if ($websitepagefileshort == 'index.php') $pageid = $website->fk_default_home;
1199
		    else $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), $websitepagefileshort);
1200
			if ($pageid > 0)
1201
			{
1202
				$tmppage->fetch($pageid);
1203
			}
1204
		}
1205
1206
		// Fill with existing translation, nothing if none
1207
		if (!is_array($languagecodes) && $pageid > 0)
1208
		{
1209
			$languagecodes = array();
1210
1211
			$sql = "SELECT wp.rowid, wp.lang, wp.pageurl, wp.fk_page";
1212
			$sql .= " FROM ".MAIN_DB_PREFIX."website_page as wp";
1213
			$sql .= " WHERE wp.fk_website = ".$website->id;
1214
			$sql .= " AND (wp.fk_page = ".$pageid." OR wp.rowid  = ".$pageid;
1215
			if ($tmppage->fk_page > 0) $sql .= " OR wp.fk_page = ".$tmppage->fk_page." OR wp.rowid = ".$tmppage->fk_page;
1216
			$sql .= ")";
1217
1218
			$resql = $this->db->query($sql);
1219
			if ($resql)
1220
			{
1221
				while ($obj = $this->db->fetch_object($resql))
1222
				{
1223
					$newlang = $obj->lang;
1224
					if ($obj->rowid == $pageid) $newlang = $obj->lang;
1225
					if (!in_array($newlang, $languagecodes)) $languagecodes[] = $newlang;
1226
				}
1227
			}
1228
		}
1229
		// Now $languagecodes is always an array
1230
1231
		$languagecodeselected = $weblangs->defaultlang; // Because we must init with a value, but real value is the lang of main parent container
1232
		if (!empty($websitepagefile))
1233
		{
1234
			$pageid = str_replace(array('.tpl.php', 'page'), array('', ''), basename($websitepagefile));
1235
			if ($pageid > 0)
1236
			{
1237
				$languagecodeselected = $tmppage->lang;
1238
				if (!in_array($tmppage->lang, $languagecodes)) $languagecodes[] = $tmppage->lang; // We add language code of page into combo list
1239
			}
1240
		}
1241
1242
		$weblangs->load('languages');
1243
		//var_dump($weblangs->defaultlang);
1244
1245
		$url = $_SERVER["REQUEST_URI"];
1246
		$url = preg_replace('/(\?|&)l=([a-zA-Z_]*)/', '', $url); // We remove param l from url
1247
		//$url = preg_replace('/(\?|&)lang=([a-zA-Z_]*)/', '', $url);	// We remove param lang from url
1248
		$url .= (preg_match('/\?/', $url) ? '&' : '?').'l=';
1249
1250
		$HEIGHTOPTION = 40;
1251
		$MAXHEIGHT = 4 * $HEIGHTOPTION;
1252
		$nboflanguage = count($languagecodes);
1253
1254
		$out = '<!-- componentSelectLang'.$htmlname.' -->'."\n";
1255
1256
		$out .= '<style>';
1257
		$out .= '.componentSelectLang'.$htmlname.':hover { height: '.min($MAXHEIGHT, ($HEIGHTOPTION * $nboflanguage)).'px; overflow-x: hidden; overflow-y: '.((($HEIGHTOPTION * $nboflanguage) > $MAXHEIGHT) ? ' scroll' : 'hidden').'; }'."\n";
1258
		$out .= '.componentSelectLang'.$htmlname.' li { line-height: '.$HEIGHTOPTION.'px; }'."\n";
1259
		$out .= '.componentSelectLang'.$htmlname.' {
1260
			display: inline-block;
1261
			padding: 0;
1262
			height: '.$HEIGHTOPTION.'px;
1263
			overflow: hidden;
1264
			transition: all .3s ease;
1265
			margin: 0 0 0 0;
1266
			vertical-align: top;
1267
		}
1268
		.componentSelectLang'.$htmlname.':hover, .componentSelectLang'.$htmlname.':hover a { background-color: #fff; color: #000 !important; }
1269
		ul.componentSelectLang'.$htmlname.' { width: 150px; }
1270
		ul.componentSelectLang'.$htmlname.':hover .fa { visibility: hidden; }
1271
		.componentSelectLang'.$htmlname.' a { text-decoration: none; width: 100%; }
1272
		.componentSelectLang'.$htmlname.' li { display: block; padding: 0px 20px; }
1273
		.componentSelectLang'.$htmlname.' li:hover { background-color: #EEE; }
1274
		';
1275
		$out .= '</style>';
1276
		$out .= '<ul class="componentSelectLang'.$htmlname.($morecss ? ' '.$morecss : '').'">';
1277
		if ($languagecodeselected)
1278
		{
1279
			$shortcode = strtolower(substr($languagecodeselected, -2));
1280
			$label = $weblangs->trans("Language_".$languagecodeselected);
1281
			if ($shortcode == 'us') $label = preg_replace('/\s*\(.*\)/', '', $label);
1282
			$out .= '<a href="'.$url.$languagecodeselected.'"><li><img height="12px" src="medias/image/common/flags/'.$shortcode.'.png" style="margin-right: 5px;"/>'.$label;
1283
			$out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
1284
			$out .= '</li></a>';
1285
		}
1286
		$i = 0;
1287
        if (is_array($languagecodes))
1288
        {
1289
            foreach ($languagecodes as $languagecode)
1290
            {
1291
                if ($languagecode == $languagecodeselected) continue; // Already output
1292
                $shortcode = strtolower(substr($languagecode, -2));
1293
                $label = $weblangs->trans("Language_".$languagecode);
1294
                if ($shortcode == 'us') $label = preg_replace('/\s*\(.*\)/', '', $label);
1295
                $out .= '<a href="'.$url.$languagecode.'"><li><img height="12px" src="medias/image/common/flags/'.$shortcode.'.png" style="margin-right: 5px;"/>'.$label;
1296
                if (empty($i) && empty($languagecodeselected)) $out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
1297
                $out .= '</li></a>';
1298
                $i++;
1299
            }
1300
        }
1301
        $out .= '</ul>';
1302
1303
        return $out;
1304
    }
1305
}
1306