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

Dolresource::fetch_all_used()   B

Complexity

Conditions 10
Paths 48

Size

Total Lines 65
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 48
nc 48
nop 5
dl 0
loc 65
rs 7.2678
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A Dolresource::getElementResources() 0 35 4
A Dolresource::fetchElementResources() 0 9 2

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) 2013-2015	Jean-François Ferry	<[email protected]>
3
 *
4
 * This program is free software; you can redistribute it and/or modify
5
 * it under the terms of the GNU General Public License as published by
6
 * the Free Software Foundation; either version 3 of the License, or
7
 * (at your option) any later version.
8
 *
9
 * This program is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU General Public License
15
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16
 */
17
18
/**
19
 *  \file      	htdocs/resource/class/dolresource.class.php
20
 *  \ingroup    resource
21
 *  \brief      Class file for resource object
22
 */
23
24
require_once DOL_DOCUMENT_ROOT."/core/class/commonobject.class.php";
25
require_once DOL_DOCUMENT_ROOT."/core/lib/functions2.lib.php";
26
27
/**
28
 *  DAO Resource object
29
 */
30
class Dolresource extends CommonObject
31
{
32
	/**
33
	 * @var string ID to identify managed object
34
	 */
35
	public $element = 'dolresource';
36
37
	/**
38
	 * @var string Name of table without prefix where object is stored
39
	 */
40
	public $table_element = 'resource';
41
42
	/**
43
	 * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
44
	 */
45
	public $picto = 'resource';
46
47
	public $resource_id;
48
	public $resource_type;
49
	public $element_id;
50
	public $element_type;
51
	public $busy;
52
	public $mandatory;
53
54
	/**
55
	 * @var int ID
56
	 */
57
	public $fk_user_create;
58
59
	public $type_label;
60
	public $tms = '';
61
62
	public $cache_code_type_resource = array();
63
64
	/**
65
	 * @var Dolresource Clone of object before changing it
66
	 */
67
	public $oldcopy;
68
69
	/**
70
	 *  Constructor
71
	 *
72
	 *  @param	DoliDb		$db      Database handler
73
	 */
74
	public function __construct($db)
75
	{
76
		$this->db = $db;
77
	}
78
79
	/**
80
	 *  Create object into database
81
	 *
82
	 *  @param	User    $user        User that creates
83
	 *  @param  int		$notrigger   0=launch triggers after, 1=disable triggers
84
	 *  @return int      		   	 <0 if KO, Id of created object if OK
85
	 */
86
	public function create($user, $notrigger = 0)
87
	{
88
		global $conf, $langs, $hookmanager;
89
		$error = 0;
90
91
		// Clean parameters
92
93
		if (isset($this->ref)) {
94
			$this->ref = trim($this->ref);
95
		}
96
		if (isset($this->description)) {
97
			$this->description = trim($this->description);
98
		}
99
		if (!is_numeric($this->country_id)) {
100
			$this->country_id = 0;
101
		}
102
		if (isset($this->fk_code_type_resource)) {
103
			$this->fk_code_type_resource = trim($this->fk_code_type_resource);
104
		}
105
		if (isset($this->note_public)) {
106
			$this->note_public = trim($this->note_public);
107
		}
108
		if (isset($this->note_private)) {
109
			$this->note_private = trim($this->note_private);
110
		}
111
112
113
		// Insert request
114
		$sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element."(";
115
		$sql .= "entity,";
116
		$sql .= "ref,";
117
		$sql .= "description,";
118
		$sql .= "fk_country,";
119
		$sql .= "fk_code_type_resource,";
120
		$sql .= "note_public,";
121
		$sql .= "note_private";
122
		$sql .= ") VALUES (";
123
		$sql .= $conf->entity.", ";
124
		$sql .= " ".(!isset($this->ref) ? 'NULL' : "'".$this->db->escape($this->ref)."'").",";
125
		$sql .= " ".(!isset($this->description) ? 'NULL' : "'".$this->db->escape($this->description)."'").",";
126
		$sql .= " ".($this->country_id > 0 ? $this->country_id : 'null').",";
127
		$sql .= " ".(!isset($this->fk_code_type_resource) ? 'NULL' : "'".$this->db->escape($this->fk_code_type_resource)."'").",";
128
		$sql .= " ".(!isset($this->note_public) ? 'NULL' : "'".$this->db->escape($this->note_public)."'").",";
129
		$sql .= " ".(!isset($this->note_private) ? 'NULL' : "'".$this->db->escape($this->note_private)."'");
130
		$sql .= ")";
131
132
		$this->db->begin();
133
134
		dol_syslog(get_class($this)."::create", LOG_DEBUG);
135
		$resql = $this->db->query($sql);
136
		if (!$resql) {
137
			$error++; $this->errors[] = "Error ".$this->db->lasterror();
138
		}
139
140
		if (!$error) {
141
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
142
		}
143
144
		if (!$error) {
145
			$action = 'create';
146
147
			// Actions on extra fields
148
			if (!$error) {
149
				$result = $this->insertExtraFields();
150
				if ($result < 0) {
151
					$error++;
152
				}
153
			}
154
		}
155
156
		if (!$error && !$notrigger) {
157
			// Call trigger
158
			$result = $this->call_trigger('RESOURCE_CREATE', $user);
159
			if ($result < 0) {
160
				$error++;
161
			}
162
			// End call triggers
163
		}
164
165
		// Commit or rollback
166
		if ($error) {
167
			foreach ($this->errors as $errmsg) {
168
				dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
169
				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
170
			}
171
			$this->db->rollback();
172
			return -1 * $error;
173
		} else {
174
			$this->db->commit();
175
			return $this->id;
176
		}
177
	}
178
179
	/**
180
	 *    Load object in memory from database
181
	 *
182
	 *    @param    int		$id     Id of object
183
	 *    @param	string	$ref	Ref of object
184
	 *    @return   int         	<0 if KO, >0 if OK
185
	 */
186
	public function fetch($id, $ref = '')
187
	{
188
		global $langs;
189
		$sql = "SELECT";
190
		$sql .= " t.rowid,";
191
		$sql .= " t.entity,";
192
		$sql .= " t.ref,";
193
		$sql .= " t.description,";
194
		$sql .= " t.fk_country,";
195
		$sql .= " t.fk_code_type_resource,";
196
		$sql .= " t.note_public,";
197
		$sql .= " t.note_private,";
198
		$sql .= " t.tms,";
199
		$sql .= " ty.label as type_label";
200
		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
201
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_resource as ty ON ty.code=t.fk_code_type_resource";
202
		if ($id) {
203
			$sql .= " WHERE t.rowid = ".((int) $id);
204
		} else {
205
			$sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
206
		}
207
208
		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
209
		$resql = $this->db->query($sql);
210
		if ($resql) {
211
			if ($this->db->num_rows($resql)) {
212
				$obj = $this->db->fetch_object($resql);
213
214
				$this->id = $obj->rowid;
215
				$this->entity = $obj->entity;
216
				$this->ref = $obj->ref;
217
				$this->description				= $obj->description;
218
				$this->country_id = $obj->fk_country;
219
				$this->fk_code_type_resource = $obj->fk_code_type_resource;
220
				$this->note_public				= $obj->note_public;
221
				$this->note_private = $obj->note_private;
222
				$this->type_label = $obj->type_label;
223
224
				// Retrieve all extrafield
225
				// fetch optionals attributes and labels
226
				$this->fetch_optionals();
227
			}
228
			$this->db->free($resql);
229
230
			return $this->id;
231
		} else {
232
			$this->error = "Error ".$this->db->lasterror();
233
			dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
234
			return -1;
235
		}
236
	}
237
238
239
	/**
240
	 *  Update object into database
241
	 *
242
	 *  @param	User	$user        User that modifies
243
	 *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
244
	 *  @return int     		   	 <0 if KO, >0 if OK
245
	 */
246
	public function update($user = null, $notrigger = 0)
247
	{
248
		global $conf, $langs, $hookmanager;
249
		$error = 0;
250
251
		// Clean parameters
252
		if (isset($this->ref)) {
253
			$this->ref = trim($this->ref);
254
		}
255
		if (isset($this->fk_code_type_resource)) {
256
			$this->fk_code_type_resource = trim($this->fk_code_type_resource);
257
		}
258
		if (isset($this->description)) {
259
			$this->description = trim($this->description);
260
		}
261
		if (!is_numeric($this->country_id)) {
262
			$this->country_id = 0;
263
		}
264
265
		if (empty($this->oldcopy)) {
266
			$org = new self($this->db);
267
			$org->fetch($this->id);
268
			$this->oldcopy = $org;
269
		}
270
271
		// Update request
272
		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
273
		$sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
274
		$sql .= " description=".(isset($this->description) ? "'".$this->db->escape($this->description)."'" : "null").",";
275
		$sql .= " fk_country=".($this->country_id > 0 ? $this->country_id : "null").",";
276
		$sql .= " fk_code_type_resource=".(isset($this->fk_code_type_resource) ? "'".$this->db->escape($this->fk_code_type_resource)."'" : "null").",";
277
		$sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null')."";
278
		$sql .= " WHERE rowid=".((int) $this->id);
279
280
		$this->db->begin();
281
282
		dol_syslog(get_class($this)."::update", LOG_DEBUG);
283
		$resql = $this->db->query($sql);
284
		if (!$resql) {
285
			$error++; $this->errors[] = "Error ".$this->db->lasterror();
286
		}
287
288
		if (!$error) {
289
			if (!$notrigger) {
290
				// Call trigger
291
				$result = $this->call_trigger('RESOURCE_MODIFY', $user);
292
				if ($result < 0) {
293
					$error++;
294
				}
295
				// End call triggers
296
			}
297
		}
298
299
		if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) {
300
			// We remove directory
301
			if (!empty($conf->resource->dir_output)) {
302
				$olddir = $conf->resource->dir_output."/".dol_sanitizeFileName($this->oldcopy->ref);
303
				$newdir = $conf->resource->dir_output."/".dol_sanitizeFileName($this->ref);
304
				if (file_exists($olddir)) {
305
					$res = @rename($olddir, $newdir);
306
					if (!$res) {
307
						$langs->load("errors");
308
						$this->error = $langs->trans('ErrorFailToRenameDir', $olddir, $newdir);
309
						$error++;
310
					}
311
				}
312
			}
313
		}
314
315
		if (!$error) {
316
			$action = 'update';
317
318
			// Actions on extra fields
319
			if (!$error) {
320
				$result = $this->insertExtraFields();
321
				if ($result < 0) {
322
					$error++;
323
				}
324
			}
325
		}
326
327
		// Commit or rollback
328
		if ($error) {
329
			foreach ($this->errors as $errmsg) {
330
				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
331
				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
332
			}
333
			$this->db->rollback();
334
			return -1 * $error;
335
		} else {
336
			$this->db->commit();
337
			return 1;
338
		}
339
	}
340
341
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
342
	/**
343
	 *    Load object in memory from database
344
	 *
345
	 *    @param      int	$id          id object
346
	 *    @return     int         <0 if KO, >0 if OK
347
	 */
348
	public function fetch_element_resource($id)
349
	{
350
		// phpcs:enable
351
		global $langs;
352
		$sql = "SELECT";
353
		$sql .= " t.rowid,";
354
		$sql .= " t.resource_id,";
355
		$sql .= " t.resource_type,";
356
		$sql .= " t.element_id,";
357
		$sql .= " t.element_type,";
358
		$sql .= " t.busy,";
359
		$sql .= " t.mandatory,";
360
		$sql .= " t.fk_user_create,";
361
		$sql .= " t.tms";
362
		$sql .= " FROM ".MAIN_DB_PREFIX."element_resources as t";
363
		$sql .= " WHERE t.rowid = ".((int) $id);
364
365
		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
366
		$resql = $this->db->query($sql);
367
		if ($resql) {
368
			if ($this->db->num_rows($resql)) {
369
				$obj = $this->db->fetch_object($resql);
370
371
				$this->id = $obj->rowid;
372
				$this->resource_id = $obj->resource_id;
373
				$this->resource_type	= $obj->resource_type;
374
				$this->element_id = $obj->element_id;
375
				$this->element_type		= $obj->element_type;
376
				$this->busy = $obj->busy;
377
				$this->mandatory = $obj->mandatory;
378
				$this->fk_user_create = $obj->fk_user_create;
379
380
				if ($obj->resource_id && $obj->resource_type) {
381
					$this->objresource = fetchObjectByElement($obj->resource_id, $obj->resource_type);
382
				}
383
				if ($obj->element_id && $obj->element_type) {
384
					$this->objelement = fetchObjectByElement($obj->element_id, $obj->element_type);
385
				}
386
			}
387
			$this->db->free($resql);
388
389
			return $this->id;
390
		} else {
391
			$this->error = "Error ".$this->db->lasterror();
392
			return -1;
393
		}
394
	}
395
396
	/**
397
	 *    Delete a resource object
398
	 *
399
	 *    @param	int		$rowid			Id of resource line to delete
400
	 *    @param	int		$notrigger		Disable all triggers
401
	 *    @return   int						>0 if OK, <0 if KO
402
	 */
403
	public function delete($rowid, $notrigger = 0)
404
	{
405
		global $user, $langs, $conf;
406
		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
407
408
		$error = 0;
409
410
		$this->db->begin();
411
412
		$sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
413
		$sql .= " WHERE rowid = ".((int) $rowid);
414
415
		dol_syslog(get_class($this), LOG_DEBUG);
416
		if ($this->db->query($sql)) {
417
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
418
			$sql .= " WHERE element_type='resource' AND resource_id = ".((int) $rowid);
419
			dol_syslog(get_class($this)."::delete", LOG_DEBUG);
420
			$resql = $this->db->query($sql);
421
			if (!$resql) {
422
				$this->error = $this->db->lasterror();
423
				$error++;
424
			}
425
		} else {
426
			$this->error = $this->db->lasterror();
427
			$error++;
428
		}
429
430
		// Removed extrafields
431
		if (!$error) {
432
			$result = $this->deleteExtraFields();
433
			if ($result < 0) {
434
				$error++;
435
				dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
436
			}
437
		}
438
439
		if (!$notrigger) {
440
			// Call trigger
441
			$result = $this->call_trigger('RESOURCE_DELETE', $user);
442
			if ($result < 0) {
443
				$error++;
444
			}
445
			// End call triggers
446
		}
447
448
		if (!$error) {
449
			// We remove directory
450
			$ref = dol_sanitizeFileName($this->ref);
451
			if (!empty($conf->resource->dir_output)) {
452
				$dir = $conf->resource->dir_output."/".dol_sanitizeFileName($this->ref);
453
				if (file_exists($dir)) {
454
					$res = @dol_delete_dir_recursive($dir);
455
					if (!$res) {
456
						$this->errors[] = 'ErrorFailToDeleteDir';
457
						$error++;
458
					}
459
				}
460
			}
461
		}
462
463
		if (!$error) {
464
			$this->db->commit();
465
			return 1;
466
		} else {
467
			$this->db->rollback();
468
			return -1;
469
		}
470
	}
471
472
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
473
	/**
474
	 *	Load resource objects into $this->lines
475
	 *
476
	 *  @param	string		$sortorder    sort order
477
	 *  @param	string		$sortfield    sort field
478
	 *  @param	int			$limit		  limit page
479
	 *  @param	int			$offset    	  page
480
	 *  @param	array		$filter    	  filter output
481
	 *  @return int          	<0 if KO, >0 if OK
482
	 */
483
	public function fetchAll($sortorder, $sortfield, $limit, $offset, $filter = '')
484
	{
485
		// phpcs:enable
486
		global $conf;
487
488
		require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
489
		$extrafields = new ExtraFields($this->db);
490
491
		$sql = "SELECT ";
492
		$sql .= " t.rowid,";
493
		$sql .= " t.entity,";
494
		$sql .= " t.ref,";
495
		$sql .= " t.description,";
496
		$sql .= " t.fk_country,";
497
		$sql .= " t.fk_code_type_resource,";
498
		$sql .= " t.tms,";
499
		// Add fields from extrafields
500
		if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['label'])) {
501
			foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
502
				$sql .= ($extrafields->attributes[$this->table_element]['type'][$key] != 'separate' ? "ef.".$key." as options_".$key.', ' : '');
503
			}
504
		}
505
		$sql .= " ty.label as type_label";
506
		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
507
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_resource as ty ON ty.code=t.fk_code_type_resource";
508
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$this->table_element."_extrafields as ef ON ef.fk_object=t.rowid";
509
		$sql .= " WHERE t.entity IN (".getEntity('resource').")";
510
		// Manage filter
511
		if (!empty($filter)) {
512
			foreach ($filter as $key => $value) {
513
				if (strpos($key, 'date')) {
514
					$sql .= " AND ".$key." = '".$this->db->idate($value)."'";
515
				} elseif (strpos($key, 'ef.') !== false) {
516
					$sql .= $value;
517
				} else {
518
					$sql .= " AND ".$key." LIKE '%".$this->db->escape($value)."%'";
519
				}
520
			}
521
		}
522
		$sql .= $this->db->order($sortfield, $sortorder);
523
		$this->num_all = 0;
524
		if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
525
			$result = $this->db->query($sql);
526
			$this->num_all = $this->db->num_rows($result);
527
		}
528
		if ($limit) {
529
			$sql .= $this->db->plimit($limit, $offset);
530
		}
531
		dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG);
532
533
		$this->lines = array();
534
		$resql = $this->db->query($sql);
535
		if ($resql) {
536
			$num = $this->db->num_rows($resql);
537
			if ($num) {
538
				while ($obj = $this->db->fetch_object($resql)) {
539
					$line = new Dolresource($this->db);
540
					$line->id = $obj->rowid;
541
					$line->ref = $obj->ref;
542
					$line->description = $obj->description;
543
					$line->country_id = $obj->fk_country;
544
					$line->fk_code_type_resource = $obj->fk_code_type_resource;
545
					$line->type_label = $obj->type_label;
546
547
					// fetch optionals attributes and labels
548
549
					$line->fetch_optionals();
550
551
					$this->lines[] = $line;
552
				}
553
				$this->db->free($resql);
554
			}
555
			return $num;
556
		} else {
557
			$this->error = $this->db->lasterror();
558
			return -1;
559
		}
560
	}
561
562
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
563
	/**
564
	 *  Update element resource into database
565
	 *
566
	 *  @param	User	$user        User that modifies
567
	 *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
568
	 *  @return int     		   	 <0 if KO, >0 if OK
569
	 */
570
	public function update_element_resource($user = null, $notrigger = 0)
571
	{
572
		// phpcs:enable
573
		global $conf, $langs;
574
		$error = 0;
575
576
		// Clean parameters
577
		if (isset($this->resource_id)) {
578
			$this->resource_id = trim($this->resource_id);
579
		}
580
		if (isset($this->resource_type)) {
581
			$this->resource_type = trim($this->resource_type);
582
		}
583
		if (isset($this->element_id)) {
584
			$this->element_id = trim($this->element_id);
585
		}
586
		if (isset($this->element_type)) {
587
			$this->element_type = trim($this->element_type);
588
		}
589
		if (isset($this->busy)) {
590
			$this->busy = trim($this->busy);
591
		}
592
		if (isset($this->mandatory)) {
593
			$this->mandatory = trim($this->mandatory);
594
		}
595
596
		// Update request
597
		$sql = "UPDATE ".MAIN_DB_PREFIX."element_resources SET";
598
		$sql .= " resource_id=".(isset($this->resource_id) ? "'".$this->db->escape($this->resource_id)."'" : "null").",";
599
		$sql .= " resource_type=".(isset($this->resource_type) ? "'".$this->db->escape($this->resource_type)."'" : "null").",";
600
		$sql .= " element_id=".(isset($this->element_id) ? $this->element_id : "null").",";
601
		$sql .= " element_type=".(isset($this->element_type) ? "'".$this->db->escape($this->element_type)."'" : "null").",";
602
		$sql .= " busy=".(isset($this->busy) ? $this->busy : "null").",";
603
		$sql .= " mandatory=".(isset($this->mandatory) ? $this->mandatory : "null").",";
604
		$sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null')."";
605
606
		$sql .= " WHERE rowid=".((int) $this->id);
607
608
		$this->db->begin();
609
610
		dol_syslog(get_class($this)."::update", LOG_DEBUG);
611
		$resql = $this->db->query($sql);
612
		if (!$resql) {
613
			$error++; $this->errors[] = "Error ".$this->db->lasterror();
614
		}
615
616
		if (!$error) {
617
			if (!$notrigger) {
618
				// Call trigger
619
				$result = $this->call_trigger('RESOURCE_MODIFY', $user);
620
				if ($result < 0) {
621
					$error++;
622
				}
623
				// End call triggers
624
			}
625
		}
626
627
		// Commit or rollback
628
		if ($error) {
629
			foreach ($this->errors as $errmsg) {
630
				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
631
				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
632
			}
633
			$this->db->rollback();
634
			return -1 * $error;
635
		} else {
636
			$this->db->commit();
637
			return 1;
638
		}
639
	}
640
641
642
	/**
643
	 * Return an array with resources linked to the element
644
	 *
645
	 * @param string    $element        Element
646
	 * @param int       $element_id     Id
647
	 * @param string    $resource_type  Type
648
	 * @return array                    Aray of resources
649
	 */
650
	public function getElementResources($element, $element_id, $resource_type = '')
651
	{
652
		$resources = array();
653
654
		// Links beetween objects are stored in this table
655
		$sql = 'SELECT rowid, resource_id, resource_type, busy, mandatory';
656
		$sql .= ' FROM '.MAIN_DB_PREFIX.'element_resources';
657
		$sql .= " WHERE element_id=".((int) $element_id)." AND element_type='".$this->db->escape($element)."'";
658
		if ($resource_type) {
659
			$sql .= " AND resource_type LIKE '%".$this->db->escape($resource_type)."%'";
660
		}
661
		$sql .= ' ORDER BY resource_type';
662
663
		dol_syslog(get_class($this)."::getElementResources", LOG_DEBUG);
664
665
		$resources = array();
666
		$resql = $this->db->query($sql);
667
		if ($resql) {
668
			$num = $this->db->num_rows($resql);
669
			$i = 0;
670
			while ($i < $num) {
671
				$obj = $this->db->fetch_object($resql);
672
673
				$resources[$i] = array(
674
					'rowid' => $obj->rowid,
675
					'resource_id' => $obj->resource_id,
676
					'resource_type'=>$obj->resource_type,
677
					'busy'=>$obj->busy,
678
					'mandatory'=>$obj->mandatory
679
				);
680
				$i++;
681
			}
682
		}
683
684
		return $resources;
685
	}
686
687
	/**
688
	 *  Return an int number of resources linked to the element
689
	 *
690
	 *  @param		string	$element		Element type
691
	 *  @param		int		$element_id		Element id
692
	 *  @return     int						Nb of resources loaded
693
	 */
694
	public function fetchElementResources($element, $element_id)
695
	{
696
		$resources = $this->getElementResources($element, $element_id);
697
		$i = 0;
698
		foreach ($resources as $nb => $resource) {
699
			$this->lines[$i] = fetchObjectByElement($resource['resource_id'], $resource['resource_type']);
700
			$i++;
701
		}
702
		return $i;
703
	}
704
705
706
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
707
	/**
708
	 *      Load in cache resource type code (setup in dictionary)
709
	 *
710
	 *      @return     int             Number of lines loaded, 0 if already loaded, <0 if KO
711
	 */
712
	public function load_cache_code_type_resource()
713
	{
714
		// phpcs:enable
715
		global $langs;
716
717
		if (is_array($this->cache_code_type_resource) && count($this->cache_code_type_resource)) {
718
			return 0; // Cache deja charge
719
		}
720
721
		$sql = "SELECT rowid, code, label, active";
722
		$sql .= " FROM ".MAIN_DB_PREFIX."c_type_resource";
723
		$sql .= " WHERE active > 0";
724
		$sql .= " ORDER BY rowid";
725
		dol_syslog(get_class($this)."::load_cache_code_type_resource", LOG_DEBUG);
726
		$resql = $this->db->query($sql);
727
		if ($resql) {
728
			$num = $this->db->num_rows($resql);
729
			$i = 0;
730
			while ($i < $num) {
731
				$obj = $this->db->fetch_object($resql);
732
				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
733
				$label = ($langs->trans("ResourceTypeShort".$obj->code) != ("ResourceTypeShort".$obj->code) ? $langs->trans("ResourceTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
734
				$this->cache_code_type_resource[$obj->rowid]['code'] = $obj->code;
735
				$this->cache_code_type_resource[$obj->rowid]['label'] = $label;
736
				$this->cache_code_type_resource[$obj->rowid]['active'] = $obj->active;
737
				$i++;
738
			}
739
			return $num;
740
		} else {
741
			dol_print_error($this->db);
742
			return -1;
743
		}
744
	}
745
746
	/**
747
	 *	Return clicable link of object (with eventually picto)
748
	 *
749
	 *	@param      int		$withpicto					Add picto into link
750
	 *	@param      string	$option						Where point the link ('compta', 'expedition', 'document', ...)
751
	 *	@param      string	$get_params    				Parametres added to url
752
	 *	@param		int  	$notooltip					1=Disable tooltip
753
	 *  @param  	string  $morecss                    Add more css on link
754
	 *  @param  	int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
755
	 *	@return     string          					String with URL
756
	 */
757
	public function getNomUrl($withpicto = 0, $option = '', $get_params = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
758
	{
759
		global $conf, $langs, $hookmanager;
760
761
		$result = '';
762
		$label = img_picto('', $this->picto).' <u>'.$langs->trans("Resource").'</u>';
763
		$label .= '<br>';
764
		$label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
765
		/*if (isset($this->status)) {
766
			$label.= '<br><b>' . $langs->trans("Status").":</b> ".$this->getLibStatut(5);
767
		}*/
768
		if (isset($this->type_label)) {
769
			$label .= '<br><b>'.$langs->trans("ResourceType").":</b> ".$this->type_label;
770
		}
771
772
		$url = DOL_URL_ROOT.'/resource/card.php?id='.$this->id;
773
774
		if ($option != 'nolink') {
775
			// Add param to save lastsearch_values or not
776
			$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
777
			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
778
				$add_save_lastsearch_values = 1;
779
			}
780
			if ($add_save_lastsearch_values) {
781
				$url .= '&save_lastsearch_values=1';
782
			}
783
		}
784
785
		$linkclose = '';
786
		if (empty($notooltip)) {
787
			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
788
				$label = $langs->trans("ShowMyObject");
789
				$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
790
			}
791
			$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
792
			$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
793
		} else {
794
			$linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
795
		}
796
797
		$linkstart = '<a href="'.$url.$get_params.'"';
798
		$linkstart .= $linkclose.'>';
799
		$linkend = '</a>';
800
		/*$linkstart = '<a href="'.DOL_URL_ROOT.'/resource/card.php?id='.$this->id.$get_params.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
801
		$linkend = '</a>';*/
802
803
		$result .= $linkstart;
804
		if ($withpicto) {
805
			$result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
806
		}
807
		if ($withpicto != 2) {
808
			$result .= $this->ref;
809
		}
810
		$result .= $linkend;
811
812
		global $action;
813
		$hookmanager->initHooks(array($this->element . 'dao'));
814
		$parameters = array('id'=>$this->id, 'getnomurl' => &$result);
815
		$reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
816
		if ($reshook > 0) {
817
			$result = $hookmanager->resPrint;
818
		} else {
819
			$result .= $hookmanager->resPrint;
820
		}
821
		return $result;
822
	}
823
824
825
	/**
826
	 *  Retourne le libelle du status d'un user (actif, inactif)
827
	 *
828
	 *  @param	int		$mode          0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
829
	 *  @return	string 			       Label of status
830
	 */
831
	public function getLibStatut($mode = 0)
832
	{
833
		return $this->LibStatut($this->status, $mode);
834
	}
835
836
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
837
	/**
838
	 *  Return the status
839
	 *
840
	 *  @param	int		$status        	Id status
841
	 *  @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
842
	 *  @return string 			       	Label of status
843
	 */
844
	public static function LibStatut($status, $mode = 0)
845
	{
846
		// phpcs:enable
847
		global $langs;
848
849
		return '';
850
	}
851
852
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
853
	/**
854
	 *      Charge indicateurs this->nb de tableau de bord
855
	 *
856
	 *      @return     int         <0 if KO, >0 if OK
857
	 */
858
	public function load_state_board()
859
	{
860
		// phpcs:enable
861
		global $conf;
862
863
		$this->nb = array();
864
865
		$sql = "SELECT count(r.rowid) as nb";
866
		$sql .= " FROM ".MAIN_DB_PREFIX."resource as r";
867
		$sql .= " WHERE r.entity IN (".getEntity('resource').")";
868
869
		$resql = $this->db->query($sql);
870
		if ($resql) {
871
			while ($obj = $this->db->fetch_object($resql)) {
872
				$this->nb["dolresource"] = $obj->nb;
873
			}
874
			$this->db->free($resql);
875
			return 1;
876
		} else {
877
			dol_print_error($this->db);
878
			$this->error = $this->db->error();
879
			return -1;
880
		}
881
	}
882
}
883