Passed
Branch develop (e2bf59)
by
unknown
29:11
created

Website::createFromClone()   F

Complexity

Conditions 19
Paths 482

Size

Total Lines 156
Code Lines 92

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 19
eloc 92
nc 482
nop 4
dl 0
loc 156
rs 1.0693
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 <https://www.gnu.org/licenses/>.
20
 */
21
22
/**
23
 * \file    htdocs/website/class/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 string Main language of web site
75
	 */
76
	public $lang;
77
78
	/**
79
	 * @var string List of languages of web site ('fr', 'es_MX', ...)
80
	 */
81
	public $otherlang;
82
83
	/**
84
	 * @var int Status
85
	 */
86
	public $status;
87
88
	/**
89
	 * @var integer|string date_creation
90
	 */
91
	public $date_creation;
92
93
	/**
94
	 * @var integer|string date_modification
95
	 */
96
	public $date_modification;
97
98
	/**
99
	 * @var integer
100
	 */
101
	public $fk_default_home;
102
103
	/**
104
	 * @var int User Create Id
105
	 */
106
	public $fk_user_creat;
107
108
	/**
109
	 * @var string
110
	 */
111
	public $virtualhost;
112
113
	/**
114
	 * @var int
115
	 */
116
	public $use_manifest;
117
118
	/**
119
	 * @var int
120
	 */
121
	public $position;
122
123
	/**
124
	 * List of containers
125
	 *
126
	 * @var array
127
	 */
128
	public $lines;
129
130
131
	const STATUS_DRAFT = 0;
132
	const STATUS_VALIDATED = 1;
133
134
135
	/**
136
	 * Constructor
137
	 *
138
	 * @param DoliDb $db Database handler
139
	 */
140
	public function __construct(DoliDB $db)
141
	{
142
		$this->db = $db;
143
		return 1;
144
	}
145
146
	/**
147
	 * Create object into database
148
	 *
149
	 * @param  User $user      User that creates
150
	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
151
	 *
152
	 * @return int <0 if KO, Id of created object if OK
153
	 */
154
	public function create(User $user, $notrigger = false)
155
	{
156
		global $conf, $langs;
157
158
		dol_syslog(__METHOD__, LOG_DEBUG);
159
160
		$error = 0;
161
		$now = dol_now();
162
163
		// Clean parameters
164
		if (isset($this->entity)) {
165
			 $this->entity = (int) $this->entity;
166
		}
167
		if (isset($this->ref)) {
168
			 $this->ref = trim($this->ref);
169
		}
170
		if (isset($this->description)) {
171
			 $this->description = trim($this->description);
172
		}
173
		if (isset($this->status)) {
174
			 $this->status = (int) $this->status;
175
		}
176
		if (empty($this->date_creation)) {
177
			$this->date_creation = $now;
178
		}
179
		if (empty($this->date_modification)) {
180
			$this->date_modification = $now;
181
		}
182
		// Remove spaces and be sure we have main language only
183
		$this->lang = preg_replace('/[_-].*$/', '', trim($this->lang)); // en_US or en-US -> en
184
		$tmparray = explode(',', $this->otherlang);
185
		if (is_array($tmparray)) {
186
			foreach ($tmparray as $key => $val) {
187
				// It possible we have empty val here if postparam WEBSITE_OTHERLANG is empty or set like this : 'en,,sv' or 'en,sv,'
188
				if (empty(trim($val))) {
189
					unset($tmparray[$key]);
190
					continue;
191
				}
192
				$tmparray[$key] = preg_replace('/[_-].*$/', '', trim($val)); // en_US or en-US -> en
193
			}
194
			$this->otherlang = join(',', $tmparray);
195
		}
196
197
		// Check parameters
198
		if (empty($this->entity)) {
199
			$this->entity = $conf->entity;
200
		}
201
		if (empty($this->lang)) {
202
			$this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MainLanguage"));
203
			return -1;
204
		}
205
206
		// Insert request
207
		$sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.'(';
208
		$sql .= 'entity,';
209
		$sql .= 'ref,';
210
		$sql .= 'description,';
211
		$sql .= 'lang,';
212
		$sql .= 'otherlang,';
213
		$sql .= 'status,';
214
		$sql .= 'fk_default_home,';
215
		$sql .= 'virtualhost,';
216
		$sql .= 'fk_user_creat,';
217
		$sql .= 'date_creation,';
218
		$sql .= 'position,';
219
		$sql .= 'tms';
220
		$sql .= ') VALUES (';
221
		$sql .= ' '.((empty($this->entity) && $this->entity != '0') ? 'NULL' : $this->entity).',';
222
		$sql .= ' '.(!isset($this->ref) ? 'NULL' : "'".$this->db->escape($this->ref)."'").',';
223
		$sql .= ' '.(!isset($this->description) ? 'NULL' : "'".$this->db->escape($this->description)."'").',';
224
		$sql .= ' '.(!isset($this->lang) ? 'NULL' : "'".$this->db->escape($this->lang)."'").',';
225
		$sql .= ' '.(!isset($this->otherlang) ? 'NULL' : "'".$this->db->escape($this->otherlang)."'").',';
226
		$sql .= ' '.(!isset($this->status) ? '1' : $this->status).',';
227
		$sql .= ' '.(!isset($this->fk_default_home) ? 'NULL' : $this->fk_default_home).',';
228
		$sql .= ' '.(!isset($this->virtualhost) ? 'NULL' : "'".$this->db->escape($this->virtualhost)."'").",";
229
		$sql .= ' '.(!isset($this->fk_user_creat) ? $user->id : $this->fk_user_creat).',';
230
		$sql .= ' '.(!isset($this->date_creation) || dol_strlen($this->date_creation) == 0 ? 'NULL' : "'".$this->db->idate($this->date_creation)."'").",";
231
		$sql .= ' '.((int) $this->position).",";
232
		$sql .= ' '.(!isset($this->date_modification) || dol_strlen($this->date_modification) == 0 ? 'NULL' : "'".$this->db->idate($this->date_modification)."'");
233
		$sql .= ')';
234
235
		$this->db->begin();
236
237
		$resql = $this->db->query($sql);
238
		if (!$resql) {
239
			$error++;
240
			$this->errors[] = 'Error '.$this->db->lasterror();
241
			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
242
		}
243
244
		if (!$error) {
245
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
246
247
			// Create subdirectory per language
248
			$tmplangarray = explode(',', $this->otherlang);
249
			if (is_array($tmplangarray)) {
250
				dol_mkdir($conf->website->dir_output.'/'.$this->ref);
251
				foreach ($tmplangarray as $val) {
252
					if (trim($val) == $this->lang) {
253
						continue;
254
					}
255
					dol_mkdir($conf->website->dir_output.'/'.$this->ref.'/'.trim($val));
256
				}
257
			}
258
259
			// Uncomment this and change WEBSITE to your own tag if you
260
			// want this action to call a trigger.
261
			// if (!$notrigger) {
262
263
			//     // Call triggers
264
			//     $result = $this->call_trigger('WEBSITE_CREATE',$user);
265
			//     if ($result < 0) $error++;
266
			//     // End call triggers
267
			// }
268
		}
269
270
		if (!$error) {
271
			$stringtodolibarrfile = "# Some properties for Dolibarr web site CMS\n";
272
			$stringtodolibarrfile .= "param=value\n";
273
			//print $conf->website->dir_output.'/'.$this->ref.'/.dolibarr';exit;
274
			file_put_contents($conf->website->dir_output.'/'.$this->ref.'/.dolibarr', $stringtodolibarrfile);
275
		}
276
277
		// Commit or rollback
278
		if ($error) {
279
			$this->db->rollback();
280
281
			return -1 * $error;
282
		} else {
283
			$this->db->commit();
284
285
			return $this->id;
286
		}
287
	}
288
289
	/**
290
	 * Load object in memory from the database
291
	 *
292
	 * @param 	int    $id  	Id object
293
	 * @param 	string $ref 	Ref
294
	 * @return 	int 			<0 if KO, 0 if not found, >0 if OK
295
	 */
296
	public function fetch($id, $ref = null)
297
	{
298
		dol_syslog(__METHOD__, LOG_DEBUG);
299
300
		$sql = "SELECT";
301
		$sql .= " t.rowid,";
302
		$sql .= " t.entity,";
303
		$sql .= " t.ref,";
304
		$sql .= " t.position,";
305
		$sql .= " t.description,";
306
		$sql .= " t.lang,";
307
		$sql .= " t.otherlang,";
308
		$sql .= " t.status,";
309
		$sql .= " t.fk_default_home,";
310
		$sql .= " t.use_manifest,";
311
		$sql .= " t.virtualhost,";
312
		$sql .= " t.fk_user_creat,";
313
		$sql .= " t.fk_user_modif,";
314
		$sql .= " t.date_creation,";
315
		$sql .= " t.tms as date_modification";
316
		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
317
		$sql .= " WHERE t.entity IN (".getEntity('website').")";
318
		if (!empty($ref)) {
319
			$sql .= " AND t.ref = '".$this->db->escape($ref)."'";
320
		} else {
321
			$sql .= " AND t.rowid = ".(int) $id;
322
		}
323
324
		$resql = $this->db->query($sql);
325
		if ($resql) {
326
			$numrows = $this->db->num_rows($resql);
327
			if ($numrows) {
328
				$obj = $this->db->fetch_object($resql);
329
330
				$this->id = $obj->rowid;
331
332
				$this->entity = $obj->entity;
333
				$this->ref = $obj->ref;
334
				$this->position = $obj->position;
335
				$this->description = $obj->description;
336
				$this->lang = $obj->lang;
337
				$this->otherlang = $obj->otherlang;
338
				$this->status = $obj->status;
339
				$this->fk_default_home = $obj->fk_default_home;
340
				$this->virtualhost = $obj->virtualhost;
341
				$this->use_manifest = $obj->use_manifest;
342
				$this->fk_user_creat = $obj->fk_user_creat;
343
				$this->fk_user_modif = $obj->fk_user_modif;
344
				$this->date_creation = $this->db->jdate($obj->date_creation);
345
				$this->date_modification = $this->db->jdate($obj->date_modification);
346
			}
347
			$this->db->free($resql);
348
349
			if ($numrows > 0) {
350
				// Lines
351
				$this->fetchLines();
352
			}
353
354
			if ($numrows > 0) {
355
				return 1;
356
			} else {
357
				return 0;
358
			}
359
		} else {
360
			$this->errors[] = 'Error '.$this->db->lasterror();
361
			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
362
363
			return -1;
364
		}
365
	}
366
367
	/**
368
	 * Load object lines in memory from the database
369
	 *
370
	 * @return int         <0 if KO, 0 if not found, >0 if OK
371
	 */
372
	public function fetchLines()
373
	{
374
		$this->lines = array();
375
376
		// Load lines with object MyObjectLine
377
378
		return count($this->lines) ? 1 : 0;
379
	}
380
381
382
	/**
383
	 * Load all object in memory ($this->records) from the database
384
	 *
385
	 * @param string $sortorder Sort Order
386
	 * @param string $sortfield Sort field
387
	 * @param int    $limit     offset limit
388
	 * @param int    $offset    offset limit
389
	 * @param array  $filter    filter array
390
	 * @param string $filtermode filter mode (AND or OR)
391
	 *
392
	 * @return int <0 if KO, >0 if OK
393
	 */
394
	public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
395
	{
396
		dol_syslog(__METHOD__, LOG_DEBUG);
397
398
		$sql = "SELECT";
399
		$sql .= " t.rowid,";
400
		$sql .= " t.entity,";
401
		$sql .= " t.ref,";
402
		$sql .= " t.description,";
403
		$sql .= " t.lang,";
404
		$sql .= " t.otherlang,";
405
		$sql .= " t.status,";
406
		$sql .= " t.fk_default_home,";
407
		$sql .= " t.virtualhost,";
408
		$sql .= " t.fk_user_creat,";
409
		$sql .= " t.fk_user_modif,";
410
		$sql .= " t.date_creation,";
411
		$sql .= " t.tms as date_modification";
412
		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
413
		$sql .= " WHERE t.entity IN (".getEntity('website').")";
414
		// Manage filter
415
		$sqlwhere = array();
416
		if (count($filter) > 0) {
417
			foreach ($filter as $key => $value) {
418
				$sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
419
			}
420
		}
421
		if (count($sqlwhere) > 0) {
422
			$sql .= ' AND '.implode(' '.$this->db->escape($filtermode).' ', $sqlwhere);
423
		}
424
425
		if (!empty($sortfield)) {
426
			$sql .= $this->db->order($sortfield, $sortorder);
427
		}
428
		if (!empty($limit)) {
429
			$sql .= $this->db->plimit($limit, $offset);
430
		}
431
		$this->records = array();
432
433
		$resql = $this->db->query($sql);
434
		if ($resql) {
435
			$num = $this->db->num_rows($resql);
436
437
			while ($obj = $this->db->fetch_object($resql)) {
438
				$line = new self($this->db);
439
440
				$line->id = $obj->rowid;
441
442
				$line->entity = $obj->entity;
443
				$line->ref = $obj->ref;
444
				$line->description = $obj->description;
445
				$line->lang = $obj->lang;
446
				$line->otherlang = $obj->otherlang;
447
				$line->status = $obj->status;
448
				$line->fk_default_home = $obj->fk_default_home;
449
				$line->virtualhost = $obj->virtualhost;
450
				$this->fk_user_creat = $obj->fk_user_creat;
451
				$this->fk_user_modif = $obj->fk_user_modif;
452
				$line->date_creation = $this->db->jdate($obj->date_creation);
453
				$line->date_modification = $this->db->jdate($obj->date_modification);
454
455
				$this->records[$line->id] = $line;
456
			}
457
			$this->db->free($resql);
458
459
			return $num;
460
		} else {
461
			$this->errors[] = 'Error '.$this->db->lasterror();
462
			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
463
464
			return -1;
465
		}
466
	}
467
468
	/**
469
	 * Update object into database
470
	 *
471
	 * @param  User $user      User that modifies
472
	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
473
	 *
474
	 * @return int <0 if KO, >0 if OK
475
	 */
476
	public function update(User $user, $notrigger = false)
477
	{
478
		global $conf, $langs;
479
480
		$error = 0;
481
482
		dol_syslog(__METHOD__, LOG_DEBUG);
483
484
		// Clean parameters
485
486
		if (isset($this->entity)) {
487
			 $this->entity = (int) $this->entity;
488
		}
489
		if (isset($this->ref)) {
490
			 $this->ref = trim($this->ref);
491
		}
492
		if (isset($this->description)) {
493
			 $this->description = trim($this->description);
494
		}
495
		if (isset($this->status)) {
496
			 $this->status = (int) $this->status;
497
		}
498
499
		// Remove spaces and be sure we have main language only
500
		$this->lang = preg_replace('/[_-].*$/', '', trim($this->lang)); // en_US or en-US -> en
501
		$tmparray = explode(',', $this->otherlang);
502
		if (is_array($tmparray)) {
503
			foreach ($tmparray as $key => $val) {
504
				// It possible we have empty val here if postparam WEBSITE_OTHERLANG is empty or set like this : 'en,,sv' or 'en,sv,'
505
				if (empty(trim($val))) {
506
					unset($tmparray[$key]);
507
					continue;
508
				}
509
				$tmparray[$key] = preg_replace('/[_-].*$/', '', trim($val)); // en_US or en-US -> en
510
			}
511
			$this->otherlang = join(',', $tmparray);
512
		}
513
		if (empty($this->lang)) {
514
			$this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MainLanguage"));
515
			return -1;
516
		}
517
518
		// Check parameters
519
		// Put here code to add a control on parameters values
520
521
		// Update request
522
		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
523
		$sql .= ' entity = '.(isset($this->entity) ? $this->entity : "null").',';
524
		$sql .= ' ref = '.(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").',';
525
		$sql .= ' description = '.(isset($this->description) ? "'".$this->db->escape($this->description)."'" : "null").',';
526
		$sql .= ' lang = '.(isset($this->lang) ? "'".$this->db->escape($this->lang)."'" : "null").',';
527
		$sql .= ' otherlang = '.(isset($this->otherlang) ? "'".$this->db->escape($this->otherlang)."'" : "null").',';
528
		$sql .= ' status = '.(isset($this->status) ? $this->status : "null").',';
529
		$sql .= ' fk_default_home = '.(($this->fk_default_home > 0) ? $this->fk_default_home : "null").',';
530
		$sql .= ' use_manifest = '.((int) $this->use_manifest).',';
531
		$sql .= ' virtualhost = '.(($this->virtualhost != '') ? "'".$this->db->escape($this->virtualhost)."'" : "null").',';
532
		$sql .= ' fk_user_modif = '.(!isset($this->fk_user_modif) ? $user->id : $this->fk_user_modif).',';
533
		$sql .= ' date_creation = '.(!isset($this->date_creation) || dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').',';
534
		$sql .= ' tms = '.(dol_strlen($this->date_modification) != 0 ? "'".$this->db->idate($this->date_modification)."'" : "'".$this->db->idate(dol_now())."'");
535
		$sql .= ' WHERE rowid='.((int) $this->id);
536
537
		$this->db->begin();
538
539
		$resql = $this->db->query($sql);
540
		if (!$resql) {
541
			$error++;
542
			$this->errors[] = 'Error '.$this->db->lasterror();
543
			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
544
		}
545
546
		if (!$error && !$notrigger) {
547
			// Uncomment this and change MYOBJECT to your own tag if you
548
			// want this action calls a trigger.
549
550
			// Create subdirectory per language
551
			$tmplangarray = explode(',', $this->otherlang);
552
			if (is_array($tmplangarray)) {
553
				dol_mkdir($conf->website->dir_output.'/'.$this->ref);
554
				foreach ($tmplangarray as $val) {
555
					if (trim($val) == $this->lang) {
556
						continue;
557
					}
558
					dol_mkdir($conf->website->dir_output.'/'.$this->ref.'/'.trim($val));
559
				}
560
			}
561
562
			//// Call triggers
563
			//$result=$this->call_trigger('WEBSITE_MODIFY',$user);
564
			//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
565
			//// End call triggers
566
		}
567
568
		// Commit or rollback
569
		if ($error) {
570
			$this->db->rollback();
571
572
			return -1 * $error;
573
		} else {
574
			$this->db->commit();
575
576
			return 1;
577
		}
578
	}
579
580
	/**
581
	 * Delete object in database
582
	 *
583
	 * @param User $user      User that deletes
584
	 * @param bool $notrigger false=launch triggers after, true=disable triggers
585
	 *
586
	 * @return int <0 if KO, >0 if OK
587
	 */
588
	public function delete(User $user, $notrigger = false)
589
	{
590
		global $conf;
591
592
		dol_syslog(__METHOD__, LOG_DEBUG);
593
594
		$error = 0;
595
596
		$this->db->begin();
597
598
		if (!$error) {
599
			if (!$notrigger) {
600
				// Uncomment this and change WEBSITE to your own tag if you
601
				// want this action calls a trigger.
602
603
				//// Call triggers
604
				//$result=$this->call_trigger('WEBSITE_DELETE',$user);
605
				//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
606
				//// End call triggers
607
			}
608
		}
609
610
		if (!$error) {
611
			$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element;
612
			$sql .= ' WHERE rowid='.((int) $this->id);
613
614
			$resql = $this->db->query($sql);
615
			if (!$resql) {
616
				$error++;
617
				$this->errors[] = 'Error '.$this->db->lasterror();
618
				dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
619
			}
620
		}
621
622
		if (!$error && !empty($this->ref)) {
623
			$pathofwebsite = DOL_DATA_ROOT.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.$this->ref;
624
625
			dol_delete_dir_recursive($pathofwebsite);
626
		}
627
628
		// Commit or rollback
629
		if ($error) {
630
			$this->db->rollback();
631
632
			return -1 * $error;
633
		} else {
634
			$this->db->commit();
635
636
			return 1;
637
		}
638
	}
639
640
	/**
641
	 * Load a website its id and create a new one in database.
642
	 * This copy website directories, regenerate all the pages + alias pages and recreate the medias link.
643
	 *
644
	 * @param	User	$user		User making the clone
645
	 * @param 	int 	$fromid 	Id of object to clone
646
	 * @param	string	$newref		New ref
647
	 * @param	string	$newlang	New language
648
	 * @return 	mixed 				New object created, <0 if KO
649
	 */
650
	public function createFromClone($user, $fromid, $newref, $newlang = '')
651
	{
652
		global $conf, $langs;
653
		global $dolibarr_main_data_root;
654
655
		$now = dol_now();
656
		$error = 0;
657
658
		dol_syslog(__METHOD__, LOG_DEBUG);
659
660
		$newref = dol_sanitizeFileName($newref);
661
662
		if (empty($newref)) {
663
			$this->error = 'ErrorBadParameter';
664
			return -1;
665
		}
666
667
		$object = new self($this->db);
668
669
		// Check no site with ref exists
670
		if ($object->fetch(0, $newref) > 0) {
671
			$this->error = 'ErrorNewRefIsAlreadyUsed';
672
			return -1;
673
		}
674
675
		$this->db->begin();
676
677
		// Load source object
678
		$object->fetch($fromid);
679
680
		$oldidforhome = $object->fk_default_home;
681
		$oldref = $object->ref;
682
683
		$pathofwebsiteold = $dolibarr_main_data_root.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.dol_sanitizeFileName($oldref);
684
		$pathofwebsitenew = $dolibarr_main_data_root.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.dol_sanitizeFileName($newref);
685
		dol_delete_dir_recursive($pathofwebsitenew);
686
687
		$fileindex = $pathofwebsitenew.'/index.php';
688
689
		// Reset some properties
690
		unset($object->id);
691
		unset($object->fk_user_creat);
692
		unset($object->import_key);
693
694
		// Clear fields
695
		$object->ref = $newref;
696
		$object->fk_default_home = 0;
697
		$object->virtualhost = '';
698
		$object->date_creation = $now;
699
		$object->fk_user_creat = $user->id;
700
		$object->position = ((int) $object->position) + 1;
701
		$object->status = self::STATUS_DRAFT;
702
		if (empty($object->lang)) {
703
			$object->lang = substr($langs->defaultlang, 0, 2); // Should not happen. Protection for corrupted site with no languages
704
		}
705
706
		// Create clone
707
		$object->context['createfromclone'] = 'createfromclone';
708
		$result = $object->create($user);
709
		if ($result < 0) {
710
			$error++;
711
			$this->error = $object->error;
712
			$this->errors = $object->errors;
713
			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
714
		}
715
716
		if (!$error) {
717
			dolCopyDir($pathofwebsiteold, $pathofwebsitenew, $conf->global->MAIN_UMASK, 0, null, 2);
718
719
			// Check symlink to medias and restore it if ko
720
			$pathtomedias = DOL_DATA_ROOT.'/medias'; // Target
721
			$pathtomediasinwebsite = $pathofwebsitenew.'/medias'; // Source / Link name
722
			if (!is_link(dol_osencode($pathtomediasinwebsite))) {
723
				dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite);
724
				dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists
725
				$result = symlink($pathtomedias, $pathtomediasinwebsite);
726
			}
727
728
			// Copy images and js dir
729
			$pathofmediasjsold = DOL_DATA_ROOT.'/medias/js/'.$oldref;
730
			$pathofmediasjsnew = DOL_DATA_ROOT.'/medias/js/'.$newref;
731
			dolCopyDir($pathofmediasjsold, $pathofmediasjsnew, $conf->global->MAIN_UMASK, 0);
732
733
			$pathofmediasimageold = DOL_DATA_ROOT.'/medias/image/'.$oldref;
734
			$pathofmediasimagenew = DOL_DATA_ROOT.'/medias/image/'.$newref;
735
			dolCopyDir($pathofmediasimageold, $pathofmediasimagenew, $conf->global->MAIN_UMASK, 0);
736
737
			$newidforhome = 0;
738
739
			// Duplicate pages
740
			$objectpages = new WebsitePage($this->db);
741
			$listofpages = $objectpages->fetchAll($fromid);
742
			foreach ($listofpages as $pageid => $objectpageold) {
743
				// Delete old file
744
				$filetplold = $pathofwebsitenew.'/page'.$pageid.'.tpl.php';
745
				dol_delete_file($filetplold);
746
747
				// Create new file
748
				$objectpagenew = $objectpageold->createFromClone($user, $pageid, $objectpageold->pageurl, '', 0, $object->id, 1);
749
750
				//print $pageid.' = '.$objectpageold->pageurl.' -> '.$objectpagenew->id.' = '.$objectpagenew->pageurl.'<br>';
751
				if (is_object($objectpagenew) && $objectpagenew->pageurl) {
752
					$filealias = $pathofwebsitenew.'/'.$objectpagenew->pageurl.'.php';
753
					$filetplnew = $pathofwebsitenew.'/page'.$objectpagenew->id.'.tpl.php';
754
755
					// Save page alias
756
					$result = dolSavePageAlias($filealias, $object, $objectpagenew);
757
					if (!$result) {
758
						setEventMessages('Failed to write file '.$filealias, null, 'errors');
759
					}
760
761
					$result = dolSavePageContent($filetplnew, $object, $objectpagenew);
762
					if (!$result) {
763
						setEventMessages('Failed to write file '.$filetplnew, null, 'errors');
764
					}
765
766
					if ($pageid == $oldidforhome) {
767
						$newidforhome = $objectpagenew->id;
768
					}
769
				} else {
770
					setEventMessages($objectpageold->error, $objectpageold->errors, 'errors');
771
					$error++;
772
				}
773
			}
774
		}
775
776
		if (!$error) {
777
			// Restore id of home page
778
			$object->fk_default_home = $newidforhome;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $newidforhome does not seem to be defined for all execution paths leading up to this point.
Loading history...
779
			$res = $object->update($user);
780
			if (!($res > 0)) {
781
				$error++;
782
				setEventMessages($object->error, $object->errors, 'errors');
783
			}
784
785
			if (!$error) {
786
				$filetpl = $pathofwebsitenew.'/page'.$newidforhome.'.tpl.php';
787
				$filewrapper = $pathofwebsitenew.'/wrapper.php';
788
789
				// Re-generates the index.php page to be the home page, and re-generates the wrapper.php
790
				//--------------------------------------------------------------------------------------
791
				$result = dolSaveIndexPage($pathofwebsitenew, $fileindex, $filetpl, $filewrapper);
792
			}
793
		}
794
795
		unset($object->context['createfromclone']);
796
797
		// End
798
		if (!$error) {
799
			$this->db->commit();
800
801
			return $object;
802
		} else {
803
			$this->db->rollback();
804
805
			return -1;
806
		}
807
	}
808
809
	/**
810
	 *  Return a link to the user card (with optionally the picto)
811
	 * 	Use this->id,this->lastname, this->firstname
812
	 *
813
	 *	@param	int		$withpicto			Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
814
	 *	@param	string	$option				On what the link point to
815
	 *  @param	integer	$notooltip			1=Disable tooltip
816
	 *  @param	int		$maxlen				Max length of visible user name
817
	 *  @param  string  $morecss            Add more css on link
818
	 *	@return	string						String with URL
819
	 */
820
	public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $maxlen = 24, $morecss = '')
821
	{
822
		global $langs, $conf, $db;
823
		global $dolibarr_main_authentication, $dolibarr_main_demo;
824
		global $menumanager;
825
826
827
		$result = '';
828
		$companylink = '';
829
830
		$label = '<u>'.$langs->trans("WebSite").'</u>';
831
		$label .= '<br>';
832
		$label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref.'<br>';
833
		$label .= '<b>'.$langs->trans('MainLanguage').':</b> '.$this->lang;
834
835
		$linkstart = '<a href="'.DOL_URL_ROOT.'/website/card.php?id='.$this->id.'"';
836
		$linkstart .= ($notooltip ? '' : ' title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip'.($morecss ? ' '.$morecss : '').'"');
837
		$linkstart .= '>';
838
		$linkend = '</a>';
839
840
		$linkstart = $linkend = '';
841
842
		if ($withpicto) {
843
			$result .= ($linkstart.img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? '' : 'class="classfortooltip"')).$linkend);
844
			if ($withpicto != 2) {
845
				$result .= ' ';
846
			}
847
		}
848
		$result .= $linkstart.$this->ref.$linkend;
849
		return $result;
850
	}
851
852
	/**
853
	 *  Retourne le libelle du status d'un user (actif, inactif)
854
	 *
855
	 *  @param	int		$mode          0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
856
	 *  @return	string 			       Label of status
857
	 */
858
	public function getLibStatut($mode = 0)
859
	{
860
		return $this->LibStatut($this->status, $mode);
861
	}
862
863
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
864
	/**
865
	 *  Renvoi le libelle d'un status donne
866
	 *
867
	 *  @param	int		$status        	Id status
868
	 *  @param  int		$mode          	0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
869
	 *  @return string 			       	Label of status
870
	 */
871
	public function LibStatut($status, $mode = 0)
872
	{
873
		// phpcs:enable
874
		global $langs;
875
876
		if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
877
			global $langs;
878
			//$langs->load("mymodule");
879
			$this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Disabled');
880
			$this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
881
			$this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Disabled');
882
			$this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
883
		}
884
885
		$statusType = 'status5';
886
		if ($status == self::STATUS_VALIDATED) {
887
			$statusType = 'status4';
888
		}
889
890
		return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
891
	}
892
893
894
	/**
895
	 * Initialise object with example values
896
	 * Id must be 0 if object instance is a specimen
897
	 *
898
	 * @return void
899
	 */
900
	public function initAsSpecimen()
901
	{
902
		global $user;
903
904
		$this->id = 0;
905
		$this->specimen = 1;
906
		$this->entity = 1;
907
		$this->ref = 'myspecimenwebsite';
908
		$this->description = 'A specimen website';
909
		$this->lang = 'en';
910
		$this->otherlang = 'fr,es';
911
		$this->status = 1;
912
		$this->fk_default_home = null;
913
		$this->virtualhost = 'http://myvirtualhost';
914
		$this->fk_user_creat = $user->id;
915
		$this->fk_user_modif = $user->id;
916
		$this->date_creation = dol_now();
917
		$this->tms = dol_now();
918
	}
919
920
921
	/**
922
	 * Generate a zip with all data of web site.
923
	 *
924
	 * @return  string						Path to file with zip or '' if error
925
	 */
926
	public function exportWebSite()
927
	{
928
		global $conf, $mysoc;
929
930
		$website = $this;
931
932
		if (empty($website->id) || empty($website->ref)) {
933
			setEventMessages("Website id or ref is not defined", null, 'errors');
934
			return '';
935
		}
936
937
		dol_syslog("Create temp dir ".$conf->website->dir_temp);
938
		dol_mkdir($conf->website->dir_temp);
939
		if (!is_writable($conf->website->dir_temp)) {
940
			setEventMessages("Temporary dir ".$conf->website->dir_temp." is not writable", null, 'errors');
941
			return '';
942
		}
943
944
		$destdir = $conf->website->dir_temp.'/'.$website->ref;
945
946
		dol_syslog("Clear temp dir ".$destdir);
947
		$count = 0; $countreallydeleted = 0;
948
		$counttodelete = dol_delete_dir_recursive($destdir, $count, 1, 0, $countreallydeleted);
949
		if ($counttodelete != $countreallydeleted) {
950
			setEventMessages("Failed to clean temp directory ".$destdir, null, 'errors');
951
			return '';
952
		}
953
954
		$arrayreplacementinfilename = array();
955
		$arrayreplacementincss = array();
956
		$arrayreplacementincss['file=image/'.$website->ref.'/'] = "file=image/__WEBSITE_KEY__/";
957
		$arrayreplacementincss['file=js/'.$website->ref.'/'] = "file=js/__WEBSITE_KEY__/";
958
		$arrayreplacementincss['medias/image/'.$website->ref.'/'] = "medias/image/__WEBSITE_KEY__/";
959
		$arrayreplacementincss['medias/js/'.$website->ref.'/'] = "medias/js/__WEBSITE_KEY__/";
960
		if ($mysoc->logo_small) {
961
			$arrayreplacementincss['file=logos%2Fthumbs%2F'.$mysoc->logo_small] = "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__";
962
		}
963
		if ($mysoc->logo_mini) {
964
			$arrayreplacementincss['file=logos%2Fthumbs%2F'.$mysoc->logo_mini] = "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__";
965
		}
966
		if ($mysoc->logo) {
967
			$arrayreplacementincss['file=logos%2Fthumbs%2F'.$mysoc->logo] = "file=logos%2Fthumbs%2F__LOGO_KEY__";
968
		}
969
970
		// Create output directories
971
		dol_syslog("Create containers dir");
972
		dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/containers');
973
		dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/medias/image/websitekey');
974
		dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/medias/js/websitekey');
975
976
		// Copy files into 'containers'
977
		$srcdir = $conf->website->dir_output.'/'.$website->ref;
978
		$destdir = $conf->website->dir_temp.'/'.$website->ref.'/containers';
979
980
		dol_syslog("Copy content from ".$srcdir." into ".$destdir);
981
		dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacementinfilename, 2);
982
983
		// Copy files into medias/image
984
		$srcdir = DOL_DATA_ROOT.'/medias/image/'.$website->ref;
985
		$destdir = $conf->website->dir_temp.'/'.$website->ref.'/medias/image/websitekey';
986
987
		dol_syslog("Copy content from ".$srcdir." into ".$destdir);
988
		dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacementinfilename);
989
990
		// Copy files into medias/js
991
		$srcdir = DOL_DATA_ROOT.'/medias/js/'.$website->ref;
992
		$destdir = $conf->website->dir_temp.'/'.$website->ref.'/medias/js/websitekey';
993
994
		dol_syslog("Copy content from ".$srcdir." into ".$destdir);
995
		dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacementinfilename);
996
997
		// Make some replacement into some files
998
		$cssindestdir = $conf->website->dir_temp.'/'.$website->ref.'/containers/styles.css.php';
999
		dolReplaceInFile($cssindestdir, $arrayreplacementincss);
1000
1001
		$htmldeaderindestdir = $conf->website->dir_temp.'/'.$website->ref.'/containers/htmlheader.html';
1002
		dolReplaceInFile($htmldeaderindestdir, $arrayreplacementincss);
1003
1004
		// Build sql file
1005
		$filesql = $conf->website->dir_temp.'/'.$website->ref.'/website_pages.sql';
1006
		$fp = fopen($filesql, "w");
1007
		if (empty($fp)) {
1008
			setEventMessages("Failed to create file ".$filesql, null, 'errors');
1009
			return '';
1010
		}
1011
1012
		$objectpages = new WebsitePage($this->db);
1013
		$listofpages = $objectpages->fetchAll($website->id);
1014
1015
		// Assign ->newid and ->newfk_page
1016
		$i = 1;
1017
		foreach ($listofpages as $pageid => $objectpageold) {
1018
			$objectpageold->newid = $i;
1019
			$i++;
1020
		}
1021
		$i = 1;
1022
		foreach ($listofpages as $pageid => $objectpageold) {
1023
			// Search newid
1024
			$newfk_page = 0;
1025
			foreach ($listofpages as $pageid2 => $objectpageold2) {
1026
				if ($pageid2 == $objectpageold->fk_page) {
1027
					$newfk_page = $objectpageold2->newid;
1028
					break;
1029
				}
1030
			}
1031
			$objectpageold->newfk_page = $newfk_page;
1032
			$i++;
1033
		}
1034
		foreach ($listofpages as $pageid => $objectpageold) {
1035
			$allaliases = $objectpageold->pageurl;
1036
			$allaliases .= ($objectpageold->aliasalt ? ','.$objectpageold->aliasalt : '');
1037
1038
			$line = '-- Page ID '.$objectpageold->id.' -> '.$objectpageold->newid.'__+MAX_llx_website_page__ - Aliases '.$allaliases.' --;'; // newid start at 1, 2...
1039
			$line .= "\n";
1040
			fputs($fp, $line);
1041
1042
			// Warning: We must keep llx_ here. It is a generic SQL.
1043
			$line = 'INSERT INTO llx_website_page(rowid, fk_page, fk_website, pageurl, aliasalt, title, description, lang, image, keywords, status, date_creation, tms, import_key, grabbed_from, type_container, htmlheader, content, author_alias, allowed_in_frames)';
1044
1045
			$line .= " VALUES(";
1046
			$line .= $objectpageold->newid."__+MAX_llx_website_page__, ";
1047
			$line .= ($objectpageold->newfk_page ? $this->db->escape($objectpageold->newfk_page)."__+MAX_llx_website_page__" : "null").", ";
1048
			$line .= "__WEBSITE_ID__, ";
1049
			$line .= "'".$this->db->escape($objectpageold->pageurl)."', ";
1050
			$line .= "'".$this->db->escape($objectpageold->aliasalt)."', ";
1051
			$line .= "'".$this->db->escape($objectpageold->title)."', ";
1052
			$line .= "'".$this->db->escape($objectpageold->description)."', ";
1053
			$line .= "'".$this->db->escape($objectpageold->lang)."', ";
1054
			$line .= "'".$this->db->escape($objectpageold->image)."', ";
1055
			$line .= "'".$this->db->escape($objectpageold->keywords)."', ";
1056
			$line .= "'".$this->db->escape($objectpageold->status)."', ";
1057
			$line .= "'".$this->db->idate($objectpageold->date_creation)."', ";
1058
			$line .= "'".$this->db->idate($objectpageold->date_modification)."', ";
1059
			$line .= ($objectpageold->import_key ? "'".$this->db->escape($objectpageold->import_key)."'" : "null").", ";
1060
			$line .= "'".$this->db->escape($objectpageold->grabbed_from)."', ";
1061
			$line .= "'".$this->db->escape($objectpageold->type_container)."', ";
1062
1063
			$stringtoexport = $objectpageold->htmlheader;
1064
			$stringtoexport = str_replace(array("\r\n", "\r", "\n"), "__N__", $stringtoexport);
1065
			$stringtoexport = str_replace('file=image/'.$website->ref.'/', "file=image/__WEBSITE_KEY__/", $stringtoexport);
1066
			$stringtoexport = str_replace('file=js/'.$website->ref.'/', "file=js/__WEBSITE_KEY__/", $stringtoexport);
1067
			$stringtoexport = str_replace('medias/image/'.$website->ref.'/', "medias/image/__WEBSITE_KEY__/", $stringtoexport);
1068
			$stringtoexport = str_replace('medias/js/'.$website->ref.'/', "medias/js/__WEBSITE_KEY__/", $stringtoexport);
1069
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_small, "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__", $stringtoexport);
1070
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_mini, "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__", $stringtoexport);
1071
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo, "file=logos%2Fthumbs%2F__LOGO_KEY__", $stringtoexport);
1072
			$line .= "'".$this->db->escape(str_replace(array("\r\n", "\r", "\n"), "__N__", $stringtoexport))."', "; // Replace \r \n to have record on 1 line
1073
1074
			$stringtoexport = $objectpageold->content;
1075
			$stringtoexport = str_replace(array("\r\n", "\r", "\n"), "__N__", $stringtoexport);
1076
			$stringtoexport = str_replace('file=image/'.$website->ref.'/', "file=image/__WEBSITE_KEY__/", $stringtoexport);
1077
			$stringtoexport = str_replace('file=js/'.$website->ref.'/', "file=js/__WEBSITE_KEY__/", $stringtoexport);
1078
			$stringtoexport = str_replace('medias/image/'.$website->ref.'/', "medias/image/__WEBSITE_KEY__/", $stringtoexport);
1079
			$stringtoexport = str_replace('medias/js/'.$website->ref.'/', "medias/js/__WEBSITE_KEY__/", $stringtoexport);
1080
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_small, "file=logos%2Fthumbs%2F__LOGO_SMALL_KEY__", $stringtoexport);
1081
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo_mini, "file=logos%2Fthumbs%2F__LOGO_MINI_KEY__", $stringtoexport);
1082
			$stringtoexport = str_replace('file=logos%2Fthumbs%2F'.$mysoc->logo, "file=logos%2Fthumbs%2F__LOGO_KEY__", $stringtoexport);
1083
1084
			// When we have a link src="image/websiteref/file.png" into html content
1085
			$stringtoexport = str_replace('="image/'.$website->ref.'/', '="image/__WEBSITE_KEY__/', $stringtoexport);
1086
1087
			$line .= "'".$this->db->escape($stringtoexport)."', "; // Replace \r \n to have record on 1 line
1088
			$line .= "'".$this->db->escape($objectpageold->author_alias)."', ";
1089
			$line .= "'".$this->db->escape($objectpageold->allowed_in_frames)."'";
1090
			$line .= ");";
1091
			$line .= "\n";
1092
1093
			fputs($fp, $line);
1094
1095
			// Add line to update home page id during import
1096
			//var_dump($this->fk_default_home.' - '.$objectpageold->id.' - '.$objectpageold->newid);exit;
1097
			if ($this->fk_default_home > 0 && ($objectpageold->id == $this->fk_default_home) && ($objectpageold->newid > 0)) {	// This is the record with home page
1098
				// Warning: We must keep llx_ here. It is a generic SQL.
1099
				$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__;";
1100
				$line .= "\n";
1101
				fputs($fp, $line);
1102
			}
1103
		}
1104
1105
		$line = "\n-- For Dolibarr v14+ --;\n";
1106
		$line .= "UPDATE llx_website SET lang = '".$this->db->escape($this->fk_default_lang)."' WHERE rowid = __WEBSITE_ID__;\n";
0 ignored issues
show
Bug introduced by
The property fk_default_lang does not exist on Website. Did you mean fk_default_home?
Loading history...
1107
		$line .= "UPDATE llx_website SET otherlang = '".$this->db->escape($this->otherlang)."' WHERE rowid = __WEBSITE_ID__;\n";
1108
		$line .= "\n";
1109
		fputs($fp, $line);
1110
1111
		fclose($fp);
1112
		if (!empty($conf->global->MAIN_UMASK)) {
1113
			@chmod($filesql, octdec($conf->global->MAIN_UMASK));
1114
		}
1115
1116
		// Build zip file
1117
		$filedir  = $conf->website->dir_temp.'/'.$website->ref.'/.';
1118
		$fileglob = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-*.zip';
1119
		$filename = $conf->website->dir_temp.'/'.$website->ref.'/website_'.$website->ref.'-'.dol_print_date(dol_now(), 'dayhourlog').'-V'.((float) DOL_VERSION).'.zip';
1120
1121
		dol_delete_file($fileglob, 0);
1122
		$result = dol_compress_file($filedir, $filename, 'zip');
1123
1124
		if ($result > 0) {
1125
			return $filename;
1126
		} else {
1127
			global $errormsg;
1128
			$this->error = $errormsg;
1129
			return '';
1130
		}
1131
	}
1132
1133
1134
	/**
1135
	 * Open a zip with all data of web site and load it into database.
1136
	 *
1137
	 * @param 	string		$pathtofile		Path of zip file
1138
	 * @return  int							<0 if KO, Id of new website if OK
1139
	 */
1140
	public function importWebSite($pathtofile)
1141
	{
1142
		global $conf, $mysoc;
1143
1144
		$error = 0;
1145
1146
		$object = $this;
1147
		if (empty($object->ref)) {
1148
			$this->error = 'Function importWebSite called on object not loaded (object->ref is empty)';
1149
			return -1;
1150
		}
1151
1152
		dol_delete_dir_recursive($conf->website->dir_temp."/".$object->ref);
1153
		dol_mkdir($conf->website->dir_temp.'/'.$object->ref);
1154
1155
		$filename = basename($pathtofile);
1156
		if (!preg_match('/^website_(.*)-(.*)$/', $filename, $reg)) {
1157
			$this->errors[] = 'Bad format for filename '.$filename.'. Must be website_XXX-VERSION.';
1158
			return -1;
1159
		}
1160
1161
		$result = dol_uncompress($pathtofile, $conf->website->dir_temp.'/'.$object->ref);
1162
1163
		if (!empty($result['error'])) {
1164
			$this->errors[] = 'Failed to unzip file '.$pathtofile.'.';
1165
			return -1;
1166
		}
1167
1168
		$arrayreplacement = array();
1169
		$arrayreplacement['__WEBSITE_ID__'] = $object->id;
1170
		$arrayreplacement['__WEBSITE_KEY__'] = $object->ref;
1171
		$arrayreplacement['__N__'] = $this->db->escape("\n"); // Restore \n
1172
		$arrayreplacement['__LOGO_SMALL_KEY__'] = $this->db->escape($mysoc->logo_small);
1173
		$arrayreplacement['__LOGO_MINI_KEY__'] = $this->db->escape($mysoc->logo_mini);
1174
		$arrayreplacement['__LOGO_KEY__'] = $this->db->escape($mysoc->logo);
1175
1176
		// Copy containers
1177
		dolCopyDir($conf->website->dir_temp.'/'.$object->ref.'/containers', $conf->website->dir_output.'/'.$object->ref, 0, 1); // Overwrite if exists
1178
1179
		// Make replacement into css and htmlheader file
1180
		$cssindestdir = $conf->website->dir_output.'/'.$object->ref.'/styles.css.php';
1181
		$result = dolReplaceInFile($cssindestdir, $arrayreplacement);
1182
1183
		$htmldeaderindestdir = $conf->website->dir_output.'/'.$object->ref.'/htmlheader.html';
1184
		$result = dolReplaceInFile($htmldeaderindestdir, $arrayreplacement);
1185
1186
		// Now generate the master.inc.php page
1187
		$filemaster = $conf->website->dir_output.'/'.$object->ref.'/master.inc.php';
1188
		$result = dolSaveMasterFile($filemaster);
1189
		if (!$result) {
1190
			$this->errors[] = 'Failed to write file '.$filemaster;
1191
			$error++;
1192
		}
1193
1194
		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
1195
		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
1196
1197
		$sqlfile = $conf->website->dir_temp."/".$object->ref.'/website_pages.sql';
1198
1199
		$result = dolReplaceInFile($sqlfile, $arrayreplacement);
1200
1201
		$this->db->begin();
1202
1203
		// Search the $maxrowid because we need it later
1204
		$sqlgetrowid = 'SELECT MAX(rowid) as max from '.MAIN_DB_PREFIX.'website_page';
1205
		$resql = $this->db->query($sqlgetrowid);
1206
		if ($resql) {
1207
			$obj = $this->db->fetch_object($resql);
1208
			$maxrowid = $obj->max;
1209
		}
1210
1211
		// Load sql record
1212
		$runsql = run_sql($sqlfile, 1, '', 0, '', 'none', 0, 1); // The maxrowid of table is searched into this function two
1213
		if ($runsql <= 0) {
1214
			$this->errors[] = 'Failed to load sql file '.$sqlfile;
1215
			$error++;
1216
		}
1217
1218
		$objectpagestatic = new WebsitePage($this->db);
1219
1220
		// Make replacement of IDs
1221
		$fp = fopen($sqlfile, "r");
1222
		if ($fp) {
1223
			while (!feof($fp)) {
1224
				$reg = array();
1225
1226
				// Warning fgets with second parameter that is null or 0 hang.
1227
				$buf = fgets($fp, 65000);
1228
				if (preg_match('/^-- Page ID (\d+)\s[^\s]+\s(\d+).*Aliases\s(.*)\s--;/i', $buf, $reg)) {
1229
					$oldid = $reg[1];
1230
					$newid = ($reg[2] + $maxrowid);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $maxrowid does not seem to be defined for all execution paths leading up to this point.
Loading history...
1231
					$aliasesarray = explode(',', $reg[3]);
1232
1233
					dol_syslog("Found ID ".$oldid." to replace with ID ".$newid." and shortcut aliases to create: ".$reg[3]);
1234
1235
					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);
1236
1237
					$objectpagestatic->fetch($newid);
1238
1239
					// The move is not enough, so we regenerate page
1240
					$filetpl = $conf->website->dir_output.'/'.$object->ref.'/page'.$newid.'.tpl.php';
1241
					$result = dolSavePageContent($filetpl, $object, $objectpagestatic);
1242
					if (!$result) {
1243
						$this->errors[] = 'Failed to write file '.basename($filetpl);
1244
						$error++;
1245
					}
1246
1247
					// Regenerate alternative aliases pages
1248
					if (is_array($aliasesarray)) {
1249
						foreach ($aliasesarray as $aliasshortcuttocreate) {
1250
							if (trim($aliasshortcuttocreate)) {
1251
								$filealias = $conf->website->dir_output.'/'.$object->ref.'/'.trim($aliasshortcuttocreate).'.php';
1252
								$result = dolSavePageAlias($filealias, $object, $objectpagestatic);
1253
								if (!$result) {
1254
									$this->errors[] = 'Failed to write file '.basename($filealias);
1255
									$error++;
1256
								}
1257
							}
1258
						}
1259
					}
1260
				}
1261
			}
1262
		}
1263
1264
		// Read record of website that has been updated by the run_sql function previously called so we can get the
1265
		// value of fk_default_home that is ID of home page
1266
		$sql = "SELECT fk_default_home FROM ".MAIN_DB_PREFIX."website WHERE rowid = ".((int) $object->id);
1267
		$resql = $this->db->query($sql);
1268
		if ($resql) {
1269
			$obj = $this->db->fetch_object($resql);
1270
			if ($obj) {
1271
				$object->fk_default_home = $obj->fk_default_home;
1272
			} else {
1273
				//$this->errors[] = 'Failed to get the Home page';
1274
				//$error++;
1275
			}
1276
		}
1277
1278
		// Regenerate index page to point to the new index page
1279
		$pathofwebsite = $conf->website->dir_output.'/'.$object->ref;
1280
		dolSaveIndexPage($pathofwebsite, $pathofwebsite.'/index.php', $pathofwebsite.'/page'.$object->fk_default_home.'.tpl.php', $pathofwebsite.'/wrapper.php');
1281
1282
		if ($error) {
1283
			$this->db->rollback();
1284
			return -1;
1285
		} else {
1286
			$this->db->commit();
1287
			return $object->id;
1288
		}
1289
	}
1290
1291
	/**
1292
	 * Rebuild all files of a containers of a website. Rebuild also the wrapper.php file. TODO Add other files too.
1293
	 * Note: Files are already regenerated during importWebSite so this function is useless when importing a website.
1294
	 *
1295
	 * @return 	int						<0 if KO, >=0 if OK
1296
	 */
1297
	public function rebuildWebSiteFiles()
1298
	{
1299
		global $conf;
1300
1301
		$error = 0;
1302
1303
		$object = $this;
1304
		if (empty($object->ref)) {
1305
			$this->error = 'Function rebuildWebSiteFiles called on object not loaded (object->ref is empty)';
1306
			return -1;
1307
		}
1308
1309
		$objectpagestatic = new WebsitePage($this->db);
1310
1311
		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."website_page WHERE fk_website = ".((int) $this->id);
1312
1313
		$resql = $this->db->query($sql);
1314
		if (!$resql) {
1315
			$this->error = $this->db->lasterror();
1316
			return -1;
1317
		}
1318
1319
		$num = $this->db->num_rows($resql);
1320
1321
		// Loop on each container/page
1322
		$i = 0;
1323
		while ($i < $num) {
1324
			$obj = $this->db->fetch_object($resql);
1325
1326
			$newid = $obj->rowid;
1327
1328
			$objectpagestatic->fetch($newid);
1329
1330
			$aliasesarray = explode(',', $objectpagestatic->aliasalt);
1331
1332
			$filetpl = $conf->website->dir_output.'/'.$object->ref.'/page'.$newid.'.tpl.php';
1333
			$result = dolSavePageContent($filetpl, $object, $objectpagestatic);
1334
			if (!$result) {
1335
				$this->errors[] = 'Failed to write file '.basename($filetpl);
1336
				$error++;
1337
			}
1338
1339
			// Add main alias to list of alternative aliases
1340
			if (!empty($objectpagestatic->pageurl) && !in_array($objectpagestatic->pageurl, $aliasesarray)) {
1341
				$aliasesarray[] = $objectpagestatic->pageurl;
1342
			}
1343
1344
			// Regenerate all aliases pages (pages with a natural name)
1345
			if (is_array($aliasesarray)) {
1346
				foreach ($aliasesarray as $aliasshortcuttocreate) {
1347
					if (trim($aliasshortcuttocreate)) {
1348
						$filealias = $conf->website->dir_output.'/'.$object->ref.'/'.trim($aliasshortcuttocreate).'.php';
1349
						$result = dolSavePageAlias($filealias, $object, $objectpagestatic);
1350
						if (!$result) {
1351
							$this->errors[] = 'Failed to write file '.basename($filealias);
1352
							$error++;
1353
						}
1354
					}
1355
				}
1356
			}
1357
1358
			$i++;
1359
		}
1360
1361
		if (!$error) {
1362
			// Save wrapper.php
1363
			$pathofwebsite = $conf->website->dir_output.'/'.$object->ref;
1364
			$filewrapper = $pathofwebsite.'/wrapper.php';
1365
			dolSaveIndexPage($pathofwebsite, '', '', $filewrapper);
1366
		}
1367
1368
		if ($error) {
1369
			return -1;
1370
		} else {
1371
			return $num;
1372
		}
1373
	}
1374
1375
	/**
1376
	 * Return if web site is a multilanguage web site. Return false if there is only 0 or 1 language.
1377
	 *
1378
	 * @return boolean			True if web site is a multilanguage web site
1379
	 */
1380
	public function isMultiLang()
1381
	{
1382
		return (empty($this->otherlang) ? false : true);
1383
	}
1384
1385
	/**
1386
	 * Component to select language inside a container (Full CSS Only)
1387
	 *
1388
	 * @param	array|string	$languagecodes			'auto' to show all languages available for page, or language codes array like array('en','fr','de','es')
1389
	 * @param	Translate		$weblangs				Language Object
1390
	 * @param	string			$morecss				More CSS class on component
1391
	 * @param	string			$htmlname				Suffix for HTML name
1392
	 * @return 	string									HTML select component
1393
	 */
1394
	public function componentSelectLang($languagecodes, $weblangs, $morecss = '', $htmlname = '')
1395
	{
1396
		global $websitepagefile, $website;
1397
1398
		if (!is_object($weblangs)) {
1399
			return 'ERROR componentSelectLang called with parameter $weblangs not defined';
1400
		}
1401
1402
		$arrayofspecialmainlanguages = array(
1403
			'en'=>'en_US',
1404
			'sq'=>'sq_AL',
1405
			'ar'=>'ar_SA',
1406
			'eu'=>'eu_ES',
1407
			'bn'=>'bn_DB',
1408
			'bs'=>'bs_BA',
1409
			'ca'=>'ca_ES',
1410
			'zh'=>'zh_CN',
1411
			'cs'=>'cs_CZ',
1412
			'da'=>'da_DK',
1413
			'et'=>'et_EE',
1414
			'ka'=>'ka_GE',
1415
			'el'=>'el_GR',
1416
			'he'=>'he_IL',
1417
			'kn'=>'kn_IN',
1418
			'km'=>'km_KH',
1419
			'ko'=>'ko_KR',
1420
			'lo'=>'lo_LA',
1421
			'nb'=>'nb_NO',
1422
			'fa'=>'fa_IR',
1423
			'sr'=>'sr_RS',
1424
			'sl'=>'sl_SI',
1425
			'uk'=>'uk_UA',
1426
			'vi'=>'vi_VN'
1427
		);
1428
1429
		// Load tmppage if we have $websitepagefile defined
1430
		$tmppage = new WebsitePage($this->db);
1431
1432
		$pageid = 0;
1433
		if (!empty($websitepagefile)) {
1434
			$websitepagefileshort = basename($websitepagefile);
1435
			if ($websitepagefileshort == 'index.php') {
1436
				$pageid = $website->fk_default_home;
1437
			} else {
1438
				$pageid = str_replace(array('.tpl.php', 'page'), array('', ''), $websitepagefileshort);
1439
			}
1440
			if ($pageid > 0) {
1441
				$tmppage->fetch($pageid);
1442
			}
1443
		}
1444
1445
		// Fill $languagecodes array with existing translation, nothing if none
1446
		if (!is_array($languagecodes) && $pageid > 0) {
1447
			$languagecodes = array();
1448
1449
			$sql = "SELECT wp.rowid, wp.lang, wp.pageurl, wp.fk_page";
1450
			$sql .= " FROM ".MAIN_DB_PREFIX."website_page as wp";
1451
			$sql .= " WHERE wp.fk_website = ".((int) $website->id);
1452
			$sql .= " AND (wp.fk_page = ".((int) $pageid)." OR wp.rowid  = ".((int) $pageid);
1453
			if ($tmppage->fk_page > 0) {
1454
				$sql .= " OR wp.fk_page = ".((int) $tmppage->fk_page)." OR wp.rowid = ".((int) $tmppage->fk_page);
1455
			}
1456
			$sql .= ")";
1457
1458
			$resql = $this->db->query($sql);
1459
			if ($resql) {
1460
				while ($obj = $this->db->fetch_object($resql)) {
1461
					$newlang = $obj->lang;
1462
					if ($obj->rowid == $pageid) {
1463
						$newlang = $obj->lang;
1464
					}
1465
					if (!in_array($newlang, $languagecodes)) {
1466
						$languagecodes[] = $newlang;
1467
					}
1468
				}
1469
			}
1470
		}
1471
		// Now $languagecodes is always an array. Example array('en', 'fr', 'es');
1472
1473
		$languagecodeselected = substr($weblangs->defaultlang, 0, 2); // Because we must init with a value, but real value is the lang of main parent container
1474
		if (!empty($websitepagefile)) {
1475
			$pageid = str_replace(array('.tpl.php', 'page'), array('', ''), basename($websitepagefile));
1476
			if ($pageid > 0) {
1477
				$pagelang = substr($tmppage->lang, 0, 2);
1478
				$languagecodeselected = substr($pagelang, 0, 2);
1479
				if (!in_array($pagelang, $languagecodes)) {
1480
					$languagecodes[] = $pagelang; // We add language code of page into combo list
1481
				}
1482
			}
1483
		}
1484
1485
		$weblangs->load('languages');
1486
		//var_dump($weblangs->defaultlang);
1487
1488
		$url = $_SERVER["REQUEST_URI"];
1489
		$url = preg_replace('/(\?|&)l=([a-zA-Z_]*)/', '', $url); // We remove param l from url
1490
		//$url = preg_replace('/(\?|&)lang=([a-zA-Z_]*)/', '', $url);	// We remove param lang from url
1491
		$url .= (preg_match('/\?/', $url) ? '&' : '?').'l=';
1492
		if (!preg_match('/^\//', $url)) {
1493
			$url = '/'.$url;
1494
		}
1495
1496
		$HEIGHTOPTION = 40;
1497
		$MAXHEIGHT = 4 * $HEIGHTOPTION;
1498
		$nboflanguage = count($languagecodes);
1499
1500
		$out = '<!-- componentSelectLang'.$htmlname.' -->'."\n";
1501
1502
		$out .= '<style>';
1503
		$out .= '.componentSelectLang'.$htmlname.':hover { height: '.min($MAXHEIGHT, ($HEIGHTOPTION * $nboflanguage)).'px; overflow-x: hidden; overflow-y: '.((($HEIGHTOPTION * $nboflanguage) > $MAXHEIGHT) ? ' scroll' : 'hidden').'; }'."\n";
1504
		$out .= '.componentSelectLang'.$htmlname.' li { line-height: '.$HEIGHTOPTION.'px; }'."\n";
1505
		$out .= '.componentSelectLang'.$htmlname.' {
1506
			display: inline-block;
1507
			padding: 0;
1508
			height: '.$HEIGHTOPTION.'px;
1509
			overflow: hidden;
1510
			transition: all .3s ease;
1511
			margin: 0 0 0 0;
1512
			vertical-align: top;
1513
		}
1514
		.componentSelectLang'.$htmlname.':hover, .componentSelectLang'.$htmlname.':hover a { background-color: #fff; color: #000 !important; }
1515
		ul.componentSelectLang'.$htmlname.' { width: 150px; }
1516
		ul.componentSelectLang'.$htmlname.':hover .fa { visibility: hidden; }
1517
		.componentSelectLang'.$htmlname.' a { text-decoration: none; width: 100%; }
1518
		.componentSelectLang'.$htmlname.' li { display: block; padding: 0px 15px; margin-left: 0; margin-right: 0; }
1519
		.componentSelectLang'.$htmlname.' li:hover { background-color: #EEE; }
1520
		';
1521
		$out .= '</style>';
1522
		$out .= '<ul class="componentSelectLang'.$htmlname.($morecss ? ' '.$morecss : '').'">';
1523
1524
		if ($languagecodeselected) {
1525
			// Convert $languagecodeselected into a long language code
1526
			if (strlen($languagecodeselected) == 2) {
1527
				$languagecodeselected = (empty($arrayofspecialmainlanguages[$languagecodeselected]) ? $languagecodeselected.'_'.strtoupper($languagecodeselected) : $arrayofspecialmainlanguages[$languagecodeselected]);
1528
			}
1529
1530
			$countrycode = strtolower(substr($languagecodeselected, -2));
1531
			$label = $weblangs->trans("Language_".$languagecodeselected);
1532
			if ($countrycode == 'us') {
1533
				$label = preg_replace('/\s*\(.*\)/', '', $label);
1534
			}
1535
			$out .= '<a href="'.$url.substr($languagecodeselected, 0, 2).'"><li><img height="12px" src="/medias/image/common/flags/'.$countrycode.'.png" style="margin-right: 5px;"/><span class="websitecomponentlilang">'.$label.'</span>';
1536
			$out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
1537
			$out .= '</li></a>';
1538
		}
1539
		$i = 0;
1540
		if (is_array($languagecodes)) {
1541
			foreach ($languagecodes as $languagecode) {
1542
				// Convert $languagecode into a long language code
1543
				if (strlen($languagecode) == 2) {
1544
					$languagecode = (empty($arrayofspecialmainlanguages[$languagecode]) ? $languagecode.'_'.strtoupper($languagecode) : $arrayofspecialmainlanguages[$languagecode]);
1545
				}
1546
1547
				if ($languagecode == $languagecodeselected) {
1548
					continue; // Already output
1549
				}
1550
1551
				$countrycode = strtolower(substr($languagecode, -2));
1552
				$label = $weblangs->trans("Language_".$languagecode);
1553
				if ($countrycode == 'us') {
1554
					$label = preg_replace('/\s*\(.*\)/', '', $label);
1555
				}
1556
				$out .= '<a href="'.$url.substr($languagecode, 0, 2).'"><li><img height="12px" src="/medias/image/common/flags/'.$countrycode.'.png" style="margin-right: 5px;"/><span class="websitecomponentlilang">'.$label.'</span>';
1557
				if (empty($i) && empty($languagecodeselected)) {
1558
					$out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
1559
				}
1560
				$out .= '</li></a>';
1561
				$i++;
1562
			}
1563
		}
1564
		$out .= '</ul>';
1565
1566
		return $out;
1567
	}
1568
}
1569