Passed
Pull Request — master (#2)
by
unknown
26:19
created

Website::importWebSite()   C

Complexity

Conditions 12
Paths 35

Size

Total Lines 124
Code Lines 68

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 68
nc 35
nop 1
dl 0
loc 124
rs 6.2714
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 <http://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 mixed
80
	 */
81
	public $date_creation;
82
83
	/**
84
	 * @var mixed
85
	 */
86
	public $tms = '';
87
88
	/**
89
	 * @var integer
90
	 */
91
	public $fk_default_home;
92
93
	/**
94
	 * @var string
95
	 */
96
	public $virtualhost;
97
98
99
	/**
100
	 * Constructor
101
	 *
102
	 * @param DoliDb $db Database handler
103
	 */
104
	public function __construct(DoliDB $db)
105
	{
106
		$this->db = $db;
107
		return 1;
108
	}
109
110
	/**
111
	 * Create object into database
112
	 *
113
	 * @param  User $user      User that creates
114
	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
115
	 *
116
	 * @return int <0 if KO, Id of created object if OK
117
	 */
118
	public function create(User $user, $notrigger = false)
119
	{
120
		global $conf;
121
122
		dol_syslog(__METHOD__, LOG_DEBUG);
123
124
		$error = 0;
125
		$now=dol_now();
126
127
		// Clean parameters
128
		if (isset($this->entity)) {
129
			 $this->entity = trim($this->entity);
0 ignored issues
show
Documentation Bug introduced by
The property $entity was declared of type integer, but trim($this->entity) is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
130
		}
131
		if (isset($this->ref)) {
132
			 $this->ref = trim($this->ref);
133
		}
134
		if (isset($this->description)) {
135
			 $this->description = trim($this->description);
136
		}
137
		if (isset($this->status)) {
138
			 $this->status = trim($this->status);
0 ignored issues
show
Documentation Bug introduced by
The property $status was declared of type integer, but trim($this->status) is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
139
		}
140
		if (empty($this->date_creation)) {
141
            $this->date_creation = $now;
142
        }
143
		if (empty($this->date_modification)) {
144
            $this->date_modification = $now;
145
        }
146
147
		// Check parameters
148
		if (empty($this->entity)) {
149
            $this->entity = $conf->entity;
150
        }
151
152
		// Insert request
153
		$sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . '(';
154
		$sql.= 'entity,';
155
		$sql.= 'ref,';
156
		$sql.= 'description,';
157
		$sql.= 'status,';
158
		$sql.= 'fk_default_home,';
159
		$sql.= 'virtualhost,';
160
		$sql.= 'fk_user_creat,';
161
		$sql.= 'date_creation,';
162
		$sql.= 'tms';
163
		$sql .= ') VALUES (';
164
		$sql .= ' '.((empty($this->entity) && $this->entity != '0')?'NULL':$this->entity).',';
165
		$sql .= ' '.(! isset($this->ref)?'NULL':"'".$this->db->escape($this->ref)."'").',';
166
		$sql .= ' '.(! isset($this->description)?'NULL':"'".$this->db->escape($this->description)."'").',';
167
		$sql .= ' '.(! isset($this->status)?'1':$this->status).',';
168
		$sql .= ' '.(! isset($this->fk_default_home)?'NULL':$this->fk_default_home).',';
169
		$sql .= ' '.(! isset($this->virtualhost)?'NULL':"'".$this->db->escape($this->virtualhost)."'").",";
170
		$sql .= ' '.(! isset($this->fk_user_creat)?$user->id:$this->fk_user_creat).',';
171
		$sql .= ' '.(! isset($this->date_creation) || dol_strlen($this->date_creation)==0?'NULL':"'".$this->db->idate($this->date_creation)."'").",";
172
		$sql .= ' '.(! isset($this->date_modification) || dol_strlen($this->date_modification)==0?'NULL':"'".$this->db->idate($this->date_creation)."'");
173
		$sql .= ')';
174
175
		$this->db->begin();
176
177
		$resql = $this->db->query($sql);
178
		if (!$resql) {
179
			$error ++;
180
			$this->errors[] = 'Error ' . $this->db->lasterror();
181
			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
182
		}
183
184
		if (!$error) {
185
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
186
187
            // Uncomment this and change MYOBJECT to your own tag if you
188
            // want this action to call a trigger.
189
            // if (!$notrigger) {
190
191
            //     // Call triggers
192
            //     $result = $this->call_trigger('MYOBJECT_CREATE',$user);
193
            //     if ($result < 0) $error++;
194
            //     // End call triggers
195
            // }
196
        }
197
198
		// Commit or rollback
199
		if ($error) {
200
			$this->db->rollback();
201
202
			return - 1 * $error;
203
		} else {
204
			$this->db->commit();
205
206
			return $this->id;
207
		}
208
	}
209
210
	/**
211
	 * Load object in memory from the database
212
	 *
213
	 * @param 	int    $id  	Id object
214
	 * @param 	string $ref 	Ref
215
	 * @return 	int 			<0 if KO, 0 if not found, >0 if OK
216
	 */
217
	public function fetch($id, $ref = null)
218
	{
219
		dol_syslog(__METHOD__, LOG_DEBUG);
220
221
		$sql = 'SELECT';
222
		$sql .= ' t.rowid,';
223
		$sql .= " t.entity,";
224
		$sql .= " t.ref,";
225
		$sql .= " t.description,";
226
		$sql .= " t.status,";
227
		$sql .= " t.fk_default_home,";
228
		$sql .= " t.virtualhost,";
229
		$sql .= " t.fk_user_creat,";
230
		$sql .= " t.fk_user_modif,";
231
		$sql .= " t.date_creation,";
232
		$sql .= " t.tms as date_modification";
233
		$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
234
		$sql .= ' WHERE t.entity IN ('.getEntity('website').')';
235
		if (null !== $ref) {
236
			$sql .= " AND t.ref = '" . $this->db->escape($ref) . "'";
237
		} else {
238
			$sql .= ' AND t.rowid = ' . $id;
239
		}
240
241
		$resql = $this->db->query($sql);
242
		if ($resql) {
243
			$numrows = $this->db->num_rows($resql);
244
			if ($numrows) {
245
				$obj = $this->db->fetch_object($resql);
246
247
				$this->id = $obj->rowid;
248
249
				$this->entity = $obj->entity;
250
				$this->ref = $obj->ref;
251
				$this->description = $obj->description;
252
				$this->status = $obj->status;
253
				$this->fk_default_home = $obj->fk_default_home;
254
				$this->virtualhost = $obj->virtualhost;
255
				$this->fk_user_creat = $obj->fk_user_creat;
256
				$this->fk_user_modif = $obj->fk_user_modif;
257
				$this->date_creation = $this->db->jdate($obj->date_creation);
258
				$this->date_modification = $this->db->jdate($obj->date_modification);
259
			}
260
			$this->db->free($resql);
261
262
			if ($numrows > 0) {
263
				// Lines
264
				$this->fetchLines();
265
			}
266
267
			if ($numrows > 0) {
268
				return 1;
269
			} else {
270
				return 0;
271
			}
272
		} else {
273
			$this->errors[] = 'Error ' . $this->db->lasterror();
274
			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
275
276
			return - 1;
277
		}
278
	}
279
280
	/**
281
	 * Load object lines in memory from the database
282
	 *
283
	 * @return int         <0 if KO, 0 if not found, >0 if OK
284
	 */
285
	public function fetchLines()
286
	{
287
		$this->lines=array();
288
289
		// Load lines with object MyObjectLine
290
291
		return count($this->lines)?1:0;
292
	}
293
294
295
	/**
296
	 * Load object in memory from the database
297
	 *
298
	 * @param string $sortorder Sort Order
299
	 * @param string $sortfield Sort field
300
	 * @param int    $limit     offset limit
301
	 * @param int    $offset    offset limit
302
	 * @param array  $filter    filter array
303
	 * @param string $filtermode filter mode (AND or OR)
304
	 *
305
	 * @return int <0 if KO, >0 if OK
306
	 */
307
	public function fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, array $filter = array(), $filtermode='AND')
308
	{
309
		dol_syslog(__METHOD__, LOG_DEBUG);
310
311
		$sql = 'SELECT';
312
		$sql .= ' t.rowid,';
313
		$sql .= " t.entity,";
314
		$sql .= " t.ref,";
315
		$sql .= " t.description,";
316
		$sql .= " t.status,";
317
		$sql .= " t.fk_default_home,";
318
		$sql .= " t.virtualhost,";
319
		$sql .= " t.fk_user_creat,";
320
		$sql .= " t.fk_user_modif,";
321
		$sql .= " t.date_creation,";
322
		$sql .= " t.tms as date_modification";
323
		$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element. ' as t';
324
		$sql .= ' WHERE t.entity IN ('.getEntity('website').')';
325
		// Manage filter
326
		$sqlwhere = array();
327
		if (count($filter) > 0) {
328
			foreach ($filter as $key => $value) {
329
				$sqlwhere [] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\'';
330
			}
331
		}
332
		if (count($sqlwhere) > 0) {
333
			$sql .= ' AND ' . implode(' '.$filtermode.' ', $sqlwhere);
334
		}
335
336
		if (!empty($sortfield)) {
337
			$sql .= $this->db->order($sortfield,$sortorder);
338
		}
339
		if (!empty($limit)) {
340
		 $sql .=  ' ' . $this->db->plimit($limit, $offset);
341
		}
342
		$this->records = array();
343
344
		$resql = $this->db->query($sql);
345
		if ($resql) {
346
			$num = $this->db->num_rows($resql);
347
348
			while ($obj = $this->db->fetch_object($resql)) {
349
				$line = new self($this->db);
350
351
				$line->id = $obj->rowid;
352
353
				$line->entity = $obj->entity;
354
				$line->ref = $obj->ref;
355
				$line->description = $obj->description;
356
				$line->status = $obj->status;
357
				$line->fk_default_home = $obj->fk_default_home;
358
				$line->virtualhost = $obj->virtualhost;
359
				$this->fk_user_creat = $obj->fk_user_creat;
360
				$this->fk_user_modif = $obj->fk_user_modif;
361
				$line->date_creation = $this->db->jdate($obj->date_creation);
362
				$line->date_modification = $this->db->jdate($obj->date_modification);
363
364
				$this->records[$line->id] = $line;
365
			}
366
			$this->db->free($resql);
367
368
			return $num;
369
		} else {
370
			$this->errors[] = 'Error ' . $this->db->lasterror();
371
			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
372
373
			return - 1;
374
		}
375
	}
376
377
	/**
378
	 * Update object into database
379
	 *
380
	 * @param  User $user      User that modifies
381
	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
382
	 *
383
	 * @return int <0 if KO, >0 if OK
384
	 */
385
	public function update(User $user, $notrigger = false)
386
	{
387
		$error = 0;
388
389
		dol_syslog(__METHOD__, LOG_DEBUG);
390
391
		// Clean parameters
392
393
		if (isset($this->entity)) {
394
			 $this->entity = trim($this->entity);
0 ignored issues
show
Documentation Bug introduced by
The property $entity was declared of type integer, but trim($this->entity) is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
395
		}
396
		if (isset($this->ref)) {
397
			 $this->ref = trim($this->ref);
398
		}
399
		if (isset($this->description)) {
400
			 $this->description = trim($this->description);
401
		}
402
		if (isset($this->status)) {
403
			 $this->status = trim($this->status);
0 ignored issues
show
Documentation Bug introduced by
The property $status was declared of type integer, but trim($this->status) is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
404
		}
405
406
		// Check parameters
407
		// Put here code to add a control on parameters values
408
409
		// Update request
410
		$sql = 'UPDATE ' . MAIN_DB_PREFIX . $this->table_element . ' SET';
411
		$sql .= ' entity = '.(isset($this->entity)?$this->entity:"null").',';
412
		$sql .= ' ref = '.(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").',';
413
		$sql .= ' description = '.(isset($this->description)?"'".$this->db->escape($this->description)."'":"null").',';
414
		$sql .= ' status = '.(isset($this->status)?$this->status:"null").',';
415
		$sql .= ' fk_default_home = '.(($this->fk_default_home > 0)?$this->fk_default_home:"null").',';
416
		$sql .= ' virtualhost = '.(($this->virtualhost != '')?"'".$this->db->escape($this->virtualhost)."'":"null").',';
417
		$sql .= ' fk_user_modif = '.(! isset($this->fk_user_modif) ? $user->id : $this->fk_user_modif).',';
418
		$sql .= ' date_creation = '.(! isset($this->date_creation) || dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null');
419
		$sql .= ', tms = '.(dol_strlen($this->date_modification) != 0 ? "'".$this->db->idate($this->date_modification)."'" : "'".$this->db->idate(dol_now())."'");
420
		$sql .= ' WHERE rowid=' . $this->id;
421
422
		$this->db->begin();
423
424
		$resql = $this->db->query($sql);
425
		if (!$resql) {
426
			$error ++;
427
			$this->errors[] = 'Error ' . $this->db->lasterror();
428
			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
429
		}
430
431
		if (!$error && !$notrigger) {
432
			// Uncomment this and change MYOBJECT to your own tag if you
433
			// want this action calls a trigger.
434
435
			//// Call triggers
436
			//$result=$this->call_trigger('MYOBJECT_MODIFY',$user);
437
			//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
438
			//// End call triggers
439
		}
440
441
		// Commit or rollback
442
		if ($error) {
443
			$this->db->rollback();
444
445
			return - 1 * $error;
446
		} else {
447
			$this->db->commit();
448
449
			return 1;
450
		}
451
	}
452
453
	/**
454
	 * Delete object in database
455
	 *
456
	 * @param User $user      User that deletes
457
	 * @param bool $notrigger false=launch triggers after, true=disable triggers
458
	 *
459
	 * @return int <0 if KO, >0 if OK
460
	 */
461
	public function delete(User $user, $notrigger = false)
462
	{
463
		dol_syslog(__METHOD__, LOG_DEBUG);
464
465
		$error = 0;
466
467
		$this->db->begin();
468
469
		if (!$error) {
470
			if (!$notrigger) {
471
				// Uncomment this and change MYOBJECT to your own tag if you
472
				// want this action calls a trigger.
473
474
				//// Call triggers
475
				//$result=$this->call_trigger('MYOBJECT_DELETE',$user);
476
				//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
477
				//// End call triggers
478
			}
479
		}
480
481
		if (!$error) {
482
			$sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element;
483
			$sql .= ' WHERE rowid=' . $this->id;
484
485
			$resql = $this->db->query($sql);
486
			if (!$resql) {
487
				$error ++;
488
				$this->errors[] = 'Error ' . $this->db->lasterror();
489
				dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
490
			}
491
		}
492
493
		if (! $error && ! empty($this->ref))
494
		{
495
			global $dolibarr_main_data_root;
496
			$pathofwebsite=$dolibarr_main_data_root.'/website/'.$this->ref;
497
498
			dol_delete_dir_recursive($pathofwebsite);
499
		}
500
501
		// Commit or rollback
502
		if ($error) {
503
			$this->db->rollback();
504
505
			return - 1 * $error;
506
		} else {
507
			$this->db->commit();
508
509
			return 1;
510
		}
511
	}
512
513
	/**
514
	 * Load an object from its id and create a new one in database.
515
	 * This copy website directories, regenerate all the pages + alias pages and recreate the medias link.
516
	 *
517
	 * @param	User	$user		User making the clone
518
	 * @param 	int 	$fromid 	Id of object to clone
519
	 * @param	string	$newref		New ref
520
	 * @param	string	$newlang	New language
521
	 * @return 	mixed 				New object created, <0 if KO
522
	 */
523
	public function createFromClone($user, $fromid, $newref, $newlang='')
524
	{
525
        global $hookmanager, $langs;
526
		global $dolibarr_main_data_root;
527
528
		$error=0;
529
530
        dol_syslog(__METHOD__, LOG_DEBUG);
531
532
		$object = new self($this->db);
533
534
        // Check no site with ref exists
535
		if ($object->fetch(0, $newref) > 0)
536
		{
537
			$this->error='NewRefIsAlreadyUsed';
538
			return -1;
539
		}
540
541
		$this->db->begin();
542
543
		// Load source object
544
		$object->fetch($fromid);
545
546
		$oldidforhome=$object->fk_default_home;
547
548
		$pathofwebsiteold=$dolibarr_main_data_root.'/website/'.$object->ref;
549
		$pathofwebsitenew=$dolibarr_main_data_root.'/website/'.$newref;
550
		dol_delete_dir_recursive($pathofwebsitenew);
551
552
		$fileindex=$pathofwebsitenew.'/index.php';
553
554
		// Reset some properties
555
		unset($object->id);
556
		unset($object->fk_user_creat);
557
		unset($object->import_key);
558
559
		// Clear fields
560
		$object->ref=$newref;
561
		$object->fk_default_home=0;
562
		$object->virtualhost='';
563
564
		// Create clone
565
		$object->context['createfromclone'] = 'createfromclone';
566
		$result = $object->create($user);
567
		if ($result < 0) {
568
			$error ++;
569
			$this->errors = $object->errors;
570
			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
571
		}
572
573
		if (! $error)
574
		{
575
			dolCopyDir($pathofwebsiteold, $pathofwebsitenew, $conf->global->MAIN_UMASK, 0);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $conf seems to be never defined.
Loading history...
576
577
			// Check symlink to medias and restore it if ko
578
			$pathtomedias=DOL_DATA_ROOT.'/medias';
579
			$pathtomediasinwebsite=$pathofwebsitenew.'/medias';
580
			if (! is_link(dol_osencode($pathtomediasinwebsite)))
581
			{
582
				dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite);
583
				dol_mkdir(dirname($pathtomediasinwebsite));     // To be sure dir for website exists
584
				$result = symlink($pathtomedias, $pathtomediasinwebsite);
585
			}
586
587
			$newidforhome=0;
588
589
			// Duplicate pages
590
			$objectpages = new WebsitePage($this->db);
591
			$listofpages = $objectpages->fetchAll($fromid);
592
			foreach($listofpages as $pageid => $objectpageold)
0 ignored issues
show
Bug introduced by
The expression $listofpages of type integer is not traversable.
Loading history...
593
			{
594
				// Delete old file
595
				$filetplold=$pathofwebsitenew.'/page'.$pageid.'.tpl.php';
596
				dol_syslog("We regenerate alias page new name=".$filealias.", old name=".$fileoldalias);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $filealias seems to be defined later in this foreach loop on line 604. Are you sure it is defined here?
Loading history...
Comprehensibility Best Practice introduced by
The variable $fileoldalias does not exist. Did you maybe mean $filealias?
Loading history...
597
				dol_delete_file($filetplold);
598
599
				// Create new file
600
				$objectpagenew = $objectpageold->createFromClone($user, $pageid, $objectpageold->pageurl, '', 0, $object->id, 1);
601
				//print $pageid.' = '.$objectpageold->pageurl.' -> '.$objectpagenew->id.' = '.$objectpagenew->pageurl.'<br>';
602
				if (is_object($objectpagenew) && $objectpagenew->pageurl)
603
				{
604
		            $filealias=$pathofwebsitenew.'/'.$objectpagenew->pageurl.'.php';
605
					$filetplnew=$pathofwebsitenew.'/page'.$objectpagenew->id.'.tpl.php';
606
607
					// Save page alias
608
					$result=dolSavePageAlias($filealias, $object, $objectpagenew);
609
					if (! $result) setEventMessages('Failed to write file '.$filealias, null, 'errors');
610
611
					$result=dolSavePageContent($filetplnew, $object, $objectpagenew);
612
					if (! $result) setEventMessages('Failed to write file '.$filetplnew, null, 'errors');
613
614
					if ($pageid == $oldidforhome)
615
					{
616
						$newidforhome = $objectpagenew->id;
617
					}
618
				}
619
				else
620
				{
621
					setEventMessages($objectpageold->error, $objectpageold->errors, 'errors');
622
					$error++;
623
				}
624
			}
625
		}
626
627
		if (! $error)
628
		{
629
			// Restore id of home page
630
			$object->fk_default_home = $newidforhome;
631
		    $res = $object->update($user);
632
		    if (! $res > 0)
633
		    {
634
		        $error++;
635
		        setEventMessages($objectpage->error, $objectpage->errors, 'errors');
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $objectpage does not exist. Did you maybe mean $object?
Loading history...
636
		    }
637
638
		    if (! $error)
639
		    {
640
		    	$filetpl=$pathofwebsitenew.'/page'.$newidforhome.'.tpl.php';
641
		    	$filewrapper=$pathofwebsitenew.'/wrapper.php';
642
643
		    	// Generate the index.php page to be the home page
644
		    	//-------------------------------------------------
645
		    	$result = dolSaveIndexPage($pathofwebsitenew, $fileindex, $filetpl, $filewrapper);
646
		    }
647
		}
648
649
		// End
650
		if (!$error) {
651
			$this->db->commit();
652
653
			return $object;
654
		} else {
655
			$this->db->rollback();
656
657
			return - 1;
658
		}
659
	}
660
661
	/**
662
	 *  Return a link to the user card (with optionaly the picto)
663
	 * 	Use this->id,this->lastname, this->firstname
664
	 *
665
	 *	@param	int		$withpicto			Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
666
	 *	@param	string	$option				On what the link point to
667
     *  @param	integer	$notooltip			1=Disable tooltip
668
     *  @param	int		$maxlen				Max length of visible user name
669
     *  @param  string  $morecss            Add more css on link
670
	 *	@return	string						String with URL
671
	 */
672
	function getNomUrl($withpicto=0, $option='', $notooltip=0, $maxlen=24, $morecss='')
673
	{
674
		global $langs, $conf, $db;
675
        global $dolibarr_main_authentication, $dolibarr_main_demo;
676
        global $menumanager;
677
678
679
        $result = '';
680
        $companylink = '';
681
682
        $label = '<u>' . $langs->trans("WebSite") . '</u>';
683
        $label.= '<div width="100%">';
684
        $label.= '<b>' . $langs->trans('Nom') . ':</b> ' . $this->ref;
685
686
        $linkstart = '<a href="'.DOL_URL_ROOT.'/website/card.php?id='.$this->id.'"';
687
        $linkstart.= ($notooltip?'':' title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip'.($morecss?' '.$morecss:'').'"');
688
        $linkstart.= '>';
689
		$linkend='</a>';
690
691
		$linkstart = $linkend = '';
692
693
        if ($withpicto)
694
        {
695
            $result.=($linkstart.img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?'':'class="classfortooltip"')).$linkend);
696
            if ($withpicto != 2) $result.=' ';
697
		}
698
		$result.= $linkstart . $this->ref . $linkend;
699
		return $result;
700
	}
701
702
	/**
703
	 *  Retourne le libelle du status d'un user (actif, inactif)
704
	 *
705
	 *  @param	int		$mode          0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
706
	 *  @return	string 			       Label of status
707
	 */
708
	function getLibStatut($mode=0)
709
	{
710
		return $this->LibStatut($this->status,$mode);
711
	}
712
713
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
714
	/**
715
	 *  Renvoi le libelle d'un status donne
716
	 *
717
	 *  @param	int		$status        	Id status
718
	 *  @param  int		$mode          	0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
719
	 *  @return string 			       	Label of status
720
	 */
721
	function LibStatut($status,$mode=0)
722
	{
723
        // phpcs:enable
724
		global $langs;
725
726
		if ($mode == 0 || $mode == 1)
727
		{
728
			if ($status == 1) return $langs->trans('Enabled');
729
			if ($status == 0) return $langs->trans('Disabled');
730
		}
731
		elseif ($mode == 2)
732
		{
733
			if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
734
			if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
735
		}
736
		elseif ($mode == 3)
737
		{
738
			if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4');
739
			if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5');
740
		}
741
		elseif ($mode == 4)
742
		{
743
			if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
744
			if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
745
		}
746
		elseif ($mode == 5)
747
		{
748
			if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4');
749
			if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5');
750
		}
751
	}
752
753
754
	/**
755
	 * Initialise object with example values
756
	 * Id must be 0 if object instance is a specimen
757
	 *
758
	 * @return void
759
	 */
760
	public function initAsSpecimen()
761
	{
762
	    global $user;
763
764
		$this->id = 0;
765
766
		$this->entity = 1;
767
		$this->ref = 'myspecimenwebsite';
768
		$this->description = 'A specimen website';
769
		$this->status = '';
0 ignored issues
show
Documentation Bug introduced by
The property $status was declared of type integer, but '' is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
770
		$this->fk_default_home = null;
771
		$this->virtualhost = 'http://myvirtualhost';
772
		$this->fk_user_creat = $user->id;
773
		$this->fk_user_modif = $user->id;
774
		$this->date_creation = dol_now();
775
		$this->tms = dol_now();
776
	}
777
778
779
	/**
780
	 * Generate a zip with all data of web site.
781
	 *
782
	 * @return  string						Path to file with zip
783
	 */
784
	function exportWebSite()
785
	{
786
		global $conf, $mysoc;
787
788
		$website = $this;
789
790
		if (empty($website->id) || empty($website->ref))
791
		{
792
			setEventMessages("Website id or ref is not defined", null, 'errors');
793
			return '';
794
		}
795
796
		dol_syslog("Create temp dir ".$conf->website->dir_temp);
797
		dol_mkdir($conf->website->dir_temp);
798
		if (! is_writable($conf->website->dir_temp))
799
		{
800
			setEventMessages("Temporary dir ".$conf->website->dir_temp." is not writable", null, 'errors');
801
			return '';
802
		}
803
804
		$destdir = $conf->website->dir_temp.'/'.$website->ref;
805
806
		dol_syslog("Clear temp dir ".$destdir);
807
		$count=0; $countreallydeleted=0;
808
		$counttodelete = dol_delete_dir_recursive($destdir, $count, 1, 0, $countreallydeleted);
809
		if ($counttodelete != $countreallydeleted)
810
		{
811
			setEventMessages("Failed to clean temp directory ".$destdir, null, 'errors');
812
			return '';
813
		}
814
815
		$arrayreplacement=array();
816
817
		$srcdir = $conf->website->dir_output.'/'.$website->ref;
818
		$destdir = $conf->website->dir_temp.'/'.$website->ref.'/containers';
819
820
		dol_syslog("Copy content from ".$srcdir." into ".$destdir);
821
		dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacement);
822
823
		$srcdir = DOL_DATA_ROOT.'/medias/image/'.$website->ref;
824
		$destdir = $conf->website->dir_temp.'/'.$website->ref.'/medias/image/websitekey';
825
826
		dol_syslog("Copy content from ".$srcdir." into ".$destdir);
827
		dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacement);
828
829
		$srcdir = DOL_DATA_ROOT.'/medias/js/'.$website->ref;
830
		$destdir = $conf->website->dir_temp.'/'.$website->ref.'/medias/js/websitekey';
831
832
		dol_syslog("Copy content from ".$srcdir." into ".$destdir);
833
		dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacement);
834
835
		// Build sql file
836
		dol_syslog("Create containers dir");
837
		dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/containers');
838
839
		$filesql = $conf->website->dir_temp.'/'.$website->ref.'/website_pages.sql';
840
		$fp = fopen($filesql,"w");
841
		if (empty($fp))
842
		{
843
			setEventMessages("Failed to create file ".$filesql, null, 'errors');
844
			return '';
845
		}
846
847
		$objectpages = new WebsitePage($this->db);
848
		$listofpages = $objectpages->fetchAll($website->id);
849
850
		// Assign ->newid and ->newfk_page
851
		$i=1;
852
		foreach($listofpages as $pageid => $objectpageold)
0 ignored issues
show
Bug introduced by
The expression $listofpages of type integer is not traversable.
Loading history...
853
		{
854
			$objectpageold->newid=$i;
855
			$i++;
856
		}
857
		$i=1;
858
		foreach($listofpages as $pageid => $objectpageold)
0 ignored issues
show
Bug introduced by
The expression $listofpages of type integer is not traversable.
Loading history...
859
		{
860
			// Search newid
861
			$newfk_page=0;
862
			foreach($listofpages as $pageid2 => $objectpageold2)
0 ignored issues
show
Bug introduced by
The expression $listofpages of type integer is not traversable.
Loading history...
863
			{
864
				if ($pageid2 == $objectpageold->fk_page)
865
				{
866
					$newfk_page = $objectpageold2->newid;
867
					break;
868
				}
869
			}
870
			$objectpageold->newfk_page=$newfk_page;
871
			$i++;
872
		}
873
		foreach($listofpages as $pageid => $objectpageold)
0 ignored issues
show
Bug introduced by
The expression $listofpages of type integer is not traversable.
Loading history...
874
		{
875
			$allaliases = $objectpageold->pageurl;
876
			$allaliases.= ($objectpageold->aliasalt ? ','.$objectpageold->aliasalt : '');
877
878
			$line = '-- Page ID '.$objectpageold->id.' -> '.$objectpageold->newid.'__+MAX_llx_website_page__ - Aliases '.$allaliases.' --;';	// newid start at 1, 2...
879
			$line.= "\n";
880
			fputs($fp, $line);
881
882
			// Warning: We must keep llx_ here. It is a generic SQL.
883
			$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)';
884
			$line.= " VALUES(";
885
			$line.= $objectpageold->newid."__+MAX_llx_website_page__, ";
886
			$line.= ($objectpageold->newfk_page ? $this->db->escape($objectpageold->newfk_page)."__+MAX_llx_website_page__" : "null").", ";
887
			$line.= "__WEBSITE_ID__, ";
888
			$line.= "'".$this->db->escape($objectpageold->pageurl)."', ";
889
			$line.= "'".$this->db->escape($objectpageold->aliasalt)."', ";
890
			$line.= "'".$this->db->escape($objectpageold->title)."', ";
891
			$line.= "'".$this->db->escape($objectpageold->description)."', ";
892
			$line.= "'".$this->db->escape($objectpageold->image)."', ";
893
			$line.= "'".$this->db->escape($objectpageold->keywords)."', ";
894
			$line.= "'".$this->db->escape($objectpageold->status)."', ";
895
			$line.= "'".$this->db->idate($objectpageold->date_creation)."', ";
896
			$line.= "'".$this->db->idate($objectpageold->date_modification)."', ";
897
			$line.= "'".$this->db->escape($objectpageold->lang)."', ";
898
			$line.= ($objectpageold->import_key ? "'".$this->db->escape($objectpageold->import_key)."'" : "null").", ";
899
			$line.= "'".$this->db->escape($objectpageold->grabbed_from)."', ";
900
			$line.= "'".$this->db->escape($objectpageold->type_container)."', ";
901
902
			$stringtoexport = $objectpageold->htmlheader;
903
			$stringtoexport = str_replace(array("\r\n","\r","\n"), "__N__", $stringtoexport);
904
			$stringtoexport = str_replace('file=image/'.$website->ref.'/', "file=image/__WEBSITE_KEY__/", $stringtoexport);
905
			$stringtoexport = str_replace('file=js/'.$website->ref.'/', "file=js/__WEBSITE_KEY__/", $stringtoexport);
906
			$stringtoexport = str_replace('medias/image/'.$website->ref.'/', "medias/image/__WEBSITE_KEY__/", $stringtoexport);
907
			$stringtoexport = str_replace('medias/js/'.$website->ref.'/', "medias/js/__WEBSITE_KEY__/", $stringtoexport);
908
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_small, "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__", $stringtoexport);
909
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_mini, "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__", $stringtoexport);
910
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo, "file=logos%2Fthumbs%2F__LOGO_KEY__", $stringtoexport);
911
			$line.= "'".$this->db->escape(str_replace(array("\r\n","\r","\n"), "__N__", $stringtoexport))."', ";	// Replace \r \n to have record on 1 line
912
913
			$stringtoexport = $objectpageold->content;
914
			$stringtoexport = str_replace(array("\r\n","\r","\n"), "__N__", $stringtoexport);
915
			$stringtoexport = str_replace('file=image/'.$website->ref.'/', "file=image/__WEBSITE_KEY__/", $stringtoexport);
916
			$stringtoexport = str_replace('file=js/'.$website->ref.'/', "file=js/__WEBSITE_KEY__/", $stringtoexport);
917
			$stringtoexport = str_replace('medias/image/'.$website->ref.'/', "medias/image/__WEBSITE_KEY__/", $stringtoexport);
918
			$stringtoexport = str_replace('medias/js/'.$website->ref.'/', "medias/js/__WEBSITE_KEY__/", $stringtoexport);
919
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_small, "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__", $stringtoexport);
920
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_mini, "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__", $stringtoexport);
921
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo, "file=logos%2Fthumbs%2F__LOGO_KEY__", $stringtoexport);
922
			$line.= "'".$this->db->escape($stringtoexport)."'";		// Replace \r \n to have record on 1 line
923
			$line.= ");";
924
			$line.= "\n";
925
			fputs($fp, $line);
926
927
			// Add line to update home page id during import
928
			//var_dump($this->fk_default_home.' - '.$objectpageold->id.' - '.$objectpageold->newid);exit;
929
			if ($this->fk_default_home > 0 && ($objectpageold->id == $this->fk_default_home) && ($objectpageold->newid > 0))	// This is the record with home page
930
			{
931
				$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__;";
932
				$line.= "\n";
933
				fputs($fp, $line);
934
			}
935
		}
936
937
		fclose($fp);
938
		if (! empty($conf->global->MAIN_UMASK))
939
			@chmod($filesql, octdec($conf->global->MAIN_UMASK));
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

939
			/** @scrutinizer ignore-unhandled */ @chmod($filesql, octdec($conf->global->MAIN_UMASK));

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
940
941
		// Build zip file
942
		$filedir  = $conf->website->dir_temp.'/'.$website->ref.'/.';
943
		$fileglob = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-*.zip';
944
		$filename = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-'.dol_print_date(dol_now(),'dayhourlog').'.zip';
945
946
		dol_delete_file($fileglob, 0);
947
		dol_compress_file($filedir, $filename, 'zip');
948
949
		return $filename;
950
	}
951
952
953
	/**
954
	 * Open a zip with all data of web site and load it into database.
955
	 *
956
	 * @param 	string		$pathtofile		Path of zip file
957
	 * @return  int							<0 if KO, Id of new website if OK
958
	 */
959
	function importWebSite($pathtofile)
960
	{
961
		global $conf, $mysoc;
962
963
		$error = 0;
964
965
		$object = $this;
966
		if (empty($object->ref))
967
		{
968
			$this->error = 'Function importWebSite called on object not loaded (object->ref is empty)';
969
			return -1;
970
		}
971
972
		dol_delete_dir_recursive(dirname($pathtofile).'/'.$object->ref);
973
		dol_mkdir(dirname($pathtofile).'/'.$object->ref);
974
975
		$filename = basename($pathtofile);
976
		if (! preg_match('/^website_(.*)-(.*)$/', $filename, $reg))
977
		{
978
			$this->errors[]='Bad format for filename '.$filename.'. Must be website_XXX-VERSION.';
979
			return -1;
980
		}
981
982
		$result = dol_uncompress($pathtofile, $conf->website->dir_temp.'/'.$object->ref);
983
		if (! empty($result['error']))
984
		{
985
			$this->errors[]='Failed to unzip file '.$pathtofile.'.';
986
			return -1;
987
		}
988
989
990
		dolCopyDir($conf->website->dir_temp.'/'.$object->ref.'/containers', $conf->website->dir_output.'/'.$object->ref, 0, 1);	// Overwrite if exists
991
992
		// Now generate the master.inc.php page
993
		$filemaster=$conf->website->dir_output.'/'.$object->ref.'/master.inc.php';
994
		$result = dolSaveMasterFile($filemaster);
995
		if (! $result)
996
		{
997
			$this->errors[]='Failed to write file '.$filemaster;
998
			$error++;
999
		}
1000
1001
		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
1002
		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
1003
1004
		$sqlfile = $conf->website->dir_temp.'/'.$object->ref.'/website_pages.sql';
1005
1006
		$arrayreplacement = array();
1007
		$arrayreplacement['__WEBSITE_ID__'] = $object->id;
1008
		$arrayreplacement['__WEBSITE_KEY__'] = $object->ref;
1009
		$arrayreplacement['__N__'] = $this->db->escape("\n");			// Restore \n
1010
		$arrayreplacement['__LOGO_SMALL_KEY__'] = $this->db->escape($mysoc->logo_small);
1011
		$arrayreplacement['__LOGO_MINI_KEY__'] = $this->db->escape($mysoc->logo_mini);
1012
		$arrayreplacement['__LOGO_KEY__'] = $this->db->escape($mysoc->logo);
1013
		$result = dolReplaceInFile($sqlfile, $arrayreplacement);
1014
1015
		$this->db->begin();
1016
1017
		// Search the $maxrowid because we need it later
1018
		$sqlgetrowid='SELECT MAX(rowid) as max from '.MAIN_DB_PREFIX.'website_page';
1019
		$resql=$this->db->query($sqlgetrowid);
1020
		if ($resql)
1021
		{
1022
			$obj=$this->db->fetch_object($resql);
1023
			$maxrowid=$obj->max;
1024
		}
1025
1026
		// Load sql record
1027
		$runsql = run_sql($sqlfile, 1, '', 0, '', 'none', 0, 1);	// The maxrowid of table is searched into this function two
1028
		if ($runsql <= 0)
1029
		{
1030
			$this->errors[]='Failed to load sql file '.$sqlfile;
1031
			$error++;
1032
		}
1033
1034
		$objectpagestatic = new WebsitePage($this->db);
1035
1036
		// Make replacement of IDs
1037
		$fp = fopen($sqlfile,"r");
1038
		if ($fp)
1039
		{
1040
			while (! feof($fp))
1041
			{
1042
				// Warning fgets with second parameter that is null or 0 hang.
1043
				$buf = fgets($fp, 65000);
1044
				if (preg_match('/^-- Page ID (\d+)\s[^\s]+\s(\d+).*Aliases\s(.*)\s--;/i', $buf, $reg))
1045
				{
1046
					$oldid = $reg[1];
1047
					$newid = ($reg[2] + $maxrowid);
1048
					$aliasesarray = explode(',', $reg[3]);
1049
1050
					$objectpagestatic->fetch($newid);
1051
1052
					dol_syslog("Found ID ".$oldid." to replace with ID ".$newid." and shortcut aliases to create: ".$reg[3]);
1053
1054
					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);
1055
1056
					// The move is not enough, so we regenerate page
1057
					$filetpl=$conf->website->dir_output.'/'.$object->ref.'/page'.$newid.'.tpl.php';
1058
					dolSavePageContent($filetpl, $object, $objectpagestatic);
1059
1060
					// Regenerate alternative aliases pages
1061
					foreach($aliasesarray as $aliasshortcuttocreate)
1062
					{
1063
						$filealias=$conf->website->dir_output.'/'.$object->ref.'/'.$aliasshortcuttocreate.'.php';
1064
						dolSavePageAlias($filealias, $object, $objectpagestatic);
1065
					}
1066
				}
1067
			}
1068
		}
1069
1070
		// Regenerate index page to point to new index page
1071
		$pathofwebsite = $conf->website->dir_output.'/'.$object->ref;
1072
		dolSaveIndexPage($pathofwebsite, $pathofwebsite.'/index.php', $pathofwebsite.'/page'.$object->fk_default_home.'.tpl.php', $pathofwebsite.'/wrapper.php');
1073
1074
		if ($error)
1075
		{
1076
			$this->db->rollback();
1077
			return -1;
1078
		}
1079
		else
1080
		{
1081
			$this->db->commit();
1082
			return $object->id;
1083
		}
1084
	}
1085
1086
	/**
1087
	 * Component to select language inside a container (Full CSS Only)
1088
	 *
1089
	 * @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')
1090
	 * @param	Translate		$weblangs				Language Object
1091
	 * @param	string			$morecss				More CSS class on component
1092
	 * @param	string			$htmlname				Suffix for HTML name
1093
	 * @return 	string									HTML select component
1094
	 */
1095
	public function componentSelectLang($languagecodes, $weblangs, $morecss='', $htmlname='')
1096
	{
1097
		global $websitepagefile, $website;
1098
1099
		if (! is_object($weblangs)) return 'ERROR componentSelectLang called with parameter $weblangs not defined';
1100
1101
		// Load tmppage if we have $websitepagefile defined
1102
		$tmppage=new WebsitePage($this->db);
1103
1104
		$pageid = 0;
1105
		if (! empty($websitepagefile))
1106
		{
1107
			$pageid = str_replace(array('.tpl.php', 'page'), array('', ''), basename($websitepagefile));
1108
			if ($pageid > 0)
1109
			{
1110
				$tmppage->fetch($pageid);
1111
			}
1112
		}
1113
1114
		// Fill with existing translation, nothing if none
1115
		if (! is_array($languagecodes) && $pageid > 0)
1116
		{
1117
			$languagecodes = array();
1118
1119
			$sql ="SELECT wp.rowid, wp.lang, wp.pageurl, wp.fk_page";
1120
			$sql.=" FROM ".MAIN_DB_PREFIX."website_page as wp";
1121
			$sql.=" WHERE wp.fk_website = ".$website->id;
1122
			$sql.=" AND (wp.fk_page = ".$pageid." OR wp.rowid  = ".$pageid;
1123
			if ($tmppage->fk_page > 0) $sql.=" OR wp.fk_page = ".$tmppage->fk_page." OR wp.rowid = ".$tmppage->fk_page;
1124
			$sql.=")";
1125
1126
			$resql = $this->db->query($sql);
1127
			if ($resql)
1128
			{
1129
				while ($obj = $this->db->fetch_object($resql))
1130
				{
1131
					$newlang = $obj->lang;
1132
					if ($obj->rowid == $pageid) $newlang = $obj->lang;
1133
					if (! in_array($newlang, $languagecodes)) $languagecodes[]=$newlang;
1134
				}
1135
			}
1136
		}
1137
		// Now $languagecodes is always an array
1138
1139
		$languagecodeselected= $weblangs->defaultlang;	// Because we must init with a value, but real value is the lang of main parent container
1140
		if (! empty($websitepagefile))
1141
		{
1142
			$pageid = str_replace(array('.tpl.php', 'page'), array('', ''), basename($websitepagefile));
1143
			if ($pageid > 0)
1144
			{
1145
1146
				$languagecodeselected=$tmppage->lang;
1147
				if (! in_array($tmppage->lang, $languagecodes)) $languagecodes[]=$tmppage->lang;	// We add language code of page into combo list
1148
			}
1149
		}
1150
1151
		$weblangs->load('languages');
1152
		//var_dump($weblangs->defaultlang);
1153
1154
		$url = $_SERVER["REQUEST_URI"];
1155
		$url = preg_replace('/(\?|&)l=([a-zA-Z_]*)/', '', $url);	// We remove param l from url
1156
		//$url = preg_replace('/(\?|&)lang=([a-zA-Z_]*)/', '', $url);	// We remove param lang from url
1157
		$url.= (preg_match('/\?/', $url) ? '&' : '?').'l=';
1158
1159
		$HEIGHTOPTION=40;
1160
		$MAXHEIGHT = 4 * $HEIGHTOPTION;
1161
		$nboflanguage = count($languagecodes);
1162
1163
		$out ='<!-- componentSelectLang'.$htmlname.' -->'."\n";
1164
1165
		$out.= '<style>';
1166
		$out.= '.componentSelectLang'.$htmlname.':hover { height: '.min($MAXHEIGHT, ($HEIGHTOPTION * $nboflanguage)).'px; overflow-x: hidden; overflow-y: '.((($HEIGHTOPTION * $nboflanguage) > $MAXHEIGHT) ? ' scroll' : 'hidden').'; }'."\n";
1167
		$out.= '.componentSelectLang'.$htmlname.' li { line-height: '.$HEIGHTOPTION.'px; }'."\n";
1168
		$out.= '.componentSelectLang'.$htmlname.' {
1169
			display: inline-block;
1170
			padding: 0;
1171
			height: '.$HEIGHTOPTION.'px;
1172
			overflow: hidden;
1173
			transition: all .3s ease;
1174
			margin: 0 50px 0 0;
1175
			vertical-align: top;
1176
		}
1177
		.componentSelectLang'.$htmlname.':hover, .componentSelectLang'.$htmlname.':hover a { background-color: #fff; color: #000 !important; }
1178
		ul.componentSelectLang'.$htmlname.' { width: 150px; }
1179
		ul.componentSelectLang'.$htmlname.':hover .fa { visibility: hidden; }
1180
		.componentSelectLang'.$htmlname.' a { text-decoration: none; width: 100%; }
1181
		.componentSelectLang'.$htmlname.' li { display: block; padding: 0px 20px; }
1182
		.componentSelectLang'.$htmlname.' li:hover { background-color: #EEE; }
1183
		';
1184
		$out.= '</style>';
1185
		$out.= '<ul class="componentSelectLang'.$htmlname.($morecss?' '.$morecss:'').'">';
1186
		if ($languagecodeselected)
1187
		{
1188
			$shortcode = strtolower(substr($languagecodeselected, -2));
1189
			$label = $weblangs->trans("Language_".$languagecodeselected);
1190
			if ($shortcode == 'us') $label = preg_replace('/\s*\(.*\)/', '', $label);
1191
			$out.= '<a href="'.$url.$languagecodeselected.'"><li><img height="12px" src="medias/image/common/flags/'.$shortcode.'.png" style="margin-right: 5px;"/>'.$label;
1192
			$out.= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
1193
			$out.= '</li></a>';
1194
		}
1195
		$i=0;
1196
		foreach($languagecodes as $languagecode)
1197
		{
1198
			if ($languagecode == $languagecodeselected) continue;	// Already output
1199
			$shortcode = strtolower(substr($languagecode, -2));
1200
			$label = $weblangs->trans("Language_".$languagecode);
1201
			if ($shortcode == 'us') $label = preg_replace('/\s*\(.*\)/', '', $label);
1202
			$out.= '<a href="'.$url.$languagecode.'"><li><img height="12px" src="medias/image/common/flags/'.$shortcode.'.png" style="margin-right: 5px;"/>'.$label;
1203
			if (empty($i) && empty($languagecodeselected)) $out.= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
1204
			$out.= '</li></a>';
1205
			$i++;
1206
		}
1207
		$out.= '</ul>';
1208
1209
		return $out;
1210
	}
1211
}
1212