Completed
Branch develop (c98f0b)
by
unknown
29:30
created

Dolresource::create()   F

Complexity

Conditions 24
Paths > 20000

Size

Total Lines 101
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 24
eloc 56
nc 393216
nop 2
dl 0
loc 101
rs 2
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) 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 <http://www.gnu.org/licenses/>.
16
 */
17
18
/**
19
 *  \file      	resource/class/resource.class.php
20
 *  \ingroup    resource
21
 *  \brief      Class file for resource object
22
23
 */
24
25
require_once DOL_DOCUMENT_ROOT."/core/class/commonobject.class.php";
26
require_once DOL_DOCUMENT_ROOT."/core/lib/functions2.lib.php";
27
28
/**
29
 *	DAO Resource object
30
 */
31
class Dolresource extends CommonObject
32
{
33
	public $element='dolresource';			//!< Id that identify managed objects
34
	public $table_element='resource';	//!< Name of table without prefix where object is stored
35
    public $picto = 'resource';
36
    
37
	public $resource_id;
38
	public $resource_type;
39
	public $element_id;
40
	public $element_type;
41
	public $busy;
42
	public $mandatory;
43
	public $fk_user_create;
44
	public $type_label;
45
	public $tms='';
46
47
    /**
48
     *  Constructor
49
     *
50
     *  @param	DoliDb		$db      Database handler
51
     */
52
    function __construct($db)
53
    {
54
        $this->db = $db;
55
        return 1;
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
56
    }
57
58
    /**
59
     *  Create object into database
60
     *
61
     *  @param	User	$user        User that creates
62
     *  @param  int		$notrigger   0=launch triggers after, 1=disable triggers
63
     *  @return int      		   	 <0 if KO, Id of created object if OK
64
     */
65
    function create($user, $notrigger=0)
66
    {
67
    	global $conf, $langs, $hookmanager;
68
    	$error=0;
69
70
    	// Clean parameters
71
72
    	if (isset($this->ref)) $this->ref=trim($this->ref);
73
    	if (isset($this->description)) $this->description=trim($this->description);
74
    	if (isset($this->fk_code_type_resource)) $this->fk_code_type_resource=trim($this->fk_code_type_resource);
75
    	if (isset($this->note_public)) $this->note_public=trim($this->note_public);
76
    	if (isset($this->note_private)) $this->note_private=trim($this->note_private);
77
78
79
    	// Insert request
80
    	$sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element."(";
81
82
    	$sql.= "entity,";
83
    	$sql.= "ref,";
84
    	$sql.= "description,";
85
    	$sql.= "fk_code_type_resource,";
86
    	$sql.= "note_public,";
87
    	$sql.= "note_private";
88
89
    	$sql.= ") VALUES (";
90
91
    	$sql.= $conf->entity.", ";
92
    	$sql.= " ".(! isset($this->ref)?'NULL':"'".$this->db->escape($this->ref)."'").",";
93
    	$sql.= " ".(! isset($this->description)?'NULL':"'".$this->db->escape($this->description)."'").",";
94
    	$sql.= " ".(! isset($this->fk_code_type_resource)?'NULL':"'".$this->db->escape($this->fk_code_type_resource)."'").",";
95
    	$sql.= " ".(! isset($this->note_public)?'NULL':"'".$this->db->escape($this->note_public)."'").",";
96
    	$sql.= " ".(! isset($this->note_private)?'NULL':"'".$this->db->escape($this->note_private)."'");
97
98
    	$sql.= ")";
99
100
    	$this->db->begin();
101
102
    	dol_syslog(get_class($this)."::create", LOG_DEBUG);
103
    	$resql=$this->db->query($sql);
104
    	if (! $resql) {
105
    		$error++; $this->errors[]="Error ".$this->db->lasterror();
106
    	}
107
108
    	if (! $error)
109
    	{
110
    		$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
111
    	}
112
113
    	if (! $error)
114
    	{
115
    		$action='create';
116
117
    		// Actions on extra fields (by external module or standard code)
118
    		// TODO le hook fait double emploi avec le trigger !!
119
    		$hookmanager->initHooks(array('actioncommdao'));
120
    		$parameters=array('actcomm'=>$this->id);
121
    		$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
122
    		if (empty($reshook))
123
    		{
124
    			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
125
    			{
126
    				$result=$this->insertExtraFields();
127
    				if ($result < 0)
128
    				{
129
    					$error++;
130
    				}
131
    			}
132
    		}
133
    		else if ($reshook < 0) $error++;
134
    	}
135
136
    	if (! $error)
137
    	{
138
    		if (! $notrigger)
139
    		{
140
    			//// Call triggers
141
    			include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
142
    			$interface=new Interfaces($this->db);
143
    			$result=$interface->run_triggers('RESOURCE_CREATE',$this,$user,$langs,$conf);
144
    			if ($result < 0) { $error++; $this->errors=$interface->errors; }
145
    			//// End call triggers
146
    		}
147
    	}
148
149
    	// Commit or rollback
150
    	if ($error)
151
    	{
152
    		foreach($this->errors as $errmsg)
153
    		{
154
    			dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
155
    			$this->error.=($this->error?', '.$errmsg:$errmsg);
156
    		}
157
    		$this->db->rollback();
158
    		return -1*$error;
159
    	}
160
    	else
161
    	{
162
    		$this->db->commit();
163
    		return $this->id;
164
    	}
165
    }
166
167
    /**
168
     *    Load object in memory from database
169
     *
170
     *    @param      int	$id          id object
171
     *    @return     int         <0 if KO, >0 if OK
172
     */
173
    function fetch($id)
174
    {
175
    	global $langs;
176
    	$sql = "SELECT";
177
    	$sql.= " t.rowid,";
178
    	$sql.= " t.entity,";
179
    	$sql.= " t.ref,";
180
    	$sql.= " t.description,";
181
    	$sql.= " t.fk_code_type_resource,";
182
    	$sql.= " t.note_public,";
183
    	$sql.= " t.note_private,";
184
    	$sql.= " t.tms,";
185
    	$sql.= " ty.label as type_label";
186
    	$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
187
    	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_resource as ty ON ty.code=t.fk_code_type_resource";
188
    	$sql.= " WHERE t.rowid = ".$this->db->escape($id);
189
190
    	dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
191
    	$resql=$this->db->query($sql);
192
    	if ($resql)
193
    	{
194
    		if ($this->db->num_rows($resql))
195
    		{
196
    			$obj = $this->db->fetch_object($resql);
197
198
    			$this->id						=	$obj->rowid;
199
    			$this->entity					=	$obj->entity;
200
    			$this->ref						=	$obj->ref;
201
    			$this->description				=	$obj->description;
202
    			$this->fk_code_type_resource	=	$obj->fk_code_type_resource;
203
    			$this->note_public				=	$obj->note_public;
204
    			$this->note_private				=	$obj->note_private;
205
    			$this->type_label				=	$obj->type_label;
206
207
    			// Retreive all extrafield for thirdparty
208
    			// fetch optionals attributes and labels
209
    			require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php');
210
    			$extrafields=new ExtraFields($this->db);
211
    			$extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
212
    			$this->fetch_optionals($this->id,$extralabels);
213
214
    		}
215
    		$this->db->free($resql);
216
217
    		return $this->id;
218
    	}
219
    	else
220
    	{
221
    		$this->error="Error ".$this->db->lasterror();
222
    		dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
223
    		return -1;
224
    	}
225
    }
226
227
    /**
228
     *  Update object into database
229
     *
230
     *  @param	User	$user        User that modifies
231
     *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
232
     *  @return int     		   	 <0 if KO, >0 if OK
233
     */
234
    function update($user=null, $notrigger=0)
235
    {
236
    	global $conf, $langs, $hookmanager;
237
    	$error=0;
238
239
    	// Clean parameters
240
    	if (isset($this->ref)) $this->ref=trim($this->ref);
241
    	if (isset($this->fk_code_type_resource)) $this->fk_code_type_resource=trim($this->fk_code_type_resource);
242
    	if (isset($this->description)) $this->description=trim($this->description);
243
244
    	// Update request
245
    	$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
246
    	$sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").",";
247
    	$sql.= " description=".(isset($this->description)?"'".$this->db->escape($this->description)."'":"null").",";
248
    	$sql.= " fk_code_type_resource=".(isset($this->fk_code_type_resource)?"'".$this->db->escape($this->fk_code_type_resource)."'":"null").",";
249
    	$sql.= " tms=".(dol_strlen($this->tms)!=0 ? "'".$this->db->idate($this->tms)."'" : 'null')."";
250
    	$sql.= " WHERE rowid=".$this->id;
251
252
    	$this->db->begin();
253
254
    	dol_syslog(get_class($this)."::update", LOG_DEBUG);
255
    	$resql = $this->db->query($sql);
256
    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
257
258
    	if (! $error)
259
    	{
260
    		if (! $notrigger)
261
    		{
262
    			// Uncomment this and change MYOBJECT to your own tag if you
263
    			// want this action calls a trigger.
264
265
    			//// Call triggers
266
    			include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
267
    			$interface=new Interfaces($this->db);
268
    			$result=$interface->run_triggers('RESOURCE_MODIFY',$this,$user,$langs,$conf);
0 ignored issues
show
Bug introduced by
It seems like $user defined by parameter $user on line 234 can be null; however, Interfaces::run_triggers() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
269
    			if ($result < 0) { $error++; $this->errors=$interface->errors; }
270
    			//// End call triggers
271
    		}
272
    	}
273
    	if (! $error)
274
    	{
275
	    	$action='update';
276
277
	    	// Actions on extra fields (by external module or standard code)
278
	    	// TODO le hook fait double emploi avec le trigger !!
279
	    	$hookmanager->initHooks(array('actioncommdao'));
280
	    	$parameters=array('actcomm'=>$this->id);
281
	    	$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
282
	    	if (empty($reshook))
283
	    	{
284
	    		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
285
	    		{
286
	    			$result=$this->insertExtraFields();
287
	    			if ($result < 0)
288
	    			{
289
	    				$error++;
290
	    			}
291
	    		}
292
	    	}
293
	    	else if ($reshook < 0) $error++;
294
    	}
295
296
    	// Commit or rollback
297
    	if ($error)
298
    	{
299
    		foreach($this->errors as $errmsg)
300
    		{
301
    			dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
302
    			$this->error.=($this->error?', '.$errmsg:$errmsg);
303
    		}
304
    		$this->db->rollback();
305
    		return -1*$error;
306
    	}
307
    	else
308
    	{
309
    		$this->db->commit();
310
    		return 1;
311
    	}
312
    }
313
314
    /**
315
     *    Load object in memory from database
316
     *
317
     *    @param      int	$id          id object
318
     *    @return     int         <0 if KO, >0 if OK
319
     */
320
    function fetch_element_resource($id)
321
    {
322
    	global $langs;
323
    	$sql = "SELECT";
324
    	$sql.= " t.rowid,";
325
   		$sql.= " t.resource_id,";
326
		$sql.= " t.resource_type,";
327
		$sql.= " t.element_id,";
328
		$sql.= " t.element_type,";
329
		$sql.= " t.busy,";
330
		$sql.= " t.mandatory,";
331
		$sql.= " t.fk_user_create,";
332
		$sql.= " t.tms";
333
		$sql.= " FROM ".MAIN_DB_PREFIX."element_resources as t";
334
    	$sql.= " WHERE t.rowid = ".$this->db->escape($id);
335
336
    	dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
337
    	$resql=$this->db->query($sql);
338
    	if ($resql)
339
    	{
340
    		if ($this->db->num_rows($resql))
341
    		{
342
    			$obj = $this->db->fetch_object($resql);
343
344
    			$this->id				=	$obj->rowid;
345
    			$this->resource_id		=	$obj->resource_id;
346
    			$this->resource_type	=	$obj->resource_type;
347
    			$this->element_id		=	$obj->element_id;
348
    			$this->element_type		=	$obj->element_type;
349
    			$this->busy				=	$obj->busy;
350
    			$this->mandatory		=	$obj->mandatory;
351
    			$this->fk_user_create	=	$obj->fk_user_create;
352
353
				if($obj->resource_id && $obj->resource_type) {
354
					$this->objresource = fetchObjectByElement($obj->resource_id,$obj->resource_type);
355
				}
356
				if($obj->element_id && $obj->element_type) {
357
					$this->objelement = fetchObjectByElement($obj->element_id,$obj->element_type);
358
				}
359
360
    		}
361
    		$this->db->free($resql);
362
363
    		return $this->id;
364
    	}
365
    	else
366
    	{
367
    		$this->error="Error ".$this->db->lasterror();
368
    		return -1;
369
    	}
370
    }
371
372
    /**
373
     *    Delete a resource object
374
     *
375
     *    @param	int		$rowid			Id of resource line to delete
376
     *    @param	int		$notrigger		Disable all triggers
377
     *    @return   int						>0 if OK, <0 if KO
378
     */
379
    function delete($rowid, $notrigger=0)
380
    {
381
        global $user,$langs,$conf;
382
383
        $error=0;
384
385
        $this->db->begin();
386
387
        $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
388
        $sql.= " WHERE rowid =".$rowid;
389
390
        dol_syslog(get_class($this), LOG_DEBUG);
391
        if ($this->db->query($sql))
392
        {
393
            $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
394
            $sql.= " WHERE element_type='resource' AND resource_id =".$this->db->escape($rowid);
395
            dol_syslog(get_class($this)."::delete", LOG_DEBUG);
396
            $resql=$this->db->query($sql);
397
            if (!$resql)
398
            {
399
            	$this->error=$this->db->lasterror();
400
            	$error++;
401
            }
402
        }
403
        else
404
        {
405
            $this->error=$this->db->lasterror();
406
            $error++;
407
        }
408
409
        // Removed extrafields
410
        if (! $error) {
411
        	$result=$this->deleteExtraFields();
412
        	if ($result < 0)
413
        	{
414
        		$error++;
415
        		dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
416
        	}
417
        }
418
419
        if (! $notrigger)
420
        {
421
        	// Call trigger
422
        	$result=$this->call_trigger('RESOURCE_DELETE',$user);
423
        	if ($result < 0) $error++;
424
        	// End call triggers
425
        }
426
427
        if (! $error)
428
        {
429
        	$this->db->commit();
430
        	return 1;
431
        }
432
        else
433
        {
434
        	$this->db->rollback();
435
        	return -1;
436
        }
437
    }
438
439
    /**
440
     *	Load resource objects into $this->lines
441
     *
442
     *  @param	string		$sortorder    sort order
443
     *  @param	string		$sortfield    sort field
444
     *  @param	int			$limit		  limit page
445
     *  @param	int			$offset    	  page
446
     *  @param	array		$filter    	  filter output
447
     *  @return int          	<0 if KO, >0 if OK
448
     */
449
    function fetch_all($sortorder, $sortfield, $limit, $offset, $filter='')
450
    {
451
    	global $conf;
452
    	$sql="SELECT ";
453
    	$sql.= " t.rowid,";
454
    	$sql.= " t.entity,";
455
    	$sql.= " t.ref,";
456
    	$sql.= " t.description,";
457
    	$sql.= " t.fk_code_type_resource,";
458
    	$sql.= " t.tms,";
459
460
    	require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php');
461
    	$extrafields=new ExtraFields($this->db);
462
    	$extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
463
    	if (is_array($extralabels) && count($extralabels)>0) {
464
    		foreach($extralabels as $code=>$label) {
465
    			$sql.= " ef.".$code." as extra_".$code.",";
466
    		}
467
    	}
468
469
    	$sql.= " ty.label as type_label";
470
    	$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
471
    	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_resource as ty ON ty.code=t.fk_code_type_resource";
472
    	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX.$this->table_element."_extrafields as ef ON ef.fk_object=t.rowid";
473
    	$sql.= " WHERE t.entity IN (".getEntity('resource',1).")";
474
475
    	//Manage filter
476
    	if (!empty($filter)){
477
    		foreach($filter as $key => $value) {
478
    			if (strpos($key,'date')) {
479
    				$sql.= ' AND '.$key.' = \''.$this->db->idate($value).'\'';
480
    			}
481
    			elseif (strpos($key,'ef.')!==false){
482
    				$sql.= $value;
483
    			}
484
    			else {
485
    				$sql.= ' AND '.$key.' LIKE \'%'.$value.'%\'';
486
    			}
487
    		}
488
    	}
489
    	$sql.= $this->db->order($sortfield,$sortorder);
490
        $this->num_all = 0;
491
        if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
492
        {
493
            $result = $this->db->query($sql);
494
            $this->num_all = $this->db->num_rows($result);
495
        }
496
    	if ($limit) $sql.= $this->db->plimit($limit, $offset);
497
    	dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG);
498
499
    	$resql=$this->db->query($sql);
500
    	if ($resql)
501
    	{
502
    		$num = $this->db->num_rows($resql);
503
    		if ($num)
504
    		{
505
    			$this->lines=array();
506
    			while ($obj = $this->db->fetch_object($resql))
507
    			{
508
    				$line = new Dolresource($this->db);
509
    				$line->id						=	$obj->rowid;
510
    				$line->ref						=	$obj->ref;
511
    				$line->description				=	$obj->description;
512
    				$line->fk_code_type_resource	=	$obj->fk_code_type_resource;
513
    				$line->type_label				=	$obj->type_label;
514
515
    				// Retreive all extrafield for thirdparty
516
    				// fetch optionals attributes and labels
517
518
    				$line->fetch_optionals($line->id,$extralabels);
519
520
    				$this->lines[] = $line;
521
    			}
522
    			$this->db->free($resql);
523
    		}
524
    		return $num;
525
    	}
526
    	else
527
    	{
528
    		$this->error = $this->db->lasterror();
529
    		return -1;
530
    	}
531
532
    }
533
534
     /**
535
     *	Load all objects into $this->lines
536
     *
537
     *  @param	string		$sortorder    sort order
538
	 *  @param	string		$sortfield    sort field
539
	 *  @param	int			$limit		  limit page
540
	 *  @param	int			$offset    	  page
541
	 *  @param	array		$filter    	  filter output
542
	 *  @return int          	<0 if KO, >0 if OK
543
     */
544
    function fetch_all_resources($sortorder, $sortfield, $limit, $offset, $filter='')
545
    {
546
   		global $conf;
547
   		$sql="SELECT ";
548
   		$sql.= " t.rowid,";
549
   		$sql.= " t.resource_id,";
550
		$sql.= " t.resource_type,";
551
		$sql.= " t.element_id,";
552
		$sql.= " t.element_type,";
553
		$sql.= " t.busy,";
554
		$sql.= " t.mandatory,";
555
		$sql.= " t.fk_user_create,";
556
		$sql.= " t.tms";
557
   		$sql.= ' FROM '.MAIN_DB_PREFIX .'element_resources as t ';
558
   		$sql.= " WHERE t.entity IN (".getEntity('resource',1).")";
559
560
   		//Manage filter
561
   		if (!empty($filter)){
562
   			foreach($filter as $key => $value) {
563
   				if (strpos($key,'date')) {
564
   					$sql.= ' AND '.$key.' = \''.$this->db->idate($value).'\'';
565
   				}
566
   				else {
567
   					$sql.= ' AND '.$key.' LIKE \'%'.$value.'%\'';
568
   				}
569
   			}
570
   		}
571
    	$sql.= $this->db->order($sortfield,$sortorder);
572
   		if ($limit) $sql.= $this->db->plimit($limit+1,$offset);
573
   		dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG);
574
575
   		$resql=$this->db->query($sql);
576
   		if ($resql)
577
   		{
578
   			$num = $this->db->num_rows($resql);
579
   			if ($num)
580
   			{
581
   				while ($obj = $this->db->fetch_object($resql))
582
   				{
583
   					$line = new Dolresource($this->db);
584
   					$line->id				=	$obj->rowid;
585
   					$line->resource_id		=	$obj->resource_id;
586
   					$line->resource_type	=	$obj->resource_type;
587
   					$line->element_id		=	$obj->element_id;
588
   					$line->element_type		=	$obj->element_type;
589
   					$line->busy				=	$obj->busy;
590
   					$line->mandatory		=	$obj->mandatory;
591
   					$line->fk_user_create	=	$obj->fk_user_create;
592
593
					if($obj->resource_id && $obj->resource_type)
594
						$line->objresource = fetchObjectByElement($obj->resource_id,$obj->resource_type);
595
					if($obj->element_id && $obj->element_type)
596
						$line->objelement = fetchObjectByElement($obj->element_id,$obj->element_type);
597
        			$this->lines[] = $line;
598
599
   				}
600
   				$this->db->free($resql);
601
   			}
602
   			return $num;
603
   		}
604
   		else
605
   		{
606
   			$this->error = $this->db->lasterror();
607
   			return -1;
608
   		}
609
610
    }
611
612
    /**
613
     *	Load all objects into $this->lines
614
     *
615
     *  @param	string		$sortorder    sort order
616
     *  @param	string		$sortfield    sort field
617
     *  @param	int			$limit		  limit page
618
     *  @param	int			$offset    	  page
619
     *  @param	array		$filter    	  filter output
620
     *  @return int          	<0 if KO, >0 if OK
621
     */
622
    function fetch_all_used($sortorder, $sortfield, $limit, $offset=1, $filter='')
623
    {
624
    	global $conf;
625
626
    	if ( ! $sortorder) $sortorder="ASC";
627
    	if ( ! $sortfield) $sortfield="t.rowid";
628
629
    	$sql="SELECT ";
630
    	$sql.= " t.rowid,";
631
    	$sql.= " t.resource_id,";
632
    	$sql.= " t.resource_type,";
633
    	$sql.= " t.element_id,";
634
    	$sql.= " t.element_type,";
635
    	$sql.= " t.busy,";
636
    	$sql.= " t.mandatory,";
637
    	$sql.= " t.fk_user_create,";
638
    	$sql.= " t.tms";
639
    	$sql.= ' FROM '.MAIN_DB_PREFIX .'element_resources as t ';
640
    	$sql.= " WHERE t.entity IN (".getEntity('resource',1).")";
641
642
    	//Manage filter
643
    	if (!empty($filter)){
644
    		foreach($filter as $key => $value) {
645
    			if (strpos($key,'date')) {
646
    				$sql.= ' AND '.$key.' = \''.$this->db->idate($value).'\'';
647
    			}
648
    			else {
649
    				$sql.= ' AND '.$key.' LIKE \'%'.$value.'%\'';
650
    			}
651
    		}
652
    	}
653
    	$sql.= $this->db->order($sortfield,$sortorder);
654
    	if ($limit) $sql.= $this->db->plimit($limit+1,$offset);
655
    	dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG);
656
657
    	$resql=$this->db->query($sql);
658
    	if ($resql)
659
    	{
660
    		$num = $this->db->num_rows($resql);
661
    		if ($num)
662
    		{
663
    			$this->lines=array();
664
    			while ($obj = $this->db->fetch_object($resql))
665
    			{
666
    				$line = new Dolresource($this->db);
667
    				$line->id				=	$obj->rowid;
668
    				$line->resource_id		=	$obj->resource_id;
669
    				$line->resource_type	=	$obj->resource_type;
670
    				$line->element_id		=	$obj->element_id;
671
    				$line->element_type		=	$obj->element_type;
672
    				$line->busy				=	$obj->busy;
673
    				$line->mandatory		=	$obj->mandatory;
674
    				$line->fk_user_create	=	$obj->fk_user_create;
675
676
    				$this->lines[] = fetchObjectByElement($obj->resource_id,$obj->resource_type);
677
    			}
678
    			$this->db->free($resql);
679
    		}
680
    		return $num;
681
    	}
682
    	else
683
    	{
684
    		$this->error = $this->db->lasterror();
685
    		return -1;
686
    	}
687
688
    }
689
690
    /**
691
     * Fetch all resources available, declared by modules
692
     * Load available resource in array $this->available_resources
693
     *
694
     * @return int 	number of available resources declared by modules
695
     * @deprecated, remplaced by hook getElementResources
696
     * @see getElementResources()
697
     */
698
    function fetch_all_available() {
699
    	global $conf;
700
701
    	if (! empty($conf->modules_parts['resources']))
702
    	{
703
    		$this->available_resources=(array) $conf->modules_parts['resources'];
704
705
    		return count($this->available_resources);
706
    	}
707
    	return 0;
708
    }
709
710
    /**
711
     *      Load properties id_previous and id_next
712
     *
713
     *      @param	string	$filter		Optional filter
714
     *	    @param  	int		$fieldid   	Name of field to use for the select MAX and MIN
715
     *	    @param	int		$nodbprefix		Do not include DB prefix to forge table name
716
     *      @return int         		<0 if KO, >0 if OK
717
     */
718
    function load_previous_next_ref($filter, $fieldid, $nodbprefix =0)
719
    {
720
    	global $conf, $user;
721
722
    	if (! $this->table_element)
723
    	{
724
    		dol_print_error('',get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
725
    		return -1;
726
    	}
727
728
    	// this->ismultientitymanaged contains
729
    	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
730
    	$alias = 's';
731
732
733
    	$sql = "SELECT MAX(te.".$fieldid.")";
734
    	$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element." as te";
735
    	if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && empty($user->rights->societe->client->voir))) $sql.= ", ".MAIN_DB_PREFIX."societe as s";	// If we need to link to societe to limit select to entity
736
    	if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc";
737
    	$sql.= " WHERE te.".$fieldid." < '".$this->db->escape($this->id)."'";
738
    	if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id;
739
    	if (! empty($filter)) $sql.=" AND ".$filter;
740
    	if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir)) $sql.= ' AND te.fk_soc = s.rowid';			// If we need to link to societe to limit select to entity
741
    	if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element, 1).')';
742
743
    	//print $sql."<br>";
744
    	$result = $this->db->query($sql);
745
    	if (! $result)
746
    	{
747
    		$this->error=$this->db->error();
748
    		return -1;
749
    	}
750
    	$row = $this->db->fetch_row($result);
751
    	$this->ref_previous = $row[0];
752
753
754
    	$sql = "SELECT MIN(te.".$fieldid.")";
755
    	$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element." as te";
756
    	if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir)) $sql.= ", ".MAIN_DB_PREFIX."societe as s";	// If we need to link to societe to limit select to entity
757
    	if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc";
758
    	$sql.= " WHERE te.".$fieldid." > '".$this->db->escape($this->id)."'";
759
    	if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id;
760
    	if (! empty($filter)) $sql.=" AND ".$filter;
761
    	if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir)) $sql.= ' AND te.fk_soc = s.rowid';			// If we need to link to societe to limit select to entity
762
    	if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element, 1).')';
763
    	// Rem: Bug in some mysql version: SELECT MIN(rowid) FROM llx_socpeople WHERE rowid > 1 when one row in database with rowid=1, returns 1 instead of null
764
765
    	//print $sql."<br>";
766
    	$result = $this->db->query($sql);
767
    	if (! $result)
768
    	{
769
    		$this->error=$this->db->error();
770
    		return -2;
771
    	}
772
    	$row = $this->db->fetch_row($result);
773
    	$this->ref_next = $row[0];
774
775
    	return 1;
776
    }
777
778
779
    /**
780
     *  Update element resource into database
781
     *
782
     *  @param	User	$user        User that modifies
783
     *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
784
     *  @return int     		   	 <0 if KO, >0 if OK
785
     */
786
    function update_element_resource($user=null, $notrigger=0)
787
    {
788
    	global $conf, $langs;
789
		$error=0;
790
791
		// Clean parameters
792
		if (isset($this->resource_id)) $this->resource_id=trim($this->resource_id);
793
		if (isset($this->resource_type)) $this->resource_type=trim($this->resource_type);
794
		if (isset($this->element_id)) $this->element_id=trim($this->element_id);
795
		if (isset($this->element_type)) $this->element_type=trim($this->element_type);
796
		if (isset($this->busy)) $this->busy=trim($this->busy);
797
		if (isset($this->mandatory)) $this->mandatory=trim($this->mandatory);
798
799
        // Update request
800
        $sql = "UPDATE ".MAIN_DB_PREFIX."element_resources SET";
801
		$sql.= " resource_id=".(isset($this->resource_id)?"'".$this->db->escape($this->resource_id)."'":"null").",";
802
		$sql.= " resource_type=".(isset($this->resource_type)?"'".$this->resource_type."'":"null").",";
803
		$sql.= " element_id=".(isset($this->element_id)?$this->element_id:"null").",";
804
		$sql.= " element_type=".(isset($this->element_type)?"'".$this->db->escape($this->element_type)."'":"null").",";
805
		$sql.= " busy=".(isset($this->busy)?$this->busy:"null").",";
806
		$sql.= " mandatory=".(isset($this->mandatory)?$this->mandatory:"null").",";
807
		$sql.= " tms=".(dol_strlen($this->tms)!=0 ? "'".$this->db->idate($this->tms)."'" : 'null')."";
808
809
        $sql.= " WHERE rowid=".$this->id;
810
811
		$this->db->begin();
812
813
		dol_syslog(get_class($this)."::update", LOG_DEBUG);
814
        $resql = $this->db->query($sql);
815
    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
816
817
		if (! $error)
818
		{
819
			if (! $notrigger)
820
			{
821
                // Call trigger
822
                $result=$this->call_trigger('RESOURCE_MODIFY',$user);
0 ignored issues
show
Bug introduced by
It seems like $user defined by parameter $user on line 786 can be null; however, CommonObject::call_trigger() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
823
                if ($result < 0) $error++;
824
                // End call triggers
825
	    	}
826
		}
827
828
        // Commit or rollback
829
		if ($error)
830
		{
831
			foreach($this->errors as $errmsg)
832
			{
833
	            dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
834
	            $this->error.=($this->error?', '.$errmsg:$errmsg);
835
			}
836
			$this->db->rollback();
837
			return -1*$error;
838
		}
839
		else
840
		{
841
			$this->db->commit();
842
			return 1;
843
		}
844
    }
845
846
847
    /**
848
     * Return an array with resources linked to the element
849
     *
850
     * @param string    $element        Element
851
     * @param int       $element_id     Id
852
     * @param string    $resource_type  Type
853
     * @return array                    Aray of resources
854
     */
855
    function getElementResources($element,$element_id,$resource_type='')
856
    {
857
	    // Links beetween objects are stored in this table
858
	    $sql = 'SELECT rowid, resource_id, resource_type, busy, mandatory';
859
	    $sql.= ' FROM '.MAIN_DB_PREFIX.'element_resources';
860
	    $sql.= " WHERE element_id=".$element_id." AND element_type='".$this->db->escape($element)."'";
861
	    if($resource_type)
862
	    	$sql.=" AND resource_type LIKE '%".$resource_type."%'";
863
	    $sql .= ' ORDER BY resource_type';
864
865
	    dol_syslog(get_class($this)."::getElementResources", LOG_DEBUG);
866
	    $resql = $this->db->query($sql);
867
	    if ($resql)
868
	    {
869
	    	$num = $this->db->num_rows($resql);
870
	    	$i = 0;
871
	    	while ($i < $num)
872
	    	{
873
	    		$obj = $this->db->fetch_object($resql);
874
875
	    		$resources[$i] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$resources was never initialized. Although not strictly required by PHP, it is generally a good practice to add $resources = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
876
	    			'rowid' => $obj->rowid,
877
	    			'resource_id' => $obj->resource_id,
878
	    			'resource_type'=>$obj->resource_type,
879
	    			'busy'=>$obj->busy,
880
	    			'mandatory'=>$obj->mandatory
881
	    		);
882
	    		$i++;
883
	    	}
884
	    }
885
886
	    return $resources;
0 ignored issues
show
Bug introduced by
The variable $resources does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
887
    }
888
889
    /*
890
     *  Return an int number of resources linked to the element
891
     *
892
     *  @return     int
893
     */
894
    function fetchElementResources($element,$element_id)
895
    {
896
        $resources = $this->getElementResources($element,$element_id);
897
        $i=0;
898
        foreach($resources as $nb => $resource) {
899
            $this->lines[$i] = fetchObjectByElement($resource['resource_id'],$resource['resource_type']);
900
            $i++;
901
        }
902
        return $i;
903
904
    }
905
906
907
    /**
908
     *      Load in cache resource type code (setup in dictionary)
909
     *
910
     *      @return     int             Nb lignes chargees, 0 si deja chargees, <0 si ko
911
     */
912
    function load_cache_code_type_resource()
913
    {
914
    	global $langs;
915
916
    	if (count($this->cache_code_type_resource)) return 0;    // Cache deja charge
917
918
    	$sql = "SELECT rowid, code, label, active";
919
    	$sql.= " FROM ".MAIN_DB_PREFIX."c_type_resource";
920
    	$sql.= " WHERE active > 0";
921
    	$sql.= " ORDER BY rowid";
922
    	dol_syslog(get_class($this)."::load_cache_code_type_resource", LOG_DEBUG);
923
    	$resql = $this->db->query($sql);
924
    	if ($resql)
925
    	{
926
    		$num = $this->db->num_rows($resql);
927
    		$i = 0;
928
    		while ($i < $num)
929
    		{
930
    			$obj = $this->db->fetch_object($resql);
931
    			// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
932
    			$label=($langs->trans("ResourceTypeShort".$obj->code)!=("ResourceTypeShort".$obj->code)?$langs->trans("ResourceTypeShort".$obj->code):($obj->label!='-'?$obj->label:''));
933
    			$this->cache_code_type_resource[$obj->rowid]['code'] = $obj->code;
934
    			$this->cache_code_type_resource[$obj->rowid]['label'] = $label;
935
    			$this->cache_code_type_resource[$obj->rowid]['active'] = $obj->active;
936
    			$i++;
937
    		}
938
    		return $num;
939
    	}
940
    	else
941
    	{
942
    		dol_print_error($this->db);
943
    		return -1;
944
    	}
945
    }
946
947
    /**
948
     *	Return clicable link of object (with eventually picto)
949
     *
950
     *	@param      int		$withpicto		Add picto into link
951
     *	@param      string	$option			Where point the link ('compta', 'expedition', 'document', ...)
952
     *	@param      string	$get_params    	Parametres added to url
953
     *	@return     string          		String with URL
954
     */
955
    function getNomUrl($withpicto=0,$option='', $get_params='')
956
    {
957
        global $langs;
958
959
        $result='';
960
        $label=$langs->trans("ShowResource").': '.$this->ref;
961
962
        if ($option == '')
963
        {
964
            $link = '<a href="'.dol_buildpath('/resource/card.php',1).'?id='.$this->id. $get_params .'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
965
            $picto='resource';
966
            $label=$langs->trans("ShowResource").': '.$this->ref;
967
968
        }
969
970
        $linkend='</a>';
971
972
973
        if ($withpicto) $result.=($link.img_object($label, $picto, 'class="classfortooltip"').$linkend);
0 ignored issues
show
Bug introduced by
The variable $link does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $picto does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
974
        if ($withpicto && $withpicto != 2) $result.=' ';
975
        $result.=$link.$this->ref.$linkend;
976
        return $result;
977
    }
978
    
979
    
980
    /**
981
     *  Retourne le libelle du status d'un user (actif, inactif)
982
     *
983
     *  @param	int		$mode          0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
984
     *  @return	string 			       Label of status
985
     */
986
    function getLibStatut($mode=0)
987
    {
988
        return $this->LibStatut($this->status,$mode);
989
    }
990
    
991
    /**
992
     *  Return the status
993
     *
994
     *  @param	int		$status        	Id status
995
     *  @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
996
     *  @return string 			       	Label of status
997
     */
998
    static function LibStatut($status,$mode=0)
999
    {
1000
        global $langs;
1001
    
1002
        return '';
1003
    }    
1004
}
1005