Completed
Branch develop (09fbe4)
by
unknown
29:23
created

Website::exportWebSite()   F

Complexity

Conditions 19
Paths 404

Size

Total Lines 166

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 19
nc 404
nop 0
dl 0
loc 166
rs 0.9422
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;
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
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
Bug introduced by
The variable $conf does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

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)
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
Bug introduced by
The variable $filealias does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $fileoldalias does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

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;
0 ignored issues
show
Bug introduced by
The variable $newidforhome does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
631
		    $res = $object->update($user);
632
		    if (! $res > 0)
633
		    {
634
		        $error++;
635
		        setEventMessages($objectpage->error, $objectpage->errors, 'errors');
0 ignored issues
show
Bug introduced by
The variable $objectpage does not exist. Did you mean $object?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

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 = '';
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)
853
		{
854
			$objectpageold->newid=$i;
855
			$i++;
856
		}
857
		$i=1;
858
		foreach($listofpages as $pageid => $objectpageold)
859
		{
860
			// Search newid
861
			$newfk_page=0;
862
			foreach($listofpages as $pageid2 => $objectpageold2)
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)
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, 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->keywords)."', ";
893
			$line.= "'".$this->db->escape($objectpageold->status)."', ";
894
			$line.= "'".$this->db->idate($objectpageold->date_creation)."', ";
895
			$line.= "'".$this->db->idate($objectpageold->date_modification)."', ";
896
			$line.= "'".$this->db->escape($objectpageold->lang)."', ";
897
			$line.= ($objectpageold->import_key ? "'".$this->db->escape($objectpageold->import_key)."'" : "null").", ";
898
			$line.= "'".$this->db->escape($objectpageold->grabbed_from)."', ";
899
			$line.= "'".$this->db->escape($objectpageold->type_container)."', ";
900
901
			$stringtoexport = $objectpageold->htmlheader;
902
			$stringtoexport = str_replace(array("\r\n","\r","\n"), "__N__", $stringtoexport);
903
			$stringtoexport = str_replace('file=image/'.$website->ref.'/', "file=image/__WEBSITE_KEY__/", $stringtoexport);
904
			$stringtoexport = str_replace('file=js/'.$website->ref.'/', "file=js/__WEBSITE_KEY__/", $stringtoexport);
905
			$stringtoexport = str_replace('medias/image/'.$website->ref.'/', "medias/image/__WEBSITE_KEY__/", $stringtoexport);
906
			$stringtoexport = str_replace('medias/js/'.$website->ref.'/', "medias/js/__WEBSITE_KEY__/", $stringtoexport);
907
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_small, "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__", $stringtoexport);
908
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_mini, "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__", $stringtoexport);
909
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo, "file=logos%2Fthumbs%2F__LOGO_KEY__", $stringtoexport);
910
			$line.= "'".$this->db->escape(str_replace(array("\r\n","\r","\n"), "__N__", $stringtoexport))."', ";	// Replace \r \n to have record on 1 line
911
912
			$stringtoexport = $objectpageold->content;
913
			$stringtoexport = str_replace(array("\r\n","\r","\n"), "__N__", $stringtoexport);
914
			$stringtoexport = str_replace('file=image/'.$website->ref.'/', "file=image/__WEBSITE_KEY__/", $stringtoexport);
915
			$stringtoexport = str_replace('file=js/'.$website->ref.'/', "file=js/__WEBSITE_KEY__/", $stringtoexport);
916
			$stringtoexport = str_replace('medias/image/'.$website->ref.'/', "medias/image/__WEBSITE_KEY__/", $stringtoexport);
917
			$stringtoexport = str_replace('medias/js/'.$website->ref.'/', "medias/js/__WEBSITE_KEY__/", $stringtoexport);
918
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_small, "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__", $stringtoexport);
919
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_mini, "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__", $stringtoexport);
920
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo, "file=logos%2Fthumbs%2F__LOGO_KEY__", $stringtoexport);
921
			$line.= "'".$this->db->escape($stringtoexport)."'";		// Replace \r \n to have record on 1 line
922
			$line.= ");";
923
			$line.= "\n";
924
			fputs($fp, $line);
925
926
			// Add line to update home page id during import
927
			//var_dump($this->fk_default_home.' - '.$objectpageold->id.' - '.$objectpageold->newid);exit;
928
			if ($this->fk_default_home > 0 && ($objectpageold->id == $this->fk_default_home) && ($objectpageold->newid > 0))	// This is the record with home page
929
			{
930
				$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__;";
931
				$line.= "\n";
932
				fputs($fp, $line);
933
			}
934
		}
935
936
		fclose($fp);
937
		if (! empty($conf->global->MAIN_UMASK))
938
			@chmod($filesql, octdec($conf->global->MAIN_UMASK));
939
940
		// Build zip file
941
		$filedir  = $conf->website->dir_temp.'/'.$website->ref.'/.';
942
		$fileglob = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-*.zip';
943
		$filename = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-'.dol_print_date(dol_now(),'dayhourlog').'.zip';
944
945
		dol_delete_file($fileglob, 0);
946
		dol_compress_file($filedir, $filename, 'zip');
947
948
		return $filename;
949
	}
950
951
952
	/**
953
	 * Open a zip with all data of web site and load it into database.
954
	 *
955
	 * @param 	string		$pathtofile		Path of zip file
956
	 * @return  int							<0 if KO, Id of new website if OK
957
	 */
958
	function importWebSite($pathtofile)
959
	{
960
		global $conf, $mysoc;
961
962
		$error = 0;
963
964
		$object = $this;
965
		if (empty($object->ref))
966
		{
967
			$this->error = 'Function importWebSite called on object not loaded (object->ref is empty)';
968
			return -1;
969
		}
970
971
		dol_delete_dir_recursive(dirname($pathtofile).'/'.$object->ref);
972
		dol_mkdir(dirname($pathtofile).'/'.$object->ref);
973
974
		$filename = basename($pathtofile);
975
		if (! preg_match('/^website_(.*)-(.*)$/', $filename, $reg))
976
		{
977
			$this->errors[]='Bad format for filename '.$filename.'. Must be website_XXX-VERSION.';
978
			return -1;
979
		}
980
981
		$result = dol_uncompress($pathtofile, $conf->website->dir_temp.'/'.$object->ref);
982
		if (! empty($result['error']))
983
		{
984
			$this->errors[]='Failed to unzip file '.$pathtofile.'.';
985
			return -1;
986
		}
987
988
989
		dolCopyDir($conf->website->dir_temp.'/'.$object->ref.'/containers', $conf->website->dir_output.'/'.$object->ref, 0, 1);	// Overwrite if exists
990
991
		// Now generate the master.inc.php page
992
		$filemaster=$conf->website->dir_output.'/'.$object->ref.'/master.inc.php';
993
		$result = dolSaveMasterFile($filemaster);
994
		if (! $result)
995
		{
996
			$this->errors[]='Failed to write file '.$filemaster;
997
			$error++;
998
		}
999
1000
		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
1001
		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
1002
1003
		$sqlfile = $conf->website->dir_temp.'/'.$object->ref.'/website_pages.sql';
1004
1005
		$arrayreplacement = array();
1006
		$arrayreplacement['__WEBSITE_ID__'] = $object->id;
1007
		$arrayreplacement['__WEBSITE_KEY__'] = $object->ref;
1008
		$arrayreplacement['__N__'] = $this->db->escape("\n");			// Restore \n
1009
		$arrayreplacement['__LOGO_SMALL_KEY__'] = $this->db->escape($mysoc->logo_small);
1010
		$arrayreplacement['__LOGO_MINI_KEY__'] = $this->db->escape($mysoc->logo_mini);
1011
		$arrayreplacement['__LOGO_KEY__'] = $this->db->escape($mysoc->logo);
1012
		$result = dolReplaceInFile($sqlfile, $arrayreplacement);
1013
1014
		$this->db->begin();
1015
1016
		// Search the $maxrowid because we need it later
1017
		$sqlgetrowid='SELECT MAX(rowid) as max from '.MAIN_DB_PREFIX.'website_page';
1018
		$resql=$this->db->query($sqlgetrowid);
1019
		if ($resql)
1020
		{
1021
			$obj=$this->db->fetch_object($resql);
1022
			$maxrowid=$obj->max;
1023
		}
1024
1025
		// Load sql record
1026
		$runsql = run_sql($sqlfile, 1, '', 0, '', 'none', 0, 1);	// The maxrowid of table is searched into this function two
1027
		if ($runsql <= 0)
1028
		{
1029
			$this->errors[]='Failed to load sql file '.$sqlfile;
1030
			$error++;
1031
		}
1032
1033
		$objectpagestatic = new WebsitePage($this->db);
1034
1035
		// Make replacement of IDs
1036
		$fp = fopen($sqlfile,"r");
1037
		if ($fp)
1038
		{
1039
			while (! feof($fp))
1040
			{
1041
				// Warning fgets with second parameter that is null or 0 hang.
1042
				$buf = fgets($fp, 65000);
1043
				if (preg_match('/^-- Page ID (\d+)\s[^\s]+\s(\d+).*Aliases\s(.*)\s--;/i', $buf, $reg))
1044
				{
1045
					$oldid = $reg[1];
1046
					$newid = ($reg[2] + $maxrowid);
0 ignored issues
show
Bug introduced by
The variable $maxrowid does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1047
					$aliasesarray = explode(',', $reg[3]);
1048
1049
					$objectpagestatic->fetch($newid);
1050
1051
					dol_syslog("Found ID ".$oldid." to replace with ID ".$newid." and shortcut aliases to create: ".$reg[3]);
1052
1053
					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);
1054
1055
					// The move is not enough, so we regenerate page
1056
					$filetpl=$conf->website->dir_output.'/'.$object->ref.'/page'.$newid.'.tpl.php';
1057
					dolSavePageContent($filetpl, $object, $objectpagestatic);
1058
1059
					// Regenerate alternative aliases pages
1060
					foreach($aliasesarray as $aliasshortcuttocreate)
1061
					{
1062
						$filealias=$conf->website->dir_output.'/'.$object->ref.'/'.$aliasshortcuttocreate.'.php';
1063
						dolSavePageAlias($filealias, $object, $objectpagestatic);
1064
					}
1065
				}
1066
			}
1067
		}
1068
1069
		if ($error)
1070
		{
1071
			$this->db->rollback();
1072
			return -1;
1073
		}
1074
		else
1075
		{
1076
			$this->db->commit();
1077
			return $object->id;
1078
		}
1079
	}
1080
1081
	/**
1082
	 * Component to select language (Full CSS Only)
1083
	 *
1084
	 * @param	array		$languagecodes			Language codes array. Example: array('en_US','fr_FR','de_DE','es_ES')
1085
	 * @param	Translate	$weblangs				Language Object
1086
	 * @param	string		$morecss				More CSS class on component
1087
	 * @param	string		$htmlname				Suffix for HTML name
1088
	 * @return 	string								HTML select component
1089
	 */
1090
	public function componentSelectLang($languagecodes, $weblangs, $morecss='', $htmlname='')
1091
	{
1092
		if (! is_object($weblangs)) return 'ERROR componentSelectLang called with parameter $weblangs not defined';
1093
1094
		$languagecodeselected = $weblangs->defaultlang;
1095
		$weblangs->load('languages');
1096
1097
		$url = $_SERVER["REQUEST_URI"];
1098
		$url = preg_replace('/(\?|&)l=([a-zA-Z_]*)/', '', $url);	// We remove param l from url
1099
		//$url = preg_replace('/(\?|&)lang=([a-zA-Z_]*)/', '', $url);	// We remove param lang from url
1100
		$url.= (preg_match('/\?/', $url) ? '&' : '?').'l=';
1101
1102
		$HEIGHTOPTION=40;
1103
		$MAXHEIGHT = 4 * $HEIGHTOPTION;
1104
		$nboflanguage = count($languagecodes);
1105
1106
		$out.='<!-- componentSelectLang'.$htmlname.' -->'."\n";
0 ignored issues
show
Bug introduced by
The variable $out does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1107
		$out.= '<style>';
1108
		$out.= '.componentSelectLang'.$htmlname.':hover { height: '.min($MAXHEIGHT, ($HEIGHTOPTION * $nboflanguage)).'px; overflow-x: hidden; overflow-y: '.((($HEIGHTOPTION * $nboflanguage) > $MAXHEIGHT) ? ' scroll' : 'hidden').'; }'."\n";
1109
		$out.= '.componentSelectLang'.$htmlname.' li { line-height: '.$HEIGHTOPTION.'px; }'."\n";
1110
		$out.= '.componentSelectLang'.$htmlname.' {
1111
			display: inline-block;
1112
			padding: 0;
1113
			height: '.$HEIGHTOPTION.'px;
1114
			overflow: hidden;
1115
			transition: all .3s ease;
1116
			margin: 0 50px 0 0;
1117
			vertical-align: top;
1118
		}
1119
		.componentSelectLang'.$htmlname.':hover, .componentSelectLang'.$htmlname.':hover a { background-color: #fff; color: #000 !important; }
1120
		ul.componentSelectLang'.$htmlname.' { width: 150px; }
1121
		ul.componentSelectLang'.$htmlname.':hover .fa { visibility: hidden; }
1122
		.componentSelectLang'.$htmlname.' a { text-decoration: none; width: 100%; }
1123
		.componentSelectLang'.$htmlname.' li { display: block; padding: 0px 20px; }
1124
		.componentSelectLang'.$htmlname.' li:hover { background-color: #EEE; }
1125
		';
1126
		$out.= '</style>';
1127
		$out.= '<ul class="componentSelectLang'.$htmlname.($morecss?' '.$morecss:'').'">';
1128
		if ($languagecodeselected)
1129
		{
1130
			$shortcode = strtolower(substr($languagecodeselected, -2));
1131
			$label = $weblangs->trans("Language_".$languagecodeselected);
1132
			if ($shortcode == 'us') $label = preg_replace('/\s*\(.*\)/', '', $label);
1133
			$out.= '<a href="'.$url.$languagecodeselected.'"><li><img height="12px" src="medias/image/common/flags/'.$shortcode.'.png" style="margin-right: 5px;"/>'.$label;
1134
			$out.= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
1135
			$out.= '</li></a>';
1136
		}
1137
		$i=0;
1138
		foreach($languagecodes as $languagecode)
1139
		{
1140
			if ($languagecode == $languagecodeselected) continue;	// Already output
1141
			$shortcode = strtolower(substr($languagecode, -2));
1142
			$label = $weblangs->trans("Language_".$languagecode);
1143
			if ($shortcode == 'us') $label = preg_replace('/\s*\(.*\)/', '', $label);
1144
			$out.= '<a href="'.$url.$languagecode.'"><li><img height="12px" src="medias/image/common/flags/'.$shortcode.'.png" style="margin-right: 5px;"/>'.$label;
1145
			if (empty($i) && empty($languagecodeselected)) $out.= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
1146
			$out.= '</li></a>';
1147
			$i++;
1148
		}
1149
		$out.= '</ul>';
1150
1151
		return $out;
1152
	}
1153
}
1154