Completed
Branch develop (ab22c9)
by
unknown
39:06
created

Website::importWebSite()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 61

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 7
nop 1
dl 0
loc 61
rs 8.2286
c 0
b 0
f 0

How to fix   Long Method   

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-2012  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) ---Put here your own copyright and developer email---
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
	 * @var string Name of table without prefix where object is stored
44
	 */
45
	public $table_element = 'website';
46
	/**
47
	 * @var array  Does website support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
48
	 */
49
	public $ismultientitymanaged = 1;
50
	/**
51
	 * @var string String with name of icon for website. Must be the part after the 'object_' into object_myobject.png
52
	 */
53
	public $picto = 'globe';
54
55
	/**
56
	 * @var int
57
	 */
58
	public $entity;
59
	/**
60
	 * @var string
61
	 */
62
	public $ref;
63
	/**
64
	 * @var string
65
	 */
66
	public $description;
67
	/**
68
	 * @var int
69
	 */
70
	public $status;
71
	/**
72
	 * @var mixed
73
	 */
74
	public $date_creation;
75
	/**
76
	 * @var mixed
77
	 */
78
	public $tms = '';
79
	/**
80
	 * @var integer
81
	 */
82
	public $fk_default_home;
83
	/**
84
	 * @var string
85
	 */
86
	public $virtualhost;
87
88
89
	/**
90
	 * Constructor
91
	 *
92
	 * @param DoliDb $db Database handler
93
	 */
94
	public function __construct(DoliDB $db)
95
	{
96
		$this->db = $db;
97
		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...
98
	}
99
100
	/**
101
	 * Create object into database
102
	 *
103
	 * @param  User $user      User that creates
104
	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
105
	 *
106
	 * @return int <0 if KO, Id of created object if OK
107
	 */
108
	public function create(User $user, $notrigger = false)
109
	{
110
		global $conf;
111
112
		dol_syslog(__METHOD__, LOG_DEBUG);
113
114
		$error = 0;
115
		$now=dol_now();
116
117
		// Clean parameters
118
		if (isset($this->entity)) {
119
			 $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...
120
		}
121
		if (isset($this->ref)) {
122
			 $this->ref = trim($this->ref);
123
		}
124
		if (isset($this->description)) {
125
			 $this->description = trim($this->description);
126
		}
127
		if (isset($this->status)) {
128
			 $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...
129
		}
130
		if (empty($this->date_creation)) $this->date_creation = $now;
131
		if (empty($this->date_modification)) $this->date_modification = $now;
132
133
		// Check parameters
134
		if (empty($this->entity)) { $this->entity = $conf->entity; }
135
136
		// Insert request
137
		$sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . '(';
138
		$sql.= 'entity,';
139
		$sql.= 'ref,';
140
		$sql.= 'description,';
141
		$sql.= 'status,';
142
		$sql.= 'fk_default_home,';
143
		$sql.= 'virtualhost,';
144
		$sql.= 'fk_user_create,';
145
		$sql.= 'date_creation,';
146
		$sql.= 'tms';
147
		$sql .= ') VALUES (';
148
		$sql .= ' '.((empty($this->entity) && $this->entity != '0')?'NULL':$this->entity).',';
149
		$sql .= ' '.(! isset($this->ref)?'NULL':"'".$this->db->escape($this->ref)."'").',';
150
		$sql .= ' '.(! isset($this->description)?'NULL':"'".$this->db->escape($this->description)."'").',';
151
		$sql .= ' '.(! isset($this->status)?'NULL':$this->status).',';
152
		$sql .= ' '.(! isset($this->fk_default_home)?'NULL':$this->fk_default_home).',';
153
		$sql .= ' '.(! isset($this->virtualhost)?'NULL':"'".$this->db->escape($this->virtualhost)."'").",";
154
		$sql .= ' '.(! isset($this->fk_user_create)?$user->id:$this->fk_user_create).',';
155
		$sql .= ' '.(! isset($this->date_creation) || dol_strlen($this->date_creation)==0?'NULL':"'".$this->db->idate($this->date_creation)."'").",";
156
		$sql .= ' '.(! isset($this->date_modification) || dol_strlen($this->date_modification)==0?'NULL':"'".$this->db->idate($this->date_creation)."'");
157
		$sql .= ')';
158
159
		$this->db->begin();
160
161
		$resql = $this->db->query($sql);
162
		if (!$resql) {
163
			$error ++;
164
			$this->errors[] = 'Error ' . $this->db->lasterror();
165
			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
166
		}
167
168
		if (!$error) {
169
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
170
171
			if (!$notrigger) {
172
				// Uncomment this and change MYOBJECT to your own tag if you
173
				// want this action to call a trigger.
174
175
				//// Call triggers
176
				//$result=$this->call_trigger('MYOBJECT_CREATE',$user);
177
				//if ($result < 0) $error++;
178
				//// End call triggers
179
			}
180
		}
181
182
		// Commit or rollback
183
		if ($error) {
184
			$this->db->rollback();
185
186
			return - 1 * $error;
187
		} else {
188
			$this->db->commit();
189
190
			return $this->id;
191
		}
192
	}
193
194
	/**
195
	 * Load object in memory from the database
196
	 *
197
	 * @param 	int    $id  	Id object
198
	 * @param 	string $ref 	Ref
199
	 * @return 	int 			<0 if KO, 0 if not found, >0 if OK
200
	 */
201
	public function fetch($id, $ref = null)
202
	{
203
		dol_syslog(__METHOD__, LOG_DEBUG);
204
205
		$sql = 'SELECT';
206
		$sql .= ' t.rowid,';
207
		$sql .= " t.entity,";
208
		$sql .= " t.ref,";
209
		$sql .= " t.description,";
210
		$sql .= " t.status,";
211
		$sql .= " t.fk_default_home,";
212
		$sql .= " t.virtualhost,";
213
		$sql .= " t.fk_user_create,";
214
		$sql .= " t.fk_user_modif,";
215
		$sql .= " t.date_creation,";
216
		$sql .= " t.tms as date_modification";
217
		$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
218
		$sql .= ' WHERE t.entity IN ('.getEntity('website').')';
219
		if (null !== $ref) {
220
			$sql .= " AND t.ref = '" . $this->db->escape($ref) . "'";
221
		} else {
222
			$sql .= ' AND t.rowid = ' . $id;
223
		}
224
225
		$resql = $this->db->query($sql);
226
		if ($resql) {
227
			$numrows = $this->db->num_rows($resql);
228
			if ($numrows) {
229
				$obj = $this->db->fetch_object($resql);
230
231
				$this->id = $obj->rowid;
232
233
				$this->entity = $obj->entity;
234
				$this->ref = $obj->ref;
235
				$this->description = $obj->description;
236
				$this->status = $obj->status;
237
				$this->fk_default_home = $obj->fk_default_home;
238
				$this->virtualhost = $obj->virtualhost;
239
				$this->fk_user_create = $obj->fk_user_create;
240
				$this->fk_user_modif = $obj->fk_user_modif;
241
				$this->date_creation = $this->db->jdate($obj->date_creation);
242
				$this->date_modification = $this->db->jdate($obj->date_modification);
243
			}
244
			$this->db->free($resql);
245
246
			if ($numrows > 0) {
247
				// Lines
248
				$this->fetchLines();
249
			}
250
251
			if ($numrows > 0) {
252
				return 1;
253
			} else {
254
				return 0;
255
			}
256
		} else {
257
			$this->errors[] = 'Error ' . $this->db->lasterror();
258
			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
259
260
			return - 1;
261
		}
262
	}
263
264
	/**
265
	 * Load object lines in memory from the database
266
	 *
267
	 * @return int         <0 if KO, 0 if not found, >0 if OK
268
	 */
269
	public function fetchLines()
270
	{
271
		$this->lines=array();
272
273
		// Load lines with object MyObjectLine
274
275
		return count($this->lines)?1:0;
276
	}
277
278
279
	/**
280
	 * Load object in memory from the database
281
	 *
282
	 * @param string $sortorder Sort Order
283
	 * @param string $sortfield Sort field
284
	 * @param int    $limit     offset limit
285
	 * @param int    $offset    offset limit
286
	 * @param array  $filter    filter array
287
	 * @param string $filtermode filter mode (AND or OR)
288
	 *
289
	 * @return int <0 if KO, >0 if OK
290
	 */
291
	public function fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, array $filter = array(), $filtermode='AND')
292
	{
293
		dol_syslog(__METHOD__, LOG_DEBUG);
294
295
		$sql = 'SELECT';
296
		$sql .= ' t.rowid,';
297
		$sql .= " t.entity,";
298
		$sql .= " t.ref,";
299
		$sql .= " t.description,";
300
		$sql .= " t.status,";
301
		$sql .= " t.fk_default_home,";
302
		$sql .= " t.virtualhost,";
303
		$sql .= " t.fk_user_create,";
304
		$sql .= " t.fk_user_modif,";
305
		$sql .= " t.date_creation,";
306
		$sql .= " t.tms as date_modification";
307
		$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element. ' as t';
308
		$sql .= ' WHERE t.entity IN ('.getEntity('website').')';
309
		// Manage filter
310
		$sqlwhere = array();
311
		if (count($filter) > 0) {
312
			foreach ($filter as $key => $value) {
313
				$sqlwhere [] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\'';
314
			}
315
		}
316
		if (count($sqlwhere) > 0) {
317
			$sql .= ' AND ' . implode(' '.$filtermode.' ', $sqlwhere);
318
		}
319
320
		if (!empty($sortfield)) {
321
			$sql .= $this->db->order($sortfield,$sortorder);
322
		}
323
		if (!empty($limit)) {
324
		 $sql .=  ' ' . $this->db->plimit($limit, $offset);
325
		}
326
		$this->records = array();
327
328
		$resql = $this->db->query($sql);
329
		if ($resql) {
330
			$num = $this->db->num_rows($resql);
331
332
			while ($obj = $this->db->fetch_object($resql)) {
333
				$line = new self($this->db);
334
335
				$line->id = $obj->rowid;
336
337
				$line->entity = $obj->entity;
338
				$line->ref = $obj->ref;
339
				$line->description = $obj->description;
340
				$line->status = $obj->status;
341
				$line->fk_default_home = $obj->fk_default_home;
342
				$line->virtualhost = $obj->virtualhost;
343
				$this->fk_user_create = $obj->fk_user_create;
344
				$this->fk_user_modif = $obj->fk_user_modif;
345
				$line->date_creation = $this->db->jdate($obj->date_creation);
346
				$line->date_modification = $this->db->jdate($obj->date_modification);
347
348
				$this->records[$line->id] = $line;
349
			}
350
			$this->db->free($resql);
351
352
			return $num;
353
		} else {
354
			$this->errors[] = 'Error ' . $this->db->lasterror();
355
			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
356
357
			return - 1;
358
		}
359
	}
360
361
	/**
362
	 * Update object into database
363
	 *
364
	 * @param  User $user      User that modifies
365
	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
366
	 *
367
	 * @return int <0 if KO, >0 if OK
368
	 */
369
	public function update(User $user, $notrigger = false)
370
	{
371
		$error = 0;
372
373
		dol_syslog(__METHOD__, LOG_DEBUG);
374
375
		// Clean parameters
376
377
		if (isset($this->entity)) {
378
			 $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...
379
		}
380
		if (isset($this->ref)) {
381
			 $this->ref = trim($this->ref);
382
		}
383
		if (isset($this->description)) {
384
			 $this->description = trim($this->description);
385
		}
386
		if (isset($this->status)) {
387
			 $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...
388
		}
389
390
		// Check parameters
391
		// Put here code to add a control on parameters values
392
393
		// Update request
394
		$sql = 'UPDATE ' . MAIN_DB_PREFIX . $this->table_element . ' SET';
395
		$sql .= ' entity = '.(isset($this->entity)?$this->entity:"null").',';
396
		$sql .= ' ref = '.(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").',';
397
		$sql .= ' description = '.(isset($this->description)?"'".$this->db->escape($this->description)."'":"null").',';
398
		$sql .= ' status = '.(isset($this->status)?$this->status:"null").',';
399
		$sql .= ' fk_default_home = '.(($this->fk_default_home > 0)?$this->fk_default_home:"null").',';
400
		$sql .= ' virtualhost = '.(($this->virtualhost != '')?"'".$this->db->escape($this->virtualhost)."'":"null").',';
401
		$sql .= ' fk_user_modif = '.(! isset($this->fk_user_modif) ? $user->id : $this->fk_user_modif).',';
402
		$sql .= ' date_creation = '.(! isset($this->date_creation) || dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null');
403
		$sql .= ', tms = '.(dol_strlen($this->date_modification) != 0 ? "'".$this->db->idate($this->date_modification)."'" : "'".$this->db->idate(dol_now())."'");
404
		$sql .= ' WHERE rowid=' . $this->id;
405
406
		$this->db->begin();
407
408
		$resql = $this->db->query($sql);
409
		if (!$resql) {
410
			$error ++;
411
			$this->errors[] = 'Error ' . $this->db->lasterror();
412
			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
413
		}
414
415
		if (!$error && !$notrigger) {
416
			// Uncomment this and change MYOBJECT to your own tag if you
417
			// want this action calls a trigger.
418
419
			//// Call triggers
420
			//$result=$this->call_trigger('MYOBJECT_MODIFY',$user);
421
			//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
422
			//// End call triggers
423
		}
424
425
		// Commit or rollback
426
		if ($error) {
427
			$this->db->rollback();
428
429
			return - 1 * $error;
430
		} else {
431
			$this->db->commit();
432
433
			return 1;
434
		}
435
	}
436
437
	/**
438
	 * Delete object in database
439
	 *
440
	 * @param User $user      User that deletes
441
	 * @param bool $notrigger false=launch triggers after, true=disable triggers
442
	 *
443
	 * @return int <0 if KO, >0 if OK
444
	 */
445
	public function delete(User $user, $notrigger = false)
446
	{
447
		dol_syslog(__METHOD__, LOG_DEBUG);
448
449
		$error = 0;
450
451
		$this->db->begin();
452
453
		if (!$error) {
454
			if (!$notrigger) {
455
				// Uncomment this and change MYOBJECT to your own tag if you
456
				// want this action calls a trigger.
457
458
				//// Call triggers
459
				//$result=$this->call_trigger('MYOBJECT_DELETE',$user);
460
				//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
461
				//// End call triggers
462
			}
463
		}
464
465
		if (!$error) {
466
			$sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element;
467
			$sql .= ' WHERE rowid=' . $this->id;
468
469
			$resql = $this->db->query($sql);
470
			if (!$resql) {
471
				$error ++;
472
				$this->errors[] = 'Error ' . $this->db->lasterror();
473
				dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
474
			}
475
		}
476
477
		// Commit or rollback
478
		if ($error) {
479
			$this->db->rollback();
480
481
			return - 1 * $error;
482
		} else {
483
			$this->db->commit();
484
485
			return 1;
486
		}
487
	}
488
489
	/**
490
	 * Load an object from its id and create a new one in database.
491
	 * This copy website directories, regenerate all the pages + alias pages and recreate the medias link.
492
	 *
493
	 * @param	User	$user		User making the clone
494
	 * @param 	int 	$fromid 	Id of object to clone
495
	 * @param	string	$newref		New ref
496
	 * @param	string	$newlang	New language
497
	 * @return 	mixed 				New object created, <0 if KO
498
	 */
499
	public function createFromClone($user, $fromid, $newref, $newlang='')
500
	{
501
        global $hookmanager, $langs;
502
		global $dolibarr_main_data_root;
503
504
		$error=0;
505
506
        dol_syslog(__METHOD__, LOG_DEBUG);
507
508
		$object = new self($this->db);
509
510
        // Check no site with ref exists
511
		if ($object->fetch(0, $newref) > 0)
512
		{
513
			$this->error='NewRefIsAlreadyUsed';
514
			return -1;
515
		}
516
517
		$this->db->begin();
518
519
		// Load source object
520
		$object->fetch($fromid);
521
522
		$oldidforhome=$object->fk_default_home;
523
524
		$pathofwebsiteold=$dolibarr_main_data_root.'/website/'.$object->ref;
525
		$pathofwebsitenew=$dolibarr_main_data_root.'/website/'.$newref;
526
		dol_delete_dir_recursive($pathofwebsitenew);
527
528
		$fileindex=$pathofwebsitenew.'/index.php';
529
530
		// Reset some properties
531
		unset($object->id);
532
		unset($object->fk_user_creat);
533
		unset($object->import_key);
534
535
		// Clear fields
536
		$object->ref=$newref;
537
		$object->fk_default_home=0;
538
		$object->virtualhost='';
539
540
		// Create clone
541
		$object->context['createfromclone'] = 'createfromclone';
542
		$result = $object->create($user);
543
		if ($result < 0) {
544
			$error ++;
545
			$this->errors = $object->errors;
546
			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
547
		}
548
549
		if (! $error)
550
		{
551
			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...
552
553
			// Check symlink to medias and restore it if ko
554
			$pathtomedias=DOL_DATA_ROOT.'/medias';
555
			$pathtomediasinwebsite=$pathofwebsitenew.'/medias';
556
			if (! is_link(dol_osencode($pathtomediasinwebsite)))
557
			{
558
				dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite);
559
				dol_mkdir(dirname($pathtomediasinwebsite));     // To be sure dir for website exists
560
				$result = symlink($pathtomedias, $pathtomediasinwebsite);
561
			}
562
563
			$newidforhome=0;
564
565
			// Duplicate pages
566
			$objectpages = new WebsitePage($this->db);
567
			$listofpages = $objectpages->fetchAll($fromid);
568
			foreach($listofpages as $pageid => $objectpageold)
569
			{
570
				// Delete old file
571
				$filetplold=$pathofwebsitenew.'/page'.$pageid.'.tpl.php';
572
				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...
573
				dol_delete_file($filetplold);
574
575
				// Create new file
576
				$objectpagenew = $objectpageold->createFromClone($user, $pageid, $objectpageold->pageurl, '', 0, $object->id, 1);
577
				//print $pageid.' = '.$objectpageold->pageurl.' -> '.$objectpagenew->id.' = '.$objectpagenew->pageurl.'<br>';
578
				if (is_object($objectpagenew) && $objectpagenew->pageurl)
579
				{
580
		            $filealias=$pathofwebsitenew.'/'.$objectpagenew->pageurl.'.php';
581
					$filetplnew=$pathofwebsitenew.'/page'.$objectpagenew->id.'.tpl.php';
582
583
					// Save page alias
584
					$result=dolSavePageAlias($filealias, $object, $objectpagenew);
585
					if (! $result) setEventMessages('Failed to write file '.$filealias, null, 'errors');
586
587
					$result=dolSavePageContent($filetplnew, $object, $objectpagenew);
588
					if (! $result) setEventMessages('Failed to write file '.$filetplnew, null, 'errors');
589
590
					if ($pageid == $oldidforhome)
591
					{
592
						$newidforhome = $objectpagenew->id;
593
					}
594
				}
595
				else
596
				{
597
					setEventMessages($objectpageold->error, $objectpageold->errors, 'errors');
598
					$error++;
599
				}
600
			}
601
		}
602
603
		if (! $error)
604
		{
605
			// Restore id of home page
606
			$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...
607
		    $res = $object->update($user);
608
		    if (! $res > 0)
609
		    {
610
		        $error++;
611
		        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...
612
		    }
613
614
		    if (! $error)
615
		    {
616
		    	$filetpl=$pathofwebsitenew.'/page'.$newidforhome.'.tpl.php';
617
618
		    	// Generate the index.php page to be the home page
619
		    	//-------------------------------------------------
620
		    	$result = dolSaveIndexPage($pathofwebsitenew, $fileindex, $filetpl);
621
		    }
622
		}
623
624
		// End
625
		if (!$error) {
626
			$this->db->commit();
627
628
			return $object;
629
		} else {
630
			$this->db->rollback();
631
632
			return - 1;
633
		}
634
	}
635
636
	/**
637
	 *  Return a link to the user card (with optionaly the picto)
638
	 * 	Use this->id,this->lastname, this->firstname
639
	 *
640
	 *	@param	int		$withpicto			Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
641
	 *	@param	string	$option				On what the link point to
642
     *  @param	integer	$notooltip			1=Disable tooltip
643
     *  @param	int		$maxlen				Max length of visible user name
644
     *  @param  string  $morecss            Add more css on link
645
	 *	@return	string						String with URL
646
	 */
647
	function getNomUrl($withpicto=0, $option='', $notooltip=0, $maxlen=24, $morecss='')
648
	{
649
		global $langs, $conf, $db;
650
        global $dolibarr_main_authentication, $dolibarr_main_demo;
651
        global $menumanager;
652
653
654
        $result = '';
655
        $companylink = '';
656
657
        $label = '<u>' . $langs->trans("WebSite") . '</u>';
658
        $label.= '<div width="100%">';
659
        $label.= '<b>' . $langs->trans('Nom') . ':</b> ' . $this->ref;
660
661
        $linkstart = '<a href="'.DOL_URL_ROOT.'/website/card.php?id='.$this->id.'"';
662
        $linkstart.= ($notooltip?'':' title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip'.($morecss?' '.$morecss:'').'"');
663
        $linkstart.= '>';
664
		$linkend='</a>';
665
666
		$linkstart = $linkend = '';
667
668
        if ($withpicto)
669
        {
670
            $result.=($linkstart.img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?'':'class="classfortooltip"')).$linkend);
671
            if ($withpicto != 2) $result.=' ';
672
		}
673
		$result.= $linkstart . $this->ref . $linkend;
674
		return $result;
675
	}
676
677
	/**
678
	 *  Retourne le libelle du status d'un user (actif, inactif)
679
	 *
680
	 *  @param	int		$mode          0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
681
	 *  @return	string 			       Label of status
682
	 */
683
	function getLibStatut($mode=0)
684
	{
685
		return $this->LibStatut($this->status,$mode);
686
	}
687
688
	/**
689
	 *  Renvoi le libelle d'un status donne
690
	 *
691
	 *  @param	int		$status        	Id status
692
	 *  @param  int		$mode          	0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
693
	 *  @return string 			       	Label of status
694
	 */
695
	function LibStatut($status,$mode=0)
696
	{
697
		global $langs;
698
699
		if ($mode == 0)
700
		{
701
			$prefix='';
702
			if ($status == 1) return $langs->trans('Enabled');
703
			if ($status == 0) return $langs->trans('Disabled');
704
		}
705
		if ($mode == 1)
706
		{
707
			if ($status == 1) return $langs->trans('Enabled');
708
			if ($status == 0) return $langs->trans('Disabled');
709
		}
710
		if ($mode == 2)
711
		{
712
			if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
713
			if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
714
		}
715
		if ($mode == 3)
716
		{
717
			if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4');
718
			if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5');
719
		}
720
		if ($mode == 4)
721
		{
722
			if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
723
			if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
724
		}
725
		if ($mode == 5)
726
		{
727
			if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4');
728
			if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5');
729
		}
730
	}
731
732
733
	/**
734
	 * Initialise object with example values
735
	 * Id must be 0 if object instance is a specimen
736
	 *
737
	 * @return void
738
	 */
739
	public function initAsSpecimen()
740
	{
741
	    global $user;
742
743
		$this->id = 0;
744
745
		$this->entity = 1;
746
		$this->ref = 'myspecimenwebsite';
747
		$this->description = 'A specimen website';
748
		$this->status = '';
749
		$this->fk_default_home = null;
750
		$this->virtualhost = 'http://myvirtualhost';
751
		$this->fk_user_create = $user->id;
752
		$this->fk_user_modif = $user->id;
753
		$this->date_creation = dol_now();
754
		$this->tms = dol_now();
755
756
757
	}
758
759
760
	/**
761
	 * Generate a zip with all data of web site.
762
	 *
763
	 * @return  string						Path to file with zip
764
	 */
765
	function exportWebSite()
766
	{
767
		global $conf;
768
769
		$website = $this;
770
771
		if (empty($website->id) || empty($website->ref))
772
		{
773
			setEventMessages("Website id or ref is not defined", null, 'errors');
774
			return '';
775
		}
776
777
		dol_syslog("Create temp dir ".$conf->website->dir_temp);
778
		dol_mkdir($conf->website->dir_temp);
779
		if (! is_writable($conf->website->dir_temp))
780
		{
781
			setEventMessages("Temporary dir ".$conf->website->dir_temp." is not writable", null, 'errors');
782
			return '';
783
		}
784
785
		$destdir = $conf->website->dir_temp.'/'.$website->ref;
786
787
		dol_syslog("Clear temp dir ".$destdir);
788
		$count=0; $countreallydeleted=0;
789
		$counttodelete = dol_delete_dir_recursive($destdir, $count, 1, 0, $countreallydeleted);
790
		if ($counttodelete != $countreallydeleted)
791
		{
792
			setEventMessages("Failed to clean temp directory ".$destdir, null, 'errors');
793
			return '';
794
		}
795
796
		$arrayreplacement=array();
797
798
		$srcdir = $conf->website->dir_output.'/'.$website->ref;
799
		$destdir = $conf->website->dir_temp.'/'.$website->ref.'/containers';
800
801
		dol_syslog("Copy content from ".$srcdir." into ".$destdir);
802
		dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacement);
803
804
		$srcdir = DOL_DATA_ROOT.'/medias/image/'.$website->ref;
805
		$destdir = $conf->website->dir_temp.'/'.$website->ref.'/medias/image/'.$website->ref;
806
807
		dol_syslog("Copy content from ".$srcdir." into ".$destdir);
808
		dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacement);
809
810
		$srcdir = DOL_DATA_ROOT.'/medias/js/'.$website->ref;
811
		$destdir = $conf->website->dir_temp.'/'.$website->ref.'/medias/js/'.$website->ref;
812
813
		dol_syslog("Copy content from ".$srcdir." into ".$destdir);
814
		dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacement);
815
816
		// Build sql file
817
		dol_syslog("Create containers dir");
818
		dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/containers');
819
820
		$filesql = $conf->website->dir_temp.'/'.$website->ref.'/website_pages.sql';
821
		$fp = fopen($filesql,"w");
822
		if (empty($fp))
823
		{
824
			setEventMessages("Failed to create file ".$filesql, null, 'errors');
825
			return '';
826
		}
827
828
		$objectpages = new WebsitePage($this->db);
829
		$listofpages = $objectpages->fetchAll($website->id);
830
831
		// Assign ->newid and ->newfk_page
832
		$i=1;
833
		foreach($listofpages as $pageid => $objectpageold)
834
		{
835
			$objectpageold->newid=$i;
836
			$i++;
837
		}
838
		$i=1;
839
		foreach($listofpages as $pageid => $objectpageold)
840
		{
841
			// Search newid
842
			$newfk_page=0;
843
			foreach($listofpages as $pageid2 => $objectpageold2)
844
			{
845
				if ($pageid2 == $objectpageold->fk_page)
846
				{
847
					$newfk_page = $objectpageold2->newid;
848
					break;
849
				}
850
			}
851
			$objectpageold->newfk_page=$newfk_page;
852
			$i++;
853
		}
854
		foreach($listofpages as $pageid => $objectpageold)
855
		{
856
			// Warning: We must keep llx_ here. It is a generic SQL.
857
			$line = 'INSERT INTO llx_website_page(rowid, fk_page, fk_website, pageurl, title, description, keywords, status, date_creation, tms, lang, import_key, grabbed_from, content)';
858
			$line.= " VALUES(";
859
			$line.= $objectpageold->newid."__+MAX_llx_website_page__, ";
860
			$line.= ($objectpageold->newfk_page ? $this->db->escape($objectpageold->newfk_page)."__+MAX_llx_website_page__" : "null").", ";
861
			$line.= "__WEBSITE_ID__, ";
862
			$line.= "'".$this->db->escape($objectpageold->pageurl)."', ";
863
			$line.= "'".$this->db->escape($objectpageold->title)."', ";
864
			$line.= "'".$this->db->escape($objectpageold->description)."', ";
865
			$line.= "'".$this->db->escape($objectpageold->keyword)."', ";
866
			$line.= "'".$this->db->escape($objectpageold->status)."', ";
867
			$line.= "'".$this->db->idate($objectpageold->date_creation)."', ";
868
			$line.= "'".$this->db->idate($objectpageold->date_modification)."', ";
869
			$line.= "'".$this->db->escape($objectpageold->lang)."', ";
870
			$line.= ($objectpageold->import_key ? "'".$this->db->escape($objectpageold->import_key)."'" : "null").", ";
871
			$line.= "'".$this->db->escape($objectpageold->grabbed_from)."', ";
872
			$line.= "'".$this->db->escape($objectpageold->content)."'";
873
			$line.= ");";
874
			$line.= "\n";
875
			fputs($fp, $line);
876
		}
877
878
		fclose($fp);
879
		if (! empty($conf->global->MAIN_UMASK))
880
			@chmod($filesql, octdec($conf->global->MAIN_UMASK));
881
882
		// Build zip file
883
		$filedir  = $conf->website->dir_temp.'/'.$website->ref.'/.';
884
		$fileglob = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-*.zip';
885
		$filename = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-'.dol_print_date(dol_now(),'dayhourlog').'.zip';
886
887
		dol_delete_file($fileglob, 0);
888
		dol_compress_file($filedir, $filename, 'zip');
889
890
		return $filename;
891
	}
892
893
894
	/**
895
	 * Open a zip with all data of web site and load it into database.
896
	 *
897
	 * @param 	string		$pathtofile		Path of zip file
898
	 * @return  int							<0 if KO, Id of new website if OK
899
	 */
900
	function importWebSite($pathtofile)
901
	{
902
		global $conf;
903
904
		$error = 0;
905
906
		$object = $this;
907
		if (empty($object->ref))
908
		{
909
			$this->error = 'Function importWebSite called on object not loaded (object->ref is empty)';
910
			return -1;
911
		}
912
913
		dol_delete_dir_recursive(dirname($pathtofile).'/'.$object->ref);
914
		dol_mkdir(dirname($pathtofile).'/'.$object->ref);
915
916
		$filename = basename($pathtofile);
917
		if (! preg_match('/^website_(.*)-(.*)$/', $filename, $reg))
918
		{
919
			$this->errors[]='Bad format for filename '.$filename.'. Must be website_XXX-VERSION.';
920
			return -1;
921
		}
922
923
		$result = dol_uncompress($pathtofile, $conf->website->dir_temp.'/'.$object->ref);
924
		if (! empty($result['error']))
925
		{
926
			$this->errors[]='Failed to unzip file '.$pathtofile.'.';
927
			return -1;
928
		}
929
930
931
		dolCopyDir($conf->website->dir_temp.'/'.$object->ref.'/containers', $conf->website->dir_output.'/'.$object->ref, 0, 1);	// Overwrite if exists
932
933
		dolCopyDir($conf->website->dir_temp.'/'.$object->ref.'/medias', $conf->website->dir_output.'/'.$object->ref.'/medias', 0, 1);	// Medias can be shared, do not overwrite if exists
934
935
		$sqlfile = $conf->website->dir_temp.'/'.$object->ref.'/website_pages.sql';
936
937
		$arrayreplacement = array('__WEBSITE_ID__' => $object->id);
938
		$result = dolReplaceInFile($sqlfile, $arrayreplacement);
939
940
		$this->db->begin();
941
942
		$runsql = run_sql($sqlfile, 1, '', 0, '', 'none', 0, 1);
943
		if ($runsql <= 0)
944
		{
945
			$this->errors[]='Failed to load sql file '.$sqlfile.'.';
946
			$error++;
947
		}
948
949
950
		if ($error)
951
		{
952
			$this->db->rollback();
953
			return -1;
954
		}
955
		else
956
		{
957
			$this->db->commit();
958
			return $object->id;
959
		}
960
	}
961
962
}
963
964