Passed
Branch develop (96ac0e)
by
unknown
23:19
created

EcmDirectory::fetch()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 43
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 33
c 0
b 0
f 0
nop 1
dl 0
loc 43
rs 9.392
nc 5
1
<?php
2
/* Copyright (C) 2007-2012 Laurent Destailleur  <[email protected]>
3
 * Copyright (C) 2008-2012 Regis Houssin        <[email protected]>
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17
 */
18
19
/**
20
 *  \file       htdocs/ecm/class/ecmdirectory.class.php
21
 *  \ingroup    ecm
22
 *  \brief      This file is an example for a class file
23
 */
24
25
/**
26
 *  Class to manage ECM directories
27
 */
28
class EcmDirectory extends CommonObject
29
{
30
	/**
31
	 * @var string ID to identify managed object
32
	 */
33
	public $element = 'ecm_directories';
34
35
	/**
36
	 * @var string Name of table without prefix where object is stored
37
	 */
38
	public $table_element = 'ecm_directories';
39
40
	/**
41
	 * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
42
	 */
43
	public $picto = 'folder-open';
44
45
	/**
46
	 * @var int ID
47
	 */
48
	public $id;
49
50
	/**
51
	 * @var string ECM directories label
52
	 */
53
	public $label;
54
55
	/**
56
	 * @var int ID
57
	 */
58
	public $fk_parent;
59
60
	/**
61
	 * @var string description
62
	 */
63
	public $description;
64
65
	/**
66
	 * @var int cache nb of doc
67
	 */
68
	public $cachenbofdoc = -1; // By default cache initialized with value 'not calculated'
69
70
	/**
71
	 * @var int date_c
72
	 */
73
	public $date_c;
74
75
	/**
76
	 * @var int date_m
77
	 */
78
	public $date_m;
79
80
	/**
81
	 * @var int ID
82
	 */
83
	public $fk_user_m;
84
85
	/**
86
	 * @var int ID
87
	 */
88
	public $fk_user_c;
89
90
	/**
91
	 * @var string Ref
92
	 */
93
	public $ref;
94
95
	/**
96
	 * @var array array of categories
97
	 */
98
	public $cats = array();
99
100
	/**
101
	 * @var array array of children categories
102
	 */
103
	public $motherof = array();
104
105
	/**
106
	 * @var array array of forbidden chars
107
	 */
108
	public $forbiddenchars = array('<', '>', ':', '/', '\\', '?', '*', '|', '"');
109
110
	/**
111
	 * @var array array of forbidden chars for dir
112
	 */
113
	public $forbiddencharsdir = array('<', '>', ':', '?', '*', '|', '"');
114
115
	/**
116
	 * @var int 1 if full arbo loaded
117
	 */
118
	public $full_arbo_loaded;
119
120
	/**
121
	 *	Constructor
122
	 *
123
	 *  @param		DoliDB		$db      Database handler
124
	 */
125
	public function __construct($db)
126
	{
127
		$this->db = $db;
128
		return 1;
129
	}
130
131
132
	/**
133
	 *  Create record into database
134
	 *
135
	 *  @param      User	$user       User that create
136
	 *  @return     int      			<0 if KO, >0 if OK
137
	 */
138
	public function create($user)
139
	{
140
		global $conf, $langs;
141
142
		$error = 0;
143
		$now = dol_now();
144
145
		// Clean parameters
146
		$this->label = dol_sanitizeFileName(trim($this->label));
147
		$this->description = trim($this->description);
148
		$this->date_c = $now;
149
		$this->fk_user_c = $user->id;
150
		if ($this->fk_parent <= 0) {
151
			$this->fk_parent = 0;
152
		}
153
154
155
		// Check if same directory does not exists with this name
156
		$relativepath = $this->label;
157
		if ($this->fk_parent > 0) {
158
			$parent = new EcmDirectory($this->db);
159
			$parent->fetch($this->fk_parent);
160
			$relativepath = $parent->getRelativePath().$relativepath;
161
		}
162
		$relativepath = preg_replace('/([\/])+/i', '/', $relativepath); // Avoid duplicate / or \
163
		//print $relativepath.'<br>';
164
165
		$cat = new EcmDirectory($this->db);
166
		$cate_arbo = $cat->get_full_arbo(1);
167
		$pathfound = 0;
168
		foreach ($cate_arbo as $key => $categ) {
169
			$path = str_replace($this->forbiddencharsdir, '_', $categ['fullrelativename']);
170
			//print $relativepath.' - '.$path.'<br>';
171
			if ($path == $relativepath) {
172
				$pathfound = 1;
173
				break;
174
			}
175
		}
176
177
		if ($pathfound) {
178
			$this->error = "ErrorDirAlreadyExists";
179
			dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
180
			return -1;
181
		} else {
182
			$this->db->begin();
183
184
			// Insert request
185
			$sql = "INSERT INTO ".MAIN_DB_PREFIX."ecm_directories(";
186
			$sql .= "label,";
187
			$sql .= "entity,";
188
			$sql .= "fk_parent,";
189
			$sql .= "description,";
190
			$sql .= "cachenbofdoc,";
191
			$sql .= "date_c,";
192
			$sql .= "fk_user_c";
193
			$sql .= ") VALUES (";
194
			$sql .= " '".$this->db->escape($this->label)."',";
195
			$sql .= " '".$this->db->escape($conf->entity)."',";
196
			$sql .= " ".($this->fk_parent > 0 ? ((int) $this->fk_parent) : "null").",";
197
			$sql .= " '".$this->db->escape($this->description)."',";
198
			$sql .= " ".((int) $this->cachenbofdoc).",";
199
			$sql .= " '".$this->db->idate($this->date_c)."',";
200
			$sql .= " ".($this->fk_user_c > 0 ? ((int) $this->fk_user_c) : "null").",";
201
			$sql .= ")";
202
203
			dol_syslog(get_class($this)."::create", LOG_DEBUG);
204
			$resql = $this->db->query($sql);
205
			if ($resql) {
206
				$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."ecm_directories");
207
208
				$dir = $conf->ecm->dir_output.'/'.$this->getRelativePath();
209
				$result = dol_mkdir($dir);
210
				if ($result < 0) {
211
					$error++; $this->error = "ErrorFailedToCreateDir";
212
				}
213
214
				// Call trigger
215
				$result = $this->call_trigger('MYECMDIR_CREATE', $user);
216
				if ($result < 0) {
217
					$error++;
218
				}
219
				// End call triggers
220
221
				if (!$error) {
222
					$this->db->commit();
223
					return $this->id;
224
				} else {
225
					$this->db->rollback();
226
					return -1;
227
				}
228
			} else {
229
				$this->error = "Error ".$this->db->lasterror();
230
				$this->db->rollback();
231
				return -1;
232
			}
233
		}
234
	}
235
236
	/**
237
	 *	Update database
238
	 *
239
	 *  @param	User	$user        	User that modify
240
	 *  @param 	int		$notrigger	    0=no, 1=yes (no update trigger)
241
	 *  @return int 			       	<0 if KO, >0 if OK
242
	 */
243
	public function update($user = null, $notrigger = 0)
244
	{
245
		global $conf, $langs;
246
247
		$error = 0;
248
249
		// Clean parameters
250
		$this->label = trim($this->label);
251
		$this->description = trim($this->description);
252
		if ($this->fk_parent <= 0) {
253
			$this->fk_parent = 0;
254
		}
255
256
		$this->db->begin();
257
258
		// Update request
259
		$sql = "UPDATE ".MAIN_DB_PREFIX."ecm_directories SET";
260
		$sql .= " label = '".$this->db->escape($this->label)."',";
261
		$sql .= " fk_parent = ".($this->fk_parent > 0 ? ((int) $this->fk_parent) : "null").",";
262
		$sql .= " description = '".$this->db->escape($this->description)."'";
263
		$sql .= " WHERE rowid = ".((int) $this->id);
264
265
		dol_syslog(get_class($this)."::update", LOG_DEBUG);
266
		$resql = $this->db->query($sql);
267
		if (!$resql) {
268
			$error++;
269
			$this->error = "Error ".$this->db->lasterror();
270
		}
271
272
		if (!$error && !$notrigger) {
273
			// Call trigger
274
			$result = $this->call_trigger('MYECMDIR_MODIFY', $user);
275
			if ($result < 0) {
276
				$error++;
277
			}
278
			// End call triggers
279
		}
280
281
		if (!$error) {
282
			$this->db->commit();
283
			return 1;
284
		} else {
285
			$this->db->rollback();
286
			return -1;
287
		}
288
	}
289
290
291
	/**
292
	 *	Update cache of nb of documents into database
293
	 *
294
	 * 	@param	string	$value		'+' or '-' or new number
295
	 *  @return int		         	<0 if KO, >0 if OK
296
	 */
297
	public function changeNbOfFiles($value)
298
	{
299
		// Update request
300
		$sql = "UPDATE ".MAIN_DB_PREFIX."ecm_directories SET";
301
		if (preg_match('/[0-9]+/', $value)) {
302
			$sql .= " cachenbofdoc = ".(int) $value;
303
		} else {
304
			$sql .= " cachenbofdoc = cachenbofdoc ".$value." 1";
305
		}
306
		$sql .= " WHERE rowid = ".((int) $this->id);
307
308
		dol_syslog(get_class($this)."::changeNbOfFiles", LOG_DEBUG);
309
		$resql = $this->db->query($sql);
310
		if (!$resql) {
311
			$this->error = "Error ".$this->db->lasterror();
312
			return -1;
313
		} else {
314
			if (preg_match('/[0-9]+/', $value)) {
315
				$this->cachenbofdoc = (int) $value;
316
			} elseif ($value == '+') {
317
				$this->cachenbofdoc++;
318
			} elseif ($value == '-') {
319
				$this->cachenbofdoc--;
320
			}
321
		}
322
323
		return 1;
324
	}
325
326
327
	/**
328
	 * 	Load object in memory from database
329
	 *
330
	 *  @param	int		$id			Id of object
331
	 *  @return int 		        <0 if KO, 0 if not found, >0 if OK
332
	 */
333
	public function fetch($id)
334
	{
335
		$sql = "SELECT";
336
		$sql .= " t.rowid,";
337
		$sql .= " t.label,";
338
		$sql .= " t.fk_parent,";
339
		$sql .= " t.description,";
340
		$sql .= " t.cachenbofdoc,";
341
		$sql .= " t.fk_user_c,";
342
		$sql .= " t.fk_user_m,";
343
		$sql .= " t.date_c as date_c,";
344
		$sql .= " t.tms as date_m";
345
		$sql .= " FROM ".MAIN_DB_PREFIX."ecm_directories as t";
346
		$sql .= " WHERE t.rowid = ".((int) $id);
347
348
		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
349
		$resql = $this->db->query($sql);
350
		if ($resql) {
351
			$obj = $this->db->fetch_object($resql);
352
			if ($obj) {
353
				$this->id    = $obj->rowid;
354
				$this->ref   = $obj->rowid;
355
356
				$this->label = $obj->label;
357
				$this->fk_parent = $obj->fk_parent;
358
				$this->description = $obj->description;
359
				$this->cachenbofdoc = $obj->cachenbofdoc;
360
				$this->fk_user_m = $obj->fk_user_m;
361
				$this->fk_user_c = $obj->fk_user_c;
362
				$this->date_c = $this->db->jdate($obj->date_c);
363
				$this->date_m = $this->db->jdate($obj->date_m);
364
			}
365
366
			// Retrieve all extrafields for ecm_files
367
			// fetch optionals attributes and labels
368
			$this->fetch_optionals();
369
370
			$this->db->free($resql);
371
372
			return $obj ? 1 : 0;
373
		} else {
374
			$this->error = "Error ".$this->db->lasterror();
375
			return -1;
376
		}
377
	}
378
379
380
	/**
381
	 * 	Delete object on database and/or on disk
382
	 *
383
	 *	@param	User	$user					User that delete
384
	 *  @param	string	$mode					'all'=delete all, 'databaseonly'=only database entry, 'fileonly' (not implemented)
385
	 *  @param	int		$deletedirrecursive		1=Agree to delete content recursiveley (otherwise an error will be returned when trying to delete)
386
	 *	@return	int								<0 if KO, >0 if OK
387
	 */
388
	public function delete($user, $mode = 'all', $deletedirrecursive = 0)
389
	{
390
		global $conf, $langs;
391
		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
392
393
		$error = 0;
394
395
		if ($mode != 'databaseonly') {
396
			$relativepath = $this->getRelativePath(1); // Ex: dir1/dir2/dir3
397
		}
398
399
		dol_syslog(get_class($this)."::delete remove directory id=".$this->id." mode=".$mode.(($mode == 'databaseonly') ? '' : ' relativepath='.$relativepath));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $relativepath does not seem to be defined for all execution paths leading up to this point.
Loading history...
400
401
		$this->db->begin();
402
403
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_directories";
404
		$sql .= " WHERE rowid=".((int) $this->id);
405
406
		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
407
		$resql = $this->db->query($sql);
408
		if (!$resql) {
409
			$this->db->rollback();
410
			$this->error = "Error ".$this->db->lasterror();
411
			return -2;
412
		} else {
413
			// Call trigger
414
			$result = $this->call_trigger('MYECMDIR_DELETE', $user);
415
			if ($result < 0) {
416
				$this->db->rollback();
417
				return -2;
418
			}
419
			// End call triggers
420
		}
421
422
		if ($mode != 'databaseonly') {
423
			$file = $conf->ecm->dir_output."/".$relativepath;
424
			if ($deletedirrecursive) {
425
				$result = @dol_delete_dir_recursive($file, 0, 0);
426
			} else {
427
				$result = @dol_delete_dir($file, 0);
428
			}
429
		}
430
431
		if ($result || !@is_dir(dol_osencode($file))) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $file does not seem to be defined for all execution paths leading up to this point.
Loading history...
432
			$this->db->commit();
433
		} else {
434
			$this->error = 'ErrorFailToDeleteDir';
435
			dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
436
			$this->db->rollback();
437
			$error++;
438
		}
439
440
		if (!$error) {
441
			return 1;
442
		} else {
443
			return -1;
444
		}
445
	}
446
447
448
	/**
449
	 *  Initialise an instance with random values.
450
	 *  Used to build previews or test instances.
451
	 *	id must be 0 if object instance is a specimen.
452
	 *
453
	 *  @return	void
454
	 */
455
	public function initAsSpecimen()
456
	{
457
		$this->id = 0;
458
459
		$this->label = 'MyDirectory';
460
		$this->fk_parent = '0';
461
		$this->description = 'This is a directory';
462
	}
463
464
465
	/**
466
	 *  Return directory name you can click (and picto)
467
	 *
468
	 *  @param	int		$withpicto		0=Pas de picto, 1=Include picto into link, 2=Only picto
469
	 *  @param	string	$option			Sur quoi pointe le lien
470
	 *  @param	int		$max			Max length
471
	 *  @param	string	$more			Add more param on a link
472
	 *  @param	int		$notooltip		1=Disable tooltip
473
	 *  @return	string					Chaine avec URL
474
	 */
475
	public function getNomUrl($withpicto = 0, $option = '', $max = 0, $more = '', $notooltip = 0)
476
	{
477
		global $langs;
478
479
		$result = '';
480
		//$newref=str_replace('_',' ',$this->ref);
481
		$newref = $this->ref;
482
		$label = $langs->trans("ShowECMSection").': '.$newref;
483
		$linkclose = '"'.($more ? ' '.$more : '').' title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
484
485
		$linkstart = '<a href="'.DOL_URL_ROOT.'/ecm/dir_card.php?section='.$this->id.$linkclose;
486
		if ($option == 'index') {
487
			$linkstart = '<a href="'.DOL_URL_ROOT.'/ecm/index.php?section='.$this->id.'&amp;sectionexpand=true'.$linkclose;
488
		}
489
		if ($option == 'indexexpanded') {
490
			$linkstart = '<a href="'.DOL_URL_ROOT.'/ecm/index.php?section='.$this->id.'&amp;sectionexpand=false'.$linkclose;
491
		}
492
		if ($option == 'indexnotexpanded') {
493
			$linkstart = '<a href="'.DOL_URL_ROOT.'/ecm/index.php?section='.$this->id.'&amp;sectionexpand=true'.$linkclose;
494
		}
495
		$linkend = '</a>';
496
497
		//$picto=DOL_URL_ROOT.'/theme/common/treemenu/folder.gif';
498
		$picto = 'dir';
499
500
		$result .= $linkstart;
501
		if ($withpicto) {
502
			$result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
503
		}
504
		if ($withpicto != 2) {
505
			$result .= ($max ?dol_trunc($newref, $max, 'middle') : $newref);
506
		}
507
		$result .= $linkend;
508
509
		return $result;
510
	}
511
512
	/**
513
	 *  Return relative path of a directory on disk
514
	 *
515
	 * 	@param	int		$force		Force reload of full arbo even if already loaded
516
	 *	@return	string				Relative physical path
517
	 */
518
	public function getRelativePath($force = 0)
519
	{
520
		$this->get_full_arbo($force);
521
522
		$ret = '';
523
		$idtosearch = $this->id;
524
		$i = 0;
525
		do {
526
			// Get index cursor in this->cats for id_mere
527
			$cursorindex = -1;
528
			foreach ($this->cats as $key => $val) {
529
				if ($this->cats[$key]['id'] == $idtosearch) {
530
					$cursorindex = $key;
531
					break;
532
				}
533
			}
534
			//print "c=".$idtosearch."-".$cursorindex;
535
536
			if ($cursorindex >= 0) {
537
				// Path is label sanitized (no space and no special char) and concatenated
538
				$ret = dol_sanitizeFileName($this->cats[$cursorindex]['label']).'/'.$ret;
539
540
				$idtosearch = $this->cats[$cursorindex]['id_mere'];
541
				$i++;
542
			}
543
		} while ($cursorindex >= 0 && !empty($idtosearch) && $i < 100); // i avoid infinite loop
544
545
		return $ret;
546
	}
547
548
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
549
	/**
550
	 * 	Load this->motherof that is array(id_son=>id_parent, ...)
551
	 *
552
	 *	@return		int		<0 if KO, >0 if OK
553
	 */
554
	public function load_motherof()
555
	{
556
		// phpcs:enable
557
		global $conf;
558
559
		$this->motherof = array();
560
561
		// Load array[child]=parent
562
		$sql = "SELECT fk_parent as id_parent, rowid as id_son";
563
		$sql .= " FROM ".MAIN_DB_PREFIX."ecm_directories";
564
		$sql .= " WHERE fk_parent != 0";
565
		$sql .= " AND entity = ".$conf->entity;
566
567
		dol_syslog(get_class($this)."::load_motherof", LOG_DEBUG);
568
		$resql = $this->db->query($sql);
569
		if ($resql) {
570
			// This assignment in condition is not a bug. It allows walking the results.
571
			while ($obj = $this->db->fetch_object($resql)) {
572
				$this->motherof[$obj->id_son] = $obj->id_parent;
573
			}
574
			return 1;
575
		} else {
576
			dol_print_error($this->db);
577
			return -1;
578
		}
579
	}
580
581
582
	/**
583
	 *  Retourne le libelle du status d'un user (actif, inactif)
584
	 *
585
	 *  @param	int		$mode          0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
586
	 *  @return	string 			       Label of status
587
	 */
588
	public function getLibStatut($mode = 0)
589
	{
590
		return $this->LibStatut($this->status, $mode);
591
	}
592
593
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
594
	/**
595
	 *  Return the status
596
	 *
597
	 *  @param	int		$status        	Id status
598
	 *  @param  int		$mode          	0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 5=Long label + Picto
599
	 *  @return string 			       	Label of status
600
	 */
601
	public static function LibStatut($status, $mode = 0)
602
	{
603
		// phpcs:enable
604
		global $langs;
605
		return '';
606
	}
607
608
609
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
610
	/**
611
	 * 	Reconstruit l'arborescence des categories sous la forme d'un tableau à partir de la base de donnée
612
	 *	Renvoi un tableau de tableau('id','id_mere',...) trie selon arbre et avec:
613
	 *				id                  Id de la categorie
614
	 *				id_mere             Id de la categorie mere
615
	 *				id_children         Tableau des id enfant
616
	 *				label               Name of directory
617
	 *				cachenbofdoc        Nb of documents
618
	 *				date_c              Date creation
619
	 * 				fk_user_c           User creation
620
	 *  			login_c             Login creation
621
	 * 				fullpath	        Full path of id (Added by build_path_from_id_categ call)
622
	 *              fullrelativename    Full path name (Added by build_path_from_id_categ call)
623
	 * 				fulllabel	        Full label (Added by build_path_from_id_categ call)
624
	 * 				level		        Level of line (Added by build_path_from_id_categ call)
625
	 *
626
	 *  @param	int		$force	        Force reload of full arbo even if already loaded in cache $this->cats
627
	 *	@return	array			        Tableau de array
628
	 */
629
	public function get_full_arbo($force = 0)
630
	{
631
		// phpcs:enable
632
		global $conf;
633
634
		if (empty($force) && !empty($this->full_arbo_loaded)) {
635
			return $this->cats;
636
		}
637
638
		// Init this->motherof that is array(id_son=>id_parent, ...)
639
		$this->load_motherof();
640
641
		// Charge tableau des categories
642
		$sql = "SELECT c.rowid as rowid, c.label as label,";
643
		$sql .= " c.description as description, c.cachenbofdoc,";
644
		$sql .= " c.fk_user_c,";
645
		$sql .= " c.date_c,";
646
		$sql .= " u.login as login_c,";
647
		$sql .= " u.statut as statut_c,";
648
		$sql .= " ca.rowid as rowid_fille";
649
		$sql .= " FROM ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."ecm_directories as c";
650
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."ecm_directories as ca";
651
		$sql .= " ON c.rowid = ca.fk_parent";
652
		$sql .= " WHERE c.fk_user_c = u.rowid";
653
		$sql .= " AND c.entity = ".$conf->entity;
654
		$sql .= " ORDER BY c.label, c.rowid";
655
656
		dol_syslog(get_class($this)."::get_full_arbo", LOG_DEBUG);
657
		$resql = $this->db->query($sql);
658
		if ($resql) {
659
			$this->cats = array();
660
			$i = 0;
661
			// This assignment in condition is not a bug. It allows walking the results.
662
			while ($obj = $this->db->fetch_object($resql)) {
663
				$this->cats[$obj->rowid]['id'] = $obj->rowid;
664
				$this->cats[$obj->rowid]['id_mere'] = (isset($this->motherof[$obj->rowid]) ? $this->motherof[$obj->rowid] : '');
665
				$this->cats[$obj->rowid]['label'] = $obj->label;
666
				$this->cats[$obj->rowid]['description'] = $obj->description;
667
				$this->cats[$obj->rowid]['cachenbofdoc'] = $obj->cachenbofdoc;
668
				$this->cats[$obj->rowid]['date_c'] = $this->db->jdate($obj->date_c);
669
				$this->cats[$obj->rowid]['fk_user_c'] = (int) $obj->fk_user_c;
670
				$this->cats[$obj->rowid]['statut_c'] = (int) $obj->statut_c;
671
				$this->cats[$obj->rowid]['login_c'] = $obj->login_c;
672
673
				if (!empty($obj->rowid_fille)) {
674
					if (isset($this->cats[$obj->rowid]['id_children']) && is_array($this->cats[$obj->rowid]['id_children'])) {
675
						$newelempos = count($this->cats[$obj->rowid]['id_children']);
676
						//print "this->cats[$i]['id_children'] est deja un tableau de $newelem elements<br>";
677
						$this->cats[$obj->rowid]['id_children'][$newelempos] = $obj->rowid_fille;
678
					} else {
679
						//print "this->cats[".$obj->rowid."]['id_children'] n'est pas encore un tableau<br>";
680
						$this->cats[$obj->rowid]['id_children'] = array($obj->rowid_fille);
681
					}
682
				}
683
				$i++;
684
			}
685
		} else {
686
			dol_print_error($this->db);
687
			return -1;
688
		}
689
690
		// We add properties fullxxx to all elements
691
		foreach ($this->cats as $key => $val) {
692
			if (isset($motherof[$key])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $motherof seems to never exist and therefore isset should always be false.
Loading history...
693
				continue;
694
			}
695
			$this->build_path_from_id_categ($key, 0);
696
		}
697
698
		$this->cats = dol_sort_array($this->cats, 'fulllabel', 'asc', true, false);
699
		$this->full_arbo_loaded = 1;
700
701
		return $this->cats;
702
	}
703
704
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
705
	/**
706
	 *	Define properties fullpath, fullrelativename, fulllabel of a directory of array this->cats and all its childs.
707
	 *  Separator between directories is always '/', whatever is OS.
708
	 *
709
	 * 	@param	int		$id_categ		id_categ entry to update
710
	 * 	@param	int		$protection		Deep counter to avoid infinite loop
711
	 * 	@return	void
712
	 */
713
	public function build_path_from_id_categ($id_categ, $protection = 0)
714
	{
715
		// phpcs:enable
716
		// Define fullpath
717
		if (!empty($this->cats[$id_categ]['id_mere'])) {
718
			$this->cats[$id_categ]['fullpath'] = $this->cats[$this->cats[$id_categ]['id_mere']]['fullpath'];
719
			$this->cats[$id_categ]['fullpath'] .= '_'.$id_categ;
720
			$this->cats[$id_categ]['fullrelativename'] = $this->cats[$this->cats[$id_categ]['id_mere']]['fullrelativename'];
721
			$this->cats[$id_categ]['fullrelativename'] .= '/'.$this->cats[$id_categ]['label'];
722
			$this->cats[$id_categ]['fulllabel'] = $this->cats[$this->cats[$id_categ]['id_mere']]['fulllabel'];
723
			$this->cats[$id_categ]['fulllabel'] .= ' >> '.$this->cats[$id_categ]['label'];
724
		} else {
725
			$this->cats[$id_categ]['fullpath'] = '_'.$id_categ;
726
			$this->cats[$id_categ]['fullrelativename'] = $this->cats[$id_categ]['label'];
727
			$this->cats[$id_categ]['fulllabel'] = $this->cats[$id_categ]['label'];
728
		}
729
		// We count number of _ to have level (we use strlen that is faster than dol_strlen)
730
		$this->cats[$id_categ]['level'] = strlen(preg_replace('/([^_])/i', '', $this->cats[$id_categ]['fullpath']));
731
732
		// Traite ces enfants
733
		$protection++;
734
		if ($protection > 20) {
735
			return; // On ne traite pas plus de 20 niveaux
736
		}
737
		if (isset($this->cats[$id_categ]['id_children']) && is_array($this->cats[$id_categ]['id_children'])) {
738
			foreach ($this->cats[$id_categ]['id_children'] as $key => $val) {
739
				$this->build_path_from_id_categ($val, $protection);
740
			}
741
		}
742
	}
743
744
	/**
745
	 *	Refresh value for cachenboffile. This scan and count files into directory.
746
	 *
747
	 *  @param		int		$all       	0=refresh record using this->id , 1=refresh record using this->entity
748
	 * 	@return		int					-1 if KO, Nb of files in directory if OK
749
	 */
750
	public function refreshcachenboffile($all = 0)
751
	{
752
		global $conf;
753
		include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
754
755
		$dir = $conf->ecm->dir_output.'/'.$this->getRelativePath();
756
		$filelist = dol_dir_list($dir, 'files', 0, '', '(\.meta|_preview.*\.png)$');
757
758
		// Test if filelist is in database
759
760
761
		// Update request
762
		$sql = "UPDATE ".MAIN_DB_PREFIX."ecm_directories SET";
763
		$sql .= " cachenbofdoc = '".count($filelist)."'";
764
		if (empty($all)) {  // By default
765
			$sql .= " WHERE rowid = ".((int) $this->id);
766
		} else {
767
			$sql .= " WHERE entity = ".$conf->entity;
768
		}
769
770
		dol_syslog(get_class($this)."::refreshcachenboffile", LOG_DEBUG);
771
		$resql = $this->db->query($sql);
772
		if ($resql) {
773
			$this->cachenbofdoc = count($filelist);
774
			return $this->cachenbofdoc;
775
		} else {
776
			$this->error = "Error ".$this->db->lasterror();
777
			return -1;
778
		}
779
	}
780
781
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
782
	/**
783
	 * Call trigger based on this instance.
784
	 * We implement it here because this class doe not extend CommonObject.
785
	 *
786
	 * NB1: Error from trigger are stacked in errors
787
	 * NB2: if trigger fail, action should be canceled.
788
	 * NB3: Should be deleted if EcmDirectory extend CommonObject
789
	 *
790
	 * @param   string    $triggerName   trigger's name to execute
791
	 * @param   User      $user           Object user
792
	 * @return  int                       Result of run_triggers
793
	 */
794
	public function call_trigger($triggerName, $user)
795
	{
796
		// phpcs:enable
797
		global $langs, $conf;
798
799
		include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
800
		$interface = new Interfaces($this->db);
801
		$result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
802
		if ($result < 0) {
803
			if (!empty($this->errors)) {
804
				$this->errors = array_merge($this->errors, $interface->errors);
805
			} else {
806
				$this->errors = $interface->errors;
807
			}
808
		}
809
		return $result;
810
	}
811
}
812