Completed
Branch develop (45fc57)
by
unknown
27:54
created

Website::importWebSite()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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