Passed
Branch develop (a7390e)
by
unknown
25:38
created

ActionComm::create()   F

Complexity

Conditions 80

Size

Total Lines 235
Code Lines 147

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 80
eloc 147
c 0
b 0
f 0
nop 2
dl 0
loc 235
rs 3.3333

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) 2002-2004  Rodolphe Quiedeville    <[email protected]>
3
 * Copyright (C) 2004-2011  Laurent Destailleur     <[email protected]>
4
 * Copyright (C) 2005-2012  Regis Houssin           <[email protected]>
5
 * Copyright (C) 2011-2017  Juanjo Menent           <[email protected]>
6
 * Copyright (C) 2015	    Marcos García		    <[email protected]>
7
 * Copyright (C) 2018	    Nicolas ZABOURI	        <[email protected]>
8
 * Copyright (C) 2018       Frédéric France         <[email protected]>
9
 *
10
 * This program is free software; you can redistribute it and/or modify
11
 * it under the terms of the GNU General Public License as published by
12
 * the Free Software Foundation; either version 3 of the License, or
13
 * (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU General Public License
21
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22
 */
23
24
/**
25
 *       \file       htdocs/comm/action/class/actioncomm.class.php
26
 *       \ingroup    agenda
27
 *       \brief      File of class to manage agenda events (actions)
28
 */
29
require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php';
30
require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
31
32
33
/**
34
 *		Class to manage agenda events (actions)
35
 */
36
class ActionComm extends CommonObject
37
{
38
    /**
39
     * @var string ID to identify managed object
40
     */
41
    public $element='action';
42
43
    /**
44
     * @var string Name of table without prefix where object is stored
45
     */
46
    public $table_element = 'actioncomm';
47
48
    public $table_rowid = 'id';
49
50
    /**
51
     * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
52
     */
53
    public $picto = 'action';
54
55
    /**
56
     * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
57
     * @var int
58
     */
59
    public $ismultientitymanaged = 1;
60
61
    /**
62
     * 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user, 2=Same than 1 but accept record if fksoc is empty
63
     * @var integer
64
     */
65
    public $restrictiononfksoc = 2;
66
67
    /**
68
     * Id of the event
69
     * @var int
70
     */
71
    public $id;
72
73
    /**
74
     * Id of the event. Use $id as possible
75
     * @var int
76
     */
77
    public $ref;
78
79
    public $type_id;		// Id into parent table llx_c_actioncomm (used only if option to use type is set)
80
    public $type_code;		// Code into parent table llx_c_actioncomm (used only if option to use type is set). With default setup, should be AC_OTH_AUTO or AC_OTH.
81
    public $type_label;
82
    public $type;			// Label into parent table llx_c_actioncomm (used only if option to use type is set)
83
    public $type_color;	// Color into parent table llx_c_actioncomm (used only if option to use type is set)
84
    public $code;			// Free code to identify action. Ie: Agenda trigger add here AC_TRIGGERNAME ('AC_COMPANY_CREATE', 'AC_PROPAL_VALIDATE', ...)
85
86
    /**
87
     * @var string Agenda event label
88
     */
89
    public $label;
90
91
    /**
92
     * Date creation record (datec)
93
     *
94
     * @var integer
95
     */
96
    public $datec;
97
98
    /**
99
     * Date end record (datef)
100
     *
101
     * @var integer
102
     */
103
    public $datef;
104
105
    /**
106
     * Duration (duree)
107
     *
108
     * @var integer
109
     */
110
    public $duree;
111
112
    /**
113
     * Date modification record (tms)
114
     *
115
     * @var integer
116
     */
117
    public $datem;
118
119
    /**
120
     * Object user that create action
121
     * @var User
122
     * @deprecated
123
     * @see $authorid
124
     */
125
    public $author;
126
127
    /**
128
     * Object user that modified action
129
     * @var User
130
     * @deprecated
131
     * @see $usermodid
132
     */
133
    public $usermod;
134
135
    /**
136
     * Id user that create action
137
     * @var int
138
     */
139
    public $authorid;
140
141
    /**
142
     * Id user that modified action
143
     * @var int
144
     */
145
    public $usermodid;
146
147
    /**
148
     * Date action start (datep)
149
     *
150
     * @var integer
151
     */
152
    public $datep;
153
154
    /**
155
     * Date action end (datep2)
156
     *
157
     * @var integer
158
     */
159
    public $datep2;
160
161
    /**
162
     * @var int -1=Unkown duration
163
     * @deprecated
164
     */
165
    public $durationp = -1;
166
    public $fulldayevent = 0;    // 1=Event on full day
167
168
    /**
169
     * Milestone
170
     * @var int
171
     * @deprecated Milestone is already event with end date = start date
172
     */
173
    public $punctual = 1;
174
    public $percentage;    // Percentage
175
    public $location;      // Location
176
177
	public $transparency;	// Transparency (ical standard). Used to say if people assigned to event are busy or not by event. 0=available, 1=busy, 2=busy (refused events)
178
    public $priority;      // Small int (0 By default)
179
180
	public $userassigned = array();	// Array of user ids
181
    public $userownerid;	// Id of user owner = fk_user_action into table
182
    public $userdoneid;	// Id of user done (deprecated)
183
184
    public $socpeopleassigned = array(); // Array of contact ids
185
186
    public $otherassigned = array(); // Array of other contact emails (not user, not contact)
187
188
189
	/**
190
     * Object user of owner
191
     * @var User
192
     * @deprecated
193
     * @see userownerid
194
     */
195
    public $usertodo;
196
197
    /**
198
     * Object user that did action
199
     * @var User
200
     * @deprecated
201
     * @see userdoneid
202
     */
203
    public $userdone;
204
205
    public $socid;
206
    public $contactid;
207
208
    /**
209
     * Company linked to action (optional)
210
     * @var Societe|null
211
     * @deprecated
212
     * @see socid
213
     */
214
    public $societe;
215
216
    /**
217
     * Contact linked to action (optional)
218
     * @var Contact|null
219
     * @deprecated
220
     * @see contactid
221
     */
222
    public $contact;
223
224
    // Properties for links to other objects
225
    public $fk_element;    // Id of record
226
    public $elementid;    // Id of record alternative for API
227
    public $elementtype;   // Type of record. This if property ->element of object linked to.
228
229
    // Ical
230
    public $icalname;
231
    public $icalcolor;
232
233
    public $actions=array();
234
235
    // Fields for emails
236
    public $email_msgid;
237
    public $email_from;
238
    public $email_sender;
239
    public $email_to;
240
    public $email_tocc;
241
    public $email_tobcc;
242
    public $email_subject;
243
    public $errors_to;
244
245
246
    /**
247
     *      Constructor
248
     *
249
     *      @param		DoliDB		$db      Database handler
250
     */
251
    public function __construct(DoliDB $db)
252
    {
253
        $this->db = $db;
254
255
        $this->societe = new stdClass();	// deprecated
1 ignored issue
show
Documentation Bug introduced by
It seems like new stdClass() of type stdClass is incompatible with the declared type Societe|null of property $societe.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
Deprecated Code introduced by
The property ActionComm::$societe has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

255
        /** @scrutinizer ignore-deprecated */ $this->societe = new stdClass();	// deprecated
Loading history...
256
        $this->contact = new stdClass();	// deprecated
1 ignored issue
show
Deprecated Code introduced by
The property ActionComm::$contact has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

256
        /** @scrutinizer ignore-deprecated */ $this->contact = new stdClass();	// deprecated
Loading history...
Documentation Bug introduced by
It seems like new stdClass() of type stdClass is incompatible with the declared type Contact|null of property $contact.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
257
    }
258
259
    /**
260
     *    Add an action/event into database.
261
     *    $this->type_id OR $this->type_code must be set.
262
     *
263
     *    @param	User	$user      		Object user making action
264
     *    @param    int		$notrigger		1 = disable triggers, 0 = enable triggers
265
     *    @return   int 		        	Id of created event, < 0 if KO
266
     */
267
    public function create(User $user, $notrigger = 0)
268
    {
269
        global $langs,$conf,$hookmanager;
270
271
        $error=0;
272
        $now=dol_now();
273
274
        // Check parameters
275
        if (! isset($this->userownerid) || $this->userownerid === '')	// $this->userownerid may be 0 (anonymous event) of > 0
276
        {
277
            dol_syslog("You tried to create an event but mandatory property ownerid was not defined", LOG_WARNING);
278
        	$this->errors[]='ErrorPropertyUserowneridNotDefined';
279
        	return -1;
280
        }
281
282
        // Clean parameters
283
        $this->label=dol_trunc(trim($this->label), 128);
284
        $this->location=dol_trunc(trim($this->location), 128);
285
        $this->note=dol_htmlcleanlastbr(trim($this->note));
286
        if (empty($this->percentage))   $this->percentage = 0;
287
        if (empty($this->priority) || ! is_numeric($this->priority)) $this->priority = 0;
288
        if (empty($this->fulldayevent)) $this->fulldayevent = 0;
289
        if (empty($this->punctual))     $this->punctual = 0;
290
        if (empty($this->transparency)) $this->transparency = 0;
291
        if ($this->percentage > 100) $this->percentage = 100;
292
        //if ($this->percentage == 100 && ! $this->dateend) $this->dateend = $this->date;
293
        if (! empty($this->datep) && ! empty($this->datef))   $this->durationp=($this->datef - $this->datep);		// deprecated
294
        //if (! empty($this->date)  && ! empty($this->dateend)) $this->durationa=($this->dateend - $this->date);
295
        if (! empty($this->datep) && ! empty($this->datef) && $this->datep > $this->datef) $this->datef=$this->datep;
296
        //if (! empty($this->date)  && ! empty($this->dateend) && $this->date > $this->dateend) $this->dateend=$this->date;
297
        if (! isset($this->fk_project) || $this->fk_project < 0) $this->fk_project = 0;
298
        // For backward compatibility
299
        if ($this->elementtype=='facture')  $this->elementtype='invoice';
300
        if ($this->elementtype=='commande') $this->elementtype='order';
301
        if ($this->elementtype=='contrat')  $this->elementtype='contract';
302
303
        if (! is_array($this->userassigned) && ! empty($this->userassigned))	// For backward compatibility when userassigned was an int instead fo array
1 ignored issue
show
introduced by
The condition is_array($this->userassigned) is always true.
Loading history...
304
        {
305
        	$tmpid=$this->userassigned;
306
        	$this->userassigned=array();
307
        	$this->userassigned[$tmpid]=array('id'=>$tmpid, 'transparency'=>$this->transparency);
308
        }
309
310
        //if (is_object($this->contact) && isset($this->contact->id) && $this->contact->id > 0 && ! ($this->contactid > 0)) $this->contactid = $this->contact->id;		// For backward compatibility. Using this->contact->xx is deprecated
311
312
313
        $userownerid=$this->userownerid;
314
        $userdoneid=$this->userdoneid;
315
316
        // Be sure assigned user is defined as an array of array('id'=>,'mandatory'=>,...).
317
        if (empty($this->userassigned) || count($this->userassigned) == 0 || ! is_array($this->userassigned))
318
        	$this->userassigned = array($userownerid=>array('id'=>$userownerid, 'transparency'=>$this->transparency));
319
320
        if (! $this->type_id || ! $this->type_code)
321
        {
322
        	$key=empty($this->type_id)?$this->type_code:$this->type_id;
323
324
            // Get id from code
325
            $cactioncomm=new CActionComm($this->db);
326
            $result=$cactioncomm->fetch($key);
327
328
            if ($result > 0)
329
            {
330
                $this->type_id=$cactioncomm->id;
331
                $this->type_code=$cactioncomm->code;
332
            }
333
            elseif ($result == 0)
334
            {
335
                $this->error='Failed to get record with id '.$this->type_id.' code '.$this->type_code.' from dictionary "type of events"';
336
                return -1;
337
            }
338
            else
339
			{
340
                $this->error=$cactioncomm->error;
341
                return -1;
342
            }
343
        }
344
        $code = empty($this->code)?$this->type_code:$this->code;
345
346
        // Check parameters
347
        if (! $this->type_id)
348
        {
349
            $this->error="ErrorWrongParameters";
350
            return -1;
351
        }
352
353
        $this->db->begin();
354
355
        $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm";
356
        $sql.= "(datec,";
357
        $sql.= "datep,";
358
        $sql.= "datep2,";
359
        $sql.= "durationp,";	// deprecated
360
        $sql.= "fk_action,";
361
        $sql.= "code,";
362
        $sql.= "fk_soc,";
363
        $sql.= "fk_project,";
364
        $sql.= "note,";
365
        $sql.= "fk_contact,";
366
        $sql.= "fk_user_author,";
367
        $sql.= "fk_user_action,";
368
        $sql.= "fk_user_done,";
369
        $sql.= "label,percent,priority,fulldayevent,location,punctual,";
370
        $sql.= "transparency,";
371
        $sql.= "fk_element,";
372
        $sql.= "elementtype,";
373
        $sql.= "entity,";
374
        $sql.= "extraparams,";
375
		// Fields emails
376
        $sql.= "email_msgid,";
377
        $sql.= "email_from,";
378
        $sql.= "email_sender,";
379
        $sql.= "email_to,";
380
        $sql.= "email_tocc,";
381
        $sql.= "email_tobcc,";
382
        $sql.= "email_subject,";
383
        $sql.= "errors_to";
384
        $sql.= ") VALUES (";
385
        $sql.= "'".$this->db->idate($now)."', ";
386
        $sql.= (strval($this->datep)!=''?"'".$this->db->idate($this->datep)."'":"null").", ";
387
        $sql.= (strval($this->datef)!=''?"'".$this->db->idate($this->datef)."'":"null").", ";
388
        $sql.= ((isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '')?"'".$this->db->escape($this->durationp)."'":"null").", ";	// deprecated
389
        $sql.= (isset($this->type_id)?$this->type_id:"null").",";
390
        $sql.= ($code?("'".$code."'"):"null").", ";
391
        $sql.= ((isset($this->socid) && $this->socid > 0) ? $this->socid:"null").", ";
392
        $sql.= ((isset($this->fk_project) && $this->fk_project > 0) ? $this->fk_project:"null").", ";
393
        $sql.= " '".$this->db->escape($this->note_private?$this->note_private:$this->note)."', ";
394
        $sql.= ((isset($this->contactid) && $this->contactid > 0) ? $this->contactid:"null").", ";
395
        $sql.= (isset($user->id) && $user->id > 0 ? $user->id:"null").", ";
396
        $sql.= ($userownerid>0 ? $userownerid:"null").", ";
397
        $sql.= ($userdoneid>0 ? $userdoneid:"null").", ";
398
        $sql.= "'".$this->db->escape($this->label)."','".$this->db->escape($this->percentage)."','".$this->db->escape($this->priority)."','".$this->db->escape($this->fulldayevent)."','".$this->db->escape($this->location)."','".$this->db->escape($this->punctual)."', ";
399
        $sql.= "'".$this->db->escape($this->transparency)."', ";
400
        $sql.= (! empty($this->fk_element)?$this->fk_element:"null").", ";
401
        $sql.= (! empty($this->elementtype)?"'".$this->db->escape($this->elementtype)."'":"null").", ";
402
        $sql.= $conf->entity.",";
403
        $sql.= (! empty($this->extraparams)?"'".$this->db->escape($this->extraparams)."'":"null").", ";
0 ignored issues
show
Bug Best Practice introduced by
The property extraparams does not exist on ActionComm. Did you maybe forget to declare it?
Loading history...
404
        // Fields emails
405
        $sql.= (! empty($this->email_msgid)?"'".$this->db->escape($this->email_msgid)."'":"null").", ";
406
        $sql.= (! empty($this->email_from)?"'".$this->db->escape($this->email_from)."'":"null").", ";
407
        $sql.= (! empty($this->email_sender)?"'".$this->db->escape($this->email_sender)."'":"null").", ";
408
        $sql.= (! empty($this->email_to)?"'".$this->db->escape($this->email_to)."'":"null").", ";
409
        $sql.= (! empty($this->email_tocc)?"'".$this->db->escape($this->email_tocc)."'":"null").", ";
410
        $sql.= (! empty($this->email_tobcc)?"'".$this->db->escape($this->email_tobcc)."'":"null").", ";
411
        $sql.= (! empty($this->email_subject)?"'".$this->db->escape($this->email_subject)."'":"null").", ";
412
        $sql.= (! empty($this->errors_to)?"'".$this->db->escape($this->errors_to)."'":"null");
413
        $sql.= ")";
414
415
        dol_syslog(get_class($this)."::add", LOG_DEBUG);
416
        $resql=$this->db->query($sql);
417
        if ($resql)
418
        {
419
            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."actioncomm", "id");
420
421
            // Now insert assignedusers
422
			if (! $error)
423
			{
424
				foreach($this->userassigned as $key => $val)
425
				{
426
			        if (! is_array($val))	// For backward compatibility when val=id
427
			        {
428
			        	$val=array('id'=>$val);
429
			        }
430
431
					$sql ="INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
432
					$sql.=" VALUES(".$this->id.", 'user', ".$val['id'].", ".(empty($val['mandatory'])?'0':$val['mandatory']).", ".(empty($val['transparency'])?'0':$val['transparency']).", ".(empty($val['answer_status'])?'0':$val['answer_status']).")";
433
434
					$resql = $this->db->query($sql);
435
					if (! $resql)
436
					{
437
						$error++;
438
		           		$this->errors[]=$this->db->lasterror();
439
					}
440
					//var_dump($sql);exit;
441
				}
442
			}
443
444
			if (!$error)
445
			{
446
				if (!empty($this->socpeopleassigned))
447
				{
448
					foreach ($this->socpeopleassigned as $id => $Tab)
449
					{
450
						$sql ="INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
451
						$sql.=" VALUES(".$this->id.", 'socpeople', ".$id.", 0, 0, 0)";
452
453
						$resql = $this->db->query($sql);
454
						if (! $resql)
455
						{
456
							$error++;
457
							$this->errors[]=$this->db->lasterror();
458
						}
459
					}
460
				}
461
			}
462
463
            if (! $error)
464
            {
465
            	$action='create';
466
467
	            // Actions on extra fields
468
            	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
469
            	{
470
            		$result=$this->insertExtraFields();
471
            		if ($result < 0)
472
            		{
473
            			$error++;
474
            		}
475
	            }
476
            }
477
478
            if (! $error && ! $notrigger)
479
            {
480
                // Call trigger
481
                $result=$this->call_trigger('ACTION_CREATE', $user);
482
                if ($result < 0) { $error++; }
483
                // End call triggers
484
            }
485
486
            if (! $error)
487
            {
488
            	$this->db->commit();
489
            	return $this->id;
490
            }
491
            else
492
           {
493
	           	$this->db->rollback();
494
	           	return -1;
495
            }
496
        }
497
        else
498
        {
499
            $this->db->rollback();
500
            $this->error=$this->db->lasterror();
501
            return -1;
502
        }
503
    }
504
505
	/**
506
	 *    Add an action/event into database.
507
	 *    $this->type_id OR $this->type_code must be set.
508
	 *
509
	 *    @param	User	$user      		Object user making action
510
	 *    @param    int		$notrigger		1 = disable triggers, 0 = enable triggers
511
	 *    @return   int 		        	Id of created event, < 0 if KO
512
	 * @deprecated Use create instead
513
	 */
514
	public function add(User $user, $notrigger = 0)
515
	{
516
		return $this->create($user, $notrigger);
517
	}
518
519
    /**
520
     *  Load an object from its id and create a new one in database
521
     *
522
     *  @param	    User	        $fuser      	Object user making action
523
	 *  @param		int				$socid			Id of thirdparty
524
     *  @return		int								New id of clone
525
     */
526
    public function createFromClone(User $fuser, $socid)
527
    {
528
        global $db, $conf, $hookmanager;
529
530
        $error=0;
531
        $now=dol_now();
532
533
        $this->db->begin();
534
535
		// Load source object
536
		$objFrom = clone $this;
537
538
		// Retreive all extrafield
539
		// fetch optionals attributes and labels
540
		$this->fetch_optionals();
541
542
		//$this->fetch_userassigned();
543
		$this->fetchResources();
544
545
        $this->id=0;
546
547
        // Create clone
548
		$this->context['createfromclone']='createfromclone';
549
		$result=$this->create($fuser);
550
        if ($result < 0) $error++;
551
552
        if (! $error)
553
        {
554
            // Hook of thirdparty module
555
            if (is_object($hookmanager))
556
            {
557
                $parameters=array('objFrom'=>$objFrom);
558
                $action='';
559
                $reshook=$hookmanager->executeHooks('createFrom', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
560
                if ($reshook < 0) $error++;
561
            }
562
563
            // Call trigger
564
            $result=$this->call_trigger('ACTION_CLONE', $fuser);
565
            if ($result < 0) { $error++; }
566
            // End call triggers
567
        }
568
569
        unset($this->context['createfromclone']);
570
571
        // End
572
        if (! $error)
573
        {
574
            $this->db->commit();
575
            return $this->id;
576
        }
577
        else
578
        {
579
            $this->db->rollback();
580
            return -1;
581
        }
582
    }
583
584
    /**
585
     *  Load object from database
586
     *
587
     *  @param  int		$id     	Id of action to get
588
     *  @param  string	$ref    	Ref of action to get
589
     *  @param  string	$ref_ext	Ref ext to get
590
     *  @return	int					<0 if KO, >0 if OK
591
     */
592
    public function fetch($id, $ref = '', $ref_ext = '')
593
    {
594
        global $langs;
595
596
        $sql = "SELECT a.id,";
597
        $sql.= " a.id as ref,";
598
        $sql.= " a.ref_ext,";
599
        $sql.= " a.datep,";
600
        $sql.= " a.datep2,";
601
        $sql.= " a.durationp,";	// deprecated
602
        $sql.= " a.datec,";
603
        $sql.= " a.tms as datem,";
604
        $sql.= " a.code, a.label, a.note,";
605
        $sql.= " a.fk_soc,";
606
        $sql.= " a.fk_project,";
607
        $sql.= " a.fk_user_author, a.fk_user_mod,";
608
        $sql.= " a.fk_user_action, a.fk_user_done,";
609
        $sql.= " a.fk_contact, a.percent as percentage,";
610
        $sql.= " a.fk_element as elementid, a.elementtype,";
611
        $sql.= " a.priority, a.fulldayevent, a.location, a.punctual, a.transparency,";
612
        $sql.= " c.id as type_id, c.code as type_code, c.libelle as type_label, c.color as type_color, c.picto as type_picto,";
613
        $sql.= " s.nom as socname,";
614
        $sql.= " u.firstname, u.lastname as lastname";
615
        $sql.= " FROM ".MAIN_DB_PREFIX."actioncomm as a ";
616
        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action=c.id ";
617
        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author";
618
        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc";
619
        $sql.= " WHERE ";
620
        if ($ref) $sql.= " a.id=".$ref;											// No field ref, we use id
621
        elseif ($ref_ext) $sql.= " a.ref_ext='".$this->db->escape($ref_ext)."'";
622
        else $sql.= " a.id=".$id;
623
624
        dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
625
        $resql=$this->db->query($sql);
626
        if ($resql)
627
        {
628
        	$num=$this->db->num_rows($resql);
629
            if ($num)
630
            {
631
                $obj = $this->db->fetch_object($resql);
632
633
                $this->id         = $obj->id;
634
                $this->ref        = $obj->ref;
635
                $this->ref_ext    = $obj->ref_ext;
636
637
                // Properties of parent table llx_c_actioncomm
638
                $this->type_id    = $obj->type_id;
639
                $this->type_code  = $obj->type_code;
640
                $this->type_color = $obj->type_color;
641
                $this->type_picto = $obj->type_picto;
642
                $transcode=$langs->trans("Action".$obj->type_code);
643
                $this->type       = (($transcode!="Action".$obj->type_code) ? $transcode : $obj->type_label);
644
                $transcode=$langs->trans("Action".$obj->type_code.'Short');
645
                $this->type_short       = (($transcode!="Action".$obj->type_code.'Short') ? $transcode : '');
646
647
				$this->code					= $obj->code;
648
                $this->label				= $obj->label;
649
                $this->datep				= $this->db->jdate($obj->datep);
650
                $this->datef				= $this->db->jdate($obj->datep2);
651
652
                $this->datec   				= $this->db->jdate($obj->datec);
653
                $this->datem   				= $this->db->jdate($obj->datem);
654
655
                $this->note					= $obj->note;
656
                $this->note_private			= $obj->note;
657
                $this->percentage			= $obj->percentage;
658
659
                $this->authorid             = $obj->fk_user_author;
660
                $this->usermodid			= $obj->fk_user_mod;
661
662
                if (!is_object($this->author)) $this->author = new stdClass(); // To avoid warning
663
                $this->author->id = $obj->fk_user_author;       // deprecated
664
                $this->author->firstname = $obj->firstname;     // deprecated
665
                $this->author->lastname = $obj->lastname;       // deprecated
666
                if (!is_object($this->usermod)) $this->usermod = new stdClass(); // To avoid warning
667
                $this->usermod->id = $obj->fk_user_mod;         // deprecated
668
669
                $this->userownerid			= $obj->fk_user_action;
670
                $this->userdoneid			= $obj->fk_user_done;
671
                $this->priority				= $obj->priority;
672
                $this->fulldayevent			= $obj->fulldayevent;
673
                $this->location				= $obj->location;
674
                $this->transparency			= $obj->transparency;
675
                $this->punctual				= $obj->punctual;       // deprecated
676
677
                $this->socid				= $obj->fk_soc;			// To have fetch_thirdparty method working
678
                $this->contactid			= $obj->fk_contact;		// To have fetch_contact method working
679
                $this->fk_project			= $obj->fk_project;		// To have fetch_project method working
680
681
                $this->societe->id			= $obj->fk_soc;			// deprecated
682
                //$this->contact->id			= $obj->fk_contact;		// deprecated
683
684
                $this->fk_element			= $obj->elementid;
685
                $this->elementid			= $obj->elementid;
686
                $this->elementtype			= $obj->elementtype;
687
688
                $this->fetchResources();
689
            }
690
            $this->db->free($resql);
691
        }
692
        else
693
        {
694
            $this->error=$this->db->lasterror();
695
            return -1;
696
        }
697
698
        return $num;
699
    }
700
701
    /**
702
     *    Initialize $this->userassigned & this->socpeopleassigned array with list of id of user and contact assigned to event
703
     *
704
     *    @return   int				<0 if KO, >0 if OK
705
     */
706
    public function fetchResources()
707
    {
708
		$sql ='SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency';
709
		$sql.=' FROM '.MAIN_DB_PREFIX.'actioncomm_resources';
710
		$sql.=' WHERE fk_actioncomm = '.$this->id;
711
		$sql.=" AND element_type IN ('user', 'socpeople')";
712
		$resql=$this->db->query($sql);
713
		if ($resql)
714
		{
715
			$this->userassigned=array();
716
			$this->socpeopleassigned=array();
717
718
			// If owner is known, we must but id first into list
719
			if ($this->userownerid > 0) $this->userassigned[$this->userownerid]=array('id'=>$this->userownerid);	// Set first so will be first into list.
720
721
            while ($obj = $this->db->fetch_object($resql))
722
            {
723
            	if ($obj->fk_element > 0)
724
				{
725
					switch ($obj->element_type) {
726
						case 'user':
727
							$this->userassigned[$obj->fk_element]=array('id'=>$obj->fk_element, 'mandatory'=>$obj->mandatory, 'answer_status'=>$obj->answer_status, 'transparency'=>$obj->transparency);
728
							if (empty($this->userownerid)) $this->userownerid=$obj->fk_element;	// If not defined (should not happened, we fix this)
729
							break;
730
						case 'socpeople':
731
							$this->socpeopleassigned[$obj->fk_element]=array('id'=>$obj->fk_element, 'mandatory'=>$obj->mandatory, 'answer_status'=>$obj->answer_status, 'transparency'=>$obj->transparency);
732
							break;
733
					}
734
				}
735
            }
736
737
        	return 1;
738
		}
739
		else
740
		{
741
			dol_print_error($this->db);
742
			return -1;
743
		}
744
	}
745
746
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
747
    /**
748
     *    Initialize this->userassigned array with list of id of user assigned to event
749
     *
750
     *    @return	int				<0 if KO, >0 if OK
751
     */
752
    public function fetch_userassigned()
753
    {
754
        // phpcs:enable
755
        $sql ="SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency";
756
		$sql.=" FROM ".MAIN_DB_PREFIX."actioncomm_resources";
757
		$sql.=" WHERE element_type = 'user' AND fk_actioncomm = ".$this->id;
758
		$resql2=$this->db->query($sql);
759
		if ($resql2)
760
		{
761
			$this->userassigned=array();
762
763
			// If owner is known, we must but id first into list
764
			if ($this->userownerid > 0) $this->userassigned[$this->userownerid]=array('id'=>$this->userownerid);	// Set first so will be first into list.
765
766
            while ($obj = $this->db->fetch_object($resql2))
767
            {
768
            	if ($obj->fk_element > 0) $this->userassigned[$obj->fk_element]=array('id'=>$obj->fk_element, 'mandatory'=>$obj->mandatory, 'answer_status'=>$obj->answer_status, 'transparency'=>$obj->transparency);
769
            	if (empty($this->userownerid)) $this->userownerid=$obj->fk_element;	// If not defined (should not happened, we fix this)
770
            }
771
772
        	return 1;
773
		}
774
		else
775
		{
776
			dol_print_error($this->db);
777
			return -1;
778
		}
779
    }
780
781
    /**
782
     *    Delete event from database
783
     *
784
     *    @param    int		$notrigger		1 = disable triggers, 0 = enable triggers
785
     *    @return   int 					<0 if KO, >0 if OK
786
     */
787
    public function delete($notrigger = 0)
788
    {
789
        global $user,$langs,$conf;
790
791
        $error=0;
792
793
        $this->db->begin();
794
795
        $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm";
796
        $sql.= " WHERE id=".$this->id;
797
798
        dol_syslog(get_class($this)."::delete", LOG_DEBUG);
799
        $res=$this->db->query($sql);
800
        if ($res < 0) {
801
        	$this->error=$this->db->lasterror();
802
        	$error++;
803
        }
804
805
        if (! $error) {
806
            $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources";
807
            $sql.= " WHERE fk_actioncomm=".$this->id;
808
809
            dol_syslog(get_class($this)."::delete", LOG_DEBUG);
810
            $res=$this->db->query($sql);
811
            if ($res < 0) {
812
                $this->error=$this->db->lasterror();
813
                $error++;
814
            }
815
        }
816
817
        // Removed extrafields
818
        if (! $error) {
819
        	$result=$this->deleteExtraFields();
820
          	if ($result < 0)
821
           	{
822
           		$error++;
823
           		dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
824
           	}
825
        }
826
827
        if (!$error)
828
        {
829
            if (! $notrigger)
830
            {
831
                // Call trigger
832
                $result=$this->call_trigger('ACTION_DELETE', $user);
833
                if ($result < 0) { $error++; }
834
                // End call triggers
835
            }
836
837
            if (! $error)
838
            {
839
                $this->db->commit();
840
                return 1;
841
            }
842
            else
843
            {
844
                $this->db->rollback();
845
                return -2;
846
            }
847
        }
848
        else
849
        {
850
            $this->db->rollback();
851
            $this->error=$this->db->lasterror();
852
            return -1;
853
        }
854
    }
855
856
    /**
857
     *    Update action into database
858
     *	  If percentage = 100, on met a jour date 100%
859
     *
860
     *    @param    User	$user			Object user making change
861
     *    @param    int		$notrigger		1 = disable triggers, 0 = enable triggers
862
     *    @return   int     				<0 if KO, >0 if OK
863
     */
864
    public function update($user, $notrigger = 0)
865
    {
866
        global $langs,$conf,$hookmanager;
867
868
        $error=0;
869
870
        // Clean parameters
871
        $this->label=trim($this->label);
872
        $this->note=trim($this->note);
1 ignored issue
show
Deprecated Code introduced by
The property CommonObject::$note has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

872
        $this->note=trim(/** @scrutinizer ignore-deprecated */ $this->note);
Loading history...
873
        if (empty($this->percentage))    $this->percentage = 0;
874
        if (empty($this->priority) || ! is_numeric($this->priority)) $this->priority = 0;
875
        if (empty($this->transparency))  $this->transparency = 0;
876
        if (empty($this->fulldayevent))  $this->fulldayevent = 0;
877
        if ($this->percentage > 100) $this->percentage = 100;
878
        //if ($this->percentage == 100 && ! $this->dateend) $this->dateend = $this->date;
879
        if ($this->datep && $this->datef)   $this->durationp=($this->datef - $this->datep);		// deprecated
1 ignored issue
show
Deprecated Code introduced by
The property ActionComm::$durationp has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

879
        if ($this->datep && $this->datef)   /** @scrutinizer ignore-deprecated */ $this->durationp=($this->datef - $this->datep);		// deprecated
Loading history...
880
        //if ($this->date  && $this->dateend) $this->durationa=($this->dateend - $this->date);
881
        if ($this->datep && $this->datef && $this->datep > $this->datef) $this->datef=$this->datep;
882
        //if ($this->date  && $this->dateend && $this->date > $this->dateend) $this->dateend=$this->date;
883
        if ($this->fk_project < 0) $this->fk_project = 0;
884
885
        // Check parameters
886
        if ($this->percentage == 0 && $this->userdoneid > 0)
887
        {
888
            $this->error="ErrorCantSaveADoneUserWithZeroPercentage";
889
            return -1;
890
        }
891
892
        $socid=($this->socid?$this->socid:((isset($this->societe->id) && $this->societe->id > 0) ? $this->societe->id : 0));
1 ignored issue
show
Deprecated Code introduced by
The property ActionComm::$societe has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

892
        $socid=($this->socid?$this->socid:((isset($this->societe->id) && /** @scrutinizer ignore-deprecated */ $this->societe->id > 0) ? $this->societe->id : 0));
Loading history...
893
        $contactid=($this->contactid?$this->contactid:0);
894
		$userownerid=($this->userownerid?$this->userownerid:0);
895
		$userdoneid=($this->userdoneid?$this->userdoneid:0);
896
897
        $this->db->begin();
898
899
        $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm ";
900
        $sql.= " SET percent = '".$this->db->escape($this->percentage)."'";
901
        if ($this->type_id > 0) $sql.= ", fk_action = '".$this->db->escape($this->type_id)."'";
902
        $sql.= ", label = ".($this->label ? "'".$this->db->escape($this->label)."'":"null");
903
        $sql.= ", datep = ".(strval($this->datep)!='' ? "'".$this->db->idate($this->datep)."'" : 'null');
904
        $sql.= ", datep2 = ".(strval($this->datef)!='' ? "'".$this->db->idate($this->datef)."'" : 'null');
905
        $sql.= ", durationp = ".(isset($this->durationp) && $this->durationp >= 0 && $this->durationp != ''?"'".$this->db->escape($this->durationp)."'":"null");	// deprecated
1 ignored issue
show
Deprecated Code introduced by
The property ActionComm::$durationp has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

905
        $sql.= ", durationp = ".(isset(/** @scrutinizer ignore-deprecated */ $this->durationp) && $this->durationp >= 0 && $this->durationp != ''?"'".$this->db->escape($this->durationp)."'":"null");	// deprecated
Loading history...
906
        $sql.= ", note = '".$this->db->escape($this->note_private?$this->note_private:$this->note)."'";
1 ignored issue
show
Deprecated Code introduced by
The property CommonObject::$note has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

906
        $sql.= ", note = '".$this->db->escape($this->note_private?$this->note_private:/** @scrutinizer ignore-deprecated */ $this->note)."'";
Loading history...
907
        $sql.= ", fk_project =". ($this->fk_project > 0 ? $this->fk_project:"null");
908
        $sql.= ", fk_soc =". ($socid > 0 ? $socid:"null");
909
        $sql.= ", fk_contact =". ($contactid > 0 ? $contactid:"null");
910
        $sql.= ", priority = '".$this->db->escape($this->priority)."'";
911
        $sql.= ", fulldayevent = '".$this->db->escape($this->fulldayevent)."'";
912
        $sql.= ", location = ".($this->location ? "'".$this->db->escape($this->location)."'":"null");
913
        $sql.= ", transparency = '".$this->db->escape($this->transparency)."'";
914
        $sql.= ", fk_user_mod = ".$user->id;
915
        $sql.= ", fk_user_action=".($userownerid > 0 ? "'".$userownerid."'":"null");
916
        $sql.= ", fk_user_done=".($userdoneid > 0 ? "'".$userdoneid."'":"null");
917
        if (! empty($this->fk_element)) $sql.= ", fk_element=".($this->fk_element?$this->db->escape($this->fk_element):"null");
918
        if (! empty($this->elementtype)) $sql.= ", elementtype=".($this->elementtype?"'".$this->db->escape($this->elementtype)."'":"null");
919
        $sql.= " WHERE id=".$this->id;
920
921
        dol_syslog(get_class($this)."::update", LOG_DEBUG);
922
        if ($this->db->query($sql))
923
        {
924
			$action='update';
925
926
        	// Actions on extra fields
927
       		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
928
       		{
929
       			$result=$this->insertExtraFields();
930
       			if ($result < 0)
931
       			{
932
       				$error++;
933
       			}
934
        	}
935
936
            // Now insert assignedusers
937
			if (! $error)
938
			{
939
				$sql ="DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources where fk_actioncomm = ".$this->id." AND element_type = 'user'";
940
				$resql = $this->db->query($sql);
941
942
				foreach($this->userassigned as $key => $val)
943
				{
944
			        if (! is_array($val))	// For backward compatibility when val=id
945
			        {
946
			        	$val=array('id'=>$val);
947
			        }
948
					$sql ="INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
949
					$sql.=" VALUES(".$this->id.", 'user', ".$val['id'].", ".(empty($val['mandatory'])?'0':$val['mandatory']).", ".(empty($val['transparency'])?'0':$val['transparency']).", ".(empty($val['answer_status'])?'0':$val['answer_status']).")";
950
951
					$resql = $this->db->query($sql);
952
					if (! $resql)
953
					{
954
						$error++;
955
		           		$this->errors[]=$this->db->lasterror();
956
					}
957
					//var_dump($sql);exit;
958
				}
959
			}
960
961
			if (!$error)
962
			{
963
				$sql ="DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources where fk_actioncomm = ".$this->id." AND element_type = 'socpeople'";
964
				$resql = $this->db->query($sql);
965
966
				if (!empty($this->socpeopleassigned))
967
				{
968
					foreach (array_keys($this->socpeopleassigned) as $id)
969
					{
970
						$sql ="INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
971
						$sql.=" VALUES(".$this->id.", 'socpeople', ".$id.", 0, 0, 0)";
972
973
						$resql = $this->db->query($sql);
974
						if (! $resql)
975
						{
976
							$error++;
977
							$this->errors[]=$this->db->lasterror();
978
						}
979
					}
980
				}
981
			}
982
983
            if (! $error && ! $notrigger)
984
            {
985
                // Call trigger
986
                $result=$this->call_trigger('ACTION_MODIFY', $user);
987
                if ($result < 0) { $error++; }
988
                // End call triggers
989
            }
990
991
            if (! $error)
992
            {
993
                $this->db->commit();
994
                return 1;
995
            }
996
            else
997
            {
998
                $this->db->rollback();
999
                dol_syslog(get_class($this)."::update ".join(',', $this->errors), LOG_ERR);
1000
                return -2;
1001
            }
1002
        }
1003
        else
1004
        {
1005
            $this->db->rollback();
1006
            $this->error=$this->db->lasterror();
1007
            return -1;
1008
        }
1009
    }
1010
1011
    /**
1012
     *  Load all objects with filters.
1013
     *  @TODO WARNING: This make a fetch on all records instead of making one request with a join.
1014
     *
1015
     *  @param		DoliDb	$db				Database handler
1016
     *  @param		int		$socid			Filter by thirdparty
1017
     *  @param		int		$fk_element		Id of element action is linked to
1018
     *  @param		string	$elementtype	Type of element action is linked to
1019
     *  @param		string	$filter			Other filter
1020
     *  @param		string	$sortfield		Sort on this field
1021
     *  @param		string	$sortorder		ASC or DESC
1022
     *  @param		string	$limit			Limit number of answers
1023
     *  @return		array|string			Error string if KO, array with actions if OK
1024
     */
1025
    public static function getActions($db, $socid = 0, $fk_element = 0, $elementtype = '', $filter = '', $sortfield = 'a.datep', $sortorder = 'DESC', $limit = 0)
1026
    {
1027
        global $conf, $langs;
1028
1029
        $resarray=array();
1030
1031
        dol_syslog(get_class()."::getActions", LOG_DEBUG);
1032
1033
        $sql = "SELECT a.id";
1034
        $sql.= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
1035
        $sql.= " WHERE a.entity IN (".getEntity('agenda').")";
1036
        if (! empty($socid)) $sql.= " AND a.fk_soc = ".$socid;
1037
        if (! empty($elementtype))
1038
        {
1039
            if ($elementtype == 'project') $sql.= ' AND a.fk_project = '.$fk_element;
1040
            else $sql.= " AND a.fk_element = ".(int) $fk_element." AND a.elementtype = '".$elementtype."'";
1041
        }
1042
        if (! empty($filter)) $sql.= $filter;
1043
		if ($sortorder && $sortfield) $sql.=$db->order($sortfield, $sortorder);
1044
		$sql.=$db->plimit($limit, 0);
1045
1046
        $resql=$db->query($sql);
1047
        if ($resql)
1048
        {
1049
            $num = $db->num_rows($resql);
1050
1051
            if ($num)
1052
            {
1053
                for($i=0;$i<$num;$i++)
1054
                {
1055
                    $obj = $db->fetch_object($resql);
1056
                    $actioncommstatic = new ActionComm($db);
1057
                    $actioncommstatic->fetch($obj->id);
1058
                    $resarray[$i] = $actioncommstatic;
1059
                }
1060
            }
1061
            $db->free($resql);
1062
            return $resarray;
1063
        }
1064
        else
1065
       {
1066
            return $db->lasterror();
1067
        }
1068
    }
1069
1070
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1071
    /**
1072
     * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
1073
     *
1074
     * @param	User	$user   			Objet user
1075
     * @param	int		$load_state_board	Charge indicateurs this->nb de tableau de bord
1076
     * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
1077
     */
1078
    public function load_board($user, $load_state_board = 0)
1079
    {
1080
        // phpcs:enable
1081
        global $conf, $langs;
1082
1083
    	if(empty($load_state_board)) $sql = "SELECT a.id, a.datep as dp";
1084
    	else {
1085
    		$this->nb=array();
1086
    		$sql = "SELECT count(a.id) as nb";
1087
    	}
1088
    	$sql.= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
1089
    	if (! $user->rights->societe->client->voir && ! $user->societe_id) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc";
1 ignored issue
show
Deprecated Code introduced by
The property User::$societe_id has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1089
    	if (! $user->rights->societe->client->voir && ! /** @scrutinizer ignore-deprecated */ $user->societe_id) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc";
Loading history...
1090
    	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid";
1091
    	$sql.= " WHERE 1 = 1";
1092
    	if(empty($load_state_board)) $sql.= " AND a.percent >= 0 AND a.percent < 100";
1093
    	$sql.= " AND a.entity IN (".getEntity('agenda').")";
1094
    	if (! $user->rights->societe->client->voir && ! $user->societe_id) $sql.= " AND (a.fk_soc IS NULL OR sc.fk_user = " .$user->id . ")";
1 ignored issue
show
Deprecated Code introduced by
The property User::$societe_id has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1094
    	if (! $user->rights->societe->client->voir && ! /** @scrutinizer ignore-deprecated */ $user->societe_id) $sql.= " AND (a.fk_soc IS NULL OR sc.fk_user = " .$user->id . ")";
Loading history...
1095
    	if ($user->societe_id) $sql.=" AND a.fk_soc = ".$user->societe_id;
1 ignored issue
show
Deprecated Code introduced by
The property User::$societe_id has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1095
    	if ($user->societe_id) $sql.=" AND a.fk_soc = "./** @scrutinizer ignore-deprecated */ $user->societe_id;
Loading history...
1096
    	if (! $user->rights->agenda->allactions->read) $sql.= " AND (a.fk_user_author = ".$user->id . " OR a.fk_user_action = ".$user->id . " OR a.fk_user_done = ".$user->id . ")";
1097
1098
    	$resql=$this->db->query($sql);
1099
    	if ($resql)
1100
    	{
1101
    		if(empty($load_state_board)) {
1102
	    		$agenda_static = new ActionComm($this->db);
1103
	    		$response = new WorkboardResponse();
1104
	    		$response->warning_delay = $conf->agenda->warning_delay/60/60/24;
1105
	    		$response->label = $langs->trans("ActionsToDo");
1106
	    		$response->url = DOL_URL_ROOT.'/comm/action/list.php?actioncode=0&amp;status=todo&amp;mainmenu=agenda';
1107
	    		if ($user->rights->agenda->allactions->read) $response->url.='&amp;filtert=-1';
1108
	    		$response->img = img_object('', "action", 'class="inline-block valigntextmiddle"');
1109
    		}
1110
    		// This assignment in condition is not a bug. It allows walking the results.
1111
    		while ($obj=$this->db->fetch_object($resql))
1112
    		{
1113
    			if(empty($load_state_board)) {
1114
	    			$response->nbtodo++;
1 ignored issue
show
Comprehensibility Best Practice introduced by
The variable $response does not seem to be defined for all execution paths leading up to this point.
Loading history...
1115
	    			$agenda_static->datep = $this->db->jdate($obj->dp);
1 ignored issue
show
Comprehensibility Best Practice introduced by
The variable $agenda_static does not seem to be defined for all execution paths leading up to this point.
Loading history...
1116
	    			if ($agenda_static->hasDelay()) $response->nbtodolate++;
1117
    			} else $this->nb["actionscomm"]=$obj->nb;
1118
    		}
1119
1120
    		$this->db->free($resql);
1121
    		if(empty($load_state_board)) return $response;
1122
    		else return 1;
1123
    	}
1124
    	else
1125
    	{
1126
    		dol_print_error($this->db);
1127
    		$this->error=$this->db->error();
1128
    		return -1;
1129
    	}
1130
    }
1131
1132
1133
    /**
1134
     *  Charge les informations d'ordre info dans l'objet facture
1135
     *
1136
     *  @param	int		$id       	Id de la facture a charger
1137
     *  @return	void
1138
     */
1139
    public function info($id)
1140
    {
1141
        $sql = 'SELECT ';
1142
        $sql.= ' a.id,';
1143
        $sql.= ' datec,';
1144
        $sql.= ' tms as datem,';
1145
        $sql.= ' fk_user_author,';
1146
        $sql.= ' fk_user_mod';
1147
        $sql.= ' FROM '.MAIN_DB_PREFIX.'actioncomm as a';
1148
        $sql.= ' WHERE a.id = '.$id;
1149
1150
        dol_syslog(get_class($this)."::info", LOG_DEBUG);
1151
        $result=$this->db->query($sql);
1152
        if ($result)
1153
        {
1154
            if ($this->db->num_rows($result))
1155
            {
1156
                $obj = $this->db->fetch_object($result);
1157
                $this->id = $obj->id;
1158
                if ($obj->fk_user_author)
1159
                {
1160
                    $cuser = new User($this->db);
1161
                    $cuser->fetch($obj->fk_user_author);
1162
                    $this->user_creation     = $cuser;
1163
                }
1164
                if ($obj->fk_user_mod)
1165
                {
1166
                    $muser = new User($this->db);
1167
                    $muser->fetch($obj->fk_user_mod);
1168
                    $this->user_modification = $muser;
1169
                }
1170
1171
                $this->date_creation     = $this->db->jdate($obj->datec);
1172
                if (! empty($obj->fk_user_mod)) $this->date_modification = $this->db->jdate($obj->datem);
1173
            }
1174
            $this->db->free($result);
1175
        }
1176
        else
1177
        {
1178
            dol_print_error($this->db);
1179
        }
1180
    }
1181
1182
1183
    /**
1184
     *  Return label of status
1185
     *
1186
     *  @param	int		$mode           0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
1187
     *  @param  int		$hidenastatus   1=Show nothing if status is "Not applicable"
1188
     *  @return string          		String with status
1189
     */
1190
    public function getLibStatut($mode, $hidenastatus = 0)
1191
    {
1192
        return $this->LibStatut($this->percentage, $mode, $hidenastatus, $this->datep);
1193
    }
1194
1195
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1196
    /**
1197
     *  Return label of action status
1198
     *
1199
     *  @param  int     $percent        Percent
1200
     *  @param  int		$mode           0=Long label, 1=Short label, 2=Picto+Short label, 3=Picto, 4=Picto+Short label, 5=Short label+Picto, 6=Picto+Long label, 7=Very short label+Picto
1201
     *  @param  int		$hidenastatus   1=Show nothing if status is "Not applicable"
1202
     *  @param  int     $datestart      Date start of event
1203
     *  @return string		    		Label
1204
     */
1205
    public function LibStatut($percent, $mode, $hidenastatus = 0, $datestart = '')
1206
    {
1207
        // phpcs:enable
1208
        global $langs;
1209
1210
        if ($mode == 0)
1211
        {
1212
            if ($percent==-1 && ! $hidenastatus) return $langs->trans('StatusNotApplicable');
1213
            elseif ($percent==0) return $langs->trans('StatusActionToDo').' (0%)';
1214
            elseif ($percent > 0 && $percent < 100) return $langs->trans('StatusActionInProcess').' ('.$percent.'%)';
1215
            elseif ($percent >= 100) return $langs->trans('StatusActionDone').' (100%)';
1216
        }
1217
        elseif ($mode == 1)
1218
        {
1219
        	if ($percent==-1 && ! $hidenastatus) return $langs->trans('StatusNotApplicable');
1220
        	elseif ($percent==0) return $langs->trans('StatusActionToDo');
1221
        	elseif ($percent > 0 && $percent < 100) return $percent.'%';
1222
        	elseif ($percent >= 100) return $langs->trans('StatusActionDone');
1223
        }
1224
        elseif ($mode == 2)
1225
        {
1226
        	if ($percent==-1 && ! $hidenastatus) return img_picto($langs->trans('StatusNotApplicable'), 'statut9').' '.$langs->trans('StatusNotApplicable');
1227
        	elseif ($percent==0) return img_picto($langs->trans('StatusActionToDo'), 'statut1').' '.$langs->trans('StatusActionToDo');
1228
        	elseif ($percent > 0 && $percent < 100) return img_picto($langs->trans('StatusActionInProcess'), 'statut3').' '. $percent.'%';
1229
        	elseif ($percent >= 100) return img_picto($langs->trans('StatusActionDone'), 'statut6').' '.$langs->trans('StatusActionDone');
1230
        }
1231
        elseif ($mode == 3)
1232
        {
1233
        	if ($percent==-1 && ! $hidenastatus) return img_picto($langs->trans("Status").': '.$langs->trans('StatusNotApplicable'), 'statut9');
1234
        	elseif ($percent==0) return img_picto($langs->trans("Status").': '.$langs->trans('StatusActionToDo').' (0%)', 'statut1');
1235
        	elseif ($percent > 0 && $percent < 100) return img_picto($langs->trans("Status").': '.$langs->trans('StatusActionInProcess').' ('.$percent.'%)', 'statut3');
1236
        	elseif ($percent >= 100) return img_picto($langs->trans("Status").': '.$langs->trans('StatusActionDone').' (100%)', 'statut6');
1237
        }
1238
        elseif ($mode == 4)
1239
        {
1240
        	if ($percent==-1 && ! $hidenastatus) return img_picto($langs->trans('StatusNotApplicable'), 'statut9').' '.$langs->trans('StatusNotApplicable');
1241
        	elseif ($percent==0) return img_picto($langs->trans('StatusActionToDo'), 'statut1').' '.$langs->trans('StatusActionToDo').' (0%)';
1242
        	elseif ($percent > 0 && $percent < 100) return img_picto($langs->trans('StatusActionInProcess'), 'statut3').' '.$langs->trans('StatusActionInProcess').' ('.$percent.'%)';
1243
        	elseif ($percent >= 100) return img_picto($langs->trans('StatusActionDone'), 'statut6').' '.$langs->trans('StatusActionDone').' (100%)';
1244
        }
1245
        elseif ($mode == 5)
1246
        {
1247
        	if ($percent==-1 && ! $hidenastatus) return img_picto($langs->trans('StatusNotApplicable'), 'statut9');
1248
        	elseif ($percent==0) return '0% '.img_picto($langs->trans('StatusActionToDo'), 'statut1');
1249
        	elseif ($percent > 0 && $percent < 100) return $percent.'% '.img_picto($langs->trans('StatusActionInProcess').' - '.$percent.'%', 'statut3');
1250
        	elseif ($percent >= 100) return $langs->trans('StatusActionDone').' '.img_picto($langs->trans('StatusActionDone'), 'statut6');
1251
        }
1252
        elseif ($mode == 6)
1253
        {
1254
        	if ($percent==-1 && ! $hidenastatus) return $langs->trans('StatusNotApplicable').' '.img_picto($langs->trans('StatusNotApplicable'), 'statut9');
1255
        	elseif ($percent==0) return $langs->trans('StatusActionToDo').' (0%) '.img_picto($langs->trans('StatusActionToDo'), 'statut1');
1256
        	elseif ($percent > 0 && $percent < 100) return $langs->trans('StatusActionInProcess').' ('.$percent.'%) '.img_picto($langs->trans('StatusActionInProcess').' - '.$percent.'%', 'statut3');
1257
        	elseif ($percent >= 100) return $langs->trans('StatusActionDone').' (100%) '.img_picto($langs->trans('StatusActionDone'), 'statut6');
1258
        }
1259
        elseif ($mode == 7)
1260
        {
1261
            if ($percent==-1 && ! $hidenastatus) return img_picto($langs->trans('StatusNotApplicable'), 'statut9');
1262
            elseif ($percent==0) return '0% '.img_picto($langs->trans('StatusActionToDo'), 'statut1');
1263
            elseif ($percent > 0 && $percent < 100) return $percent.'% '.img_picto($langs->trans('StatusActionInProcess').' - '.$percent.'%', 'statut3');
1264
            elseif ($percent >= 100) return img_picto($langs->trans('StatusActionDone'), 'statut6');
1265
        }
1266
1267
        return '';
1268
    }
1269
1270
    /**
1271
     *  Return URL of event
1272
     *  Use $this->id, $this->type_code, $this->label and $this->type_label
1273
     *
1274
     *  @param	int		$withpicto				0=No picto, 1=Include picto into link, 2=Only picto
1275
     *  @param	int		$maxlength				Max number of charaters into label. If negative, use the ref as label.
1276
     *  @param	string	$classname				Force style class on a link
1277
     *  @param	string	$option					''=Link to action, 'birthday'=Link to contact
1278
     *  @param	int		$overwritepicto			1=Overwrite picto
1279
     *  @param	int   	$notooltip		    	1=Disable tooltip
1280
     *  @param  int     $save_lastsearch_value  -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1281
     *  @return	string							Chaine avec URL
1282
     */
1283
    public function getNomUrl($withpicto = 0, $maxlength = 0, $classname = '', $option = '', $overwritepicto = 0, $notooltip = 0, $save_lastsearch_value = -1)
1284
    {
1285
        global $conf, $langs, $user, $hookmanager, $action;
1286
1287
        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
1288
1289
        if ((!$user->rights->agenda->allactions->read && $this->authorid != $user->id) || (!$user->rights->agenda->myactions->read && $this->authorid == $user->id))
1290
            $option = 'nolink';
1291
1292
        $label = $this->label;
1293
		if (empty($label)) $label=$this->libelle;   // For backward compatibility
1 ignored issue
show
Bug Best Practice introduced by
The property libelle does not exist on ActionComm. Did you maybe forget to declare it?
Loading history...
1294
1295
		$result='';
1296
1297
		// Set label of type
1298
		$labeltype = '';
1299
		if ($this->type_code)
1300
		{
1301
			$labeltype = ($langs->transnoentities("Action".$this->type_code) != "Action".$this->type_code)?$langs->transnoentities("Action".$this->type_code):$this->type_label;
1302
		}
1303
		if (empty($conf->global->AGENDA_USE_EVENT_TYPE))
1304
		{
1305
		    if ($this->type_code != 'AC_OTH_AUTO') $labeltype = $langs->trans('ActionAC_MANUAL');
1306
		}
1307
1308
		$tooltip = '<u>' . $langs->trans('ShowAction') . '</u>';
1309
		if (! empty($this->ref))
1310
			$tooltip .= '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
1311
		if (! empty($label))
1312
			$tooltip .= '<br><b>' . $langs->trans('Title') . ':</b> ' . $label;
1313
		if (! empty($labeltype))
1314
			$tooltip .= '<br><b>' . $langs->trans('Type') . ':</b> ' . $labeltype;
1315
		if (! empty($this->location))
1316
			$tooltip .= '<br><b>' . $langs->trans('Location') . ':</b> ' . $this->location;
1317
		if (! empty($this->note))
1 ignored issue
show
Deprecated Code introduced by
The property CommonObject::$note has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1317
		if (! empty(/** @scrutinizer ignore-deprecated */ $this->note))
Loading history...
1318
		    $tooltip .= '<br><b>' . $langs->trans('Note') . ':</b> ' . (dol_textishtml($this->note) ? str_replace(array("\r","\n"), "", $this->note) : str_replace(array("\r","\n"), '<br>', $this->note));
1 ignored issue
show
Deprecated Code introduced by
The property CommonObject::$note has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1318
		    $tooltip .= '<br><b>' . $langs->trans('Note') . ':</b> ' . (dol_textishtml($this->note) ? str_replace(array("\r","\n"), "", /** @scrutinizer ignore-deprecated */ $this->note) : str_replace(array("\r","\n"), '<br>', $this->note));
Loading history...
1319
		$linkclose='';
1320
		if (! empty($conf->global->AGENDA_USE_EVENT_TYPE) && $this->type_color)
1321
			$linkclose = ' style="background-color:#'.$this->type_color.'"';
1322
1323
		if (empty($notooltip))
1324
		{
1325
		    if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1326
		    {
1327
		        $label=$langs->trans("ShowAction");
1328
		        $linkclose.=' alt="'.dol_escape_htmltag($tooltip, 1).'"';
1329
		    }
1330
		    $linkclose.=' title="'.dol_escape_htmltag($tooltip, 1).'"';
1331
		    $linkclose.=' class="'.$classname.' classfortooltip"';
1332
1333
		    /*
1334
		    $hookmanager->initHooks(array('actiondao'));
1335
		    $parameters=array('id'=>$this->id);
1336
		    $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1337
		    $linkclose = ($hookmanager->resPrint ? $hookmanager->resPrint : $linkclose);
1338
		    */
1339
		}
1340
		else $linkclose.=' class="'.$classname.'"';
1341
1342
		$url='';
1343
		if ($option=='birthday')
1344
			$url = DOL_URL_ROOT.'/contact/perso.php?id='.$this->id;
1345
		else
1346
			$url = DOL_URL_ROOT.'/comm/action/card.php?id='.$this->id;
1347
		if ($option !== 'nolink')
1348
		{
1349
			// Add param to save lastsearch_values or not
1350
			$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
1351
			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
1352
			if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
1353
		}
1354
1355
		$linkstart = '<a href="'.$url.'"';
1356
		$linkstart.=$linkclose.'>';
1357
		$linkend='</a>';
1358
1359
		if ($option == 'nolink') {
1360
			$linkstart = '';
1361
			$linkend = '';
1362
		}
1363
		//print 'rrr'.$this->libelle.'rrr'.$this->label.'rrr'.$withpicto;
1364
1365
        if ($withpicto == 2)
1366
        {
1367
            $libelle=$label;
1368
            if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) $libelle=$labeltype;
1369
            $libelleshort='';
1370
        }
1371
        else
1372
        {
1373
            $libelle=(empty($this->libelle)?$label:$this->libelle.(($label && $label != $this->libelle)?' '.$label:''));
1374
            if (! empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($libelle)) $libelle=$labeltype;
1375
            if ($maxlength < 0) $libelleshort=$this->ref;
1376
            else $libelleshort=dol_trunc($libelle, $maxlength);
1377
        }
1378
1379
        if ($withpicto)
1380
        {
1381
            if (! empty($conf->global->AGENDA_USE_EVENT_TYPE))	// Add code into ()
1382
            {
1383
            	if ($labeltype)
1384
            	{
1385
                	$libelle.=(preg_match('/'.preg_quote($labeltype, '/').'/', $libelle)?'':' ('.$langs->transnoentities("Action".$this->type_code).')');
1386
            	}
1387
            }
1388
        }
1389
1390
        $result.=$linkstart;
1391
        if ($withpicto)	$result.=img_object(($notooltip?'':$langs->trans("ShowAction").': '.$libelle), ($overwritepicto?$overwritepicto:'action'), ($notooltip?'class="'.(($withpicto != 2) ? 'paddingright ' : '').'valigntextbottom"':'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1);
1392
        $result.=$libelleshort;
1393
        $result.=$linkend;
1394
1395
        global $action;
1396
        $hookmanager->initHooks(array('actiondao'));
1397
        $parameters=array('id'=>$this->id, 'getnomurl'=>$result);
1398
        $reshook=$hookmanager->executeHooks('getNomUrl', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
1399
        if ($reshook > 0) $result = $hookmanager->resPrint;
1400
        else $result .= $hookmanager->resPrint;
1401
1402
        return $result;
1403
    }
1404
1405
1406
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1407
    /**
1408
     *		Export events from database into a cal file.
1409
     *
1410
     *		@param	string		$format			'vcal', 'ical/ics', 'rss'
1411
     *		@param	string		$type			'event' or 'journal'
1412
     *		@param	int			$cachedelay		Do not rebuild file if date older than cachedelay seconds
1413
     *		@param	string		$filename		Force filename
1414
     *		@param	array		$filters		Array of filters. Exemple array('notolderthan'=>99, 'year'=>..., 'idfrom'=>..., 'notactiontype'=>'systemauto', 'project'=>123, ...)
1415
     *		@return int     					<0 if error, nb of events in new file if ok
1416
     */
1417
    public function build_exportfile($format, $type, $cachedelay, $filename, $filters)
1418
    {
1419
    	global $hookmanager;
1420
1421
        // phpcs:enable
1422
        global $conf,$langs,$dolibarr_main_url_root,$mysoc;
1423
1424
        require_once DOL_DOCUMENT_ROOT ."/core/lib/xcal.lib.php";
1425
        require_once DOL_DOCUMENT_ROOT ."/core/lib/date.lib.php";
1426
        require_once DOL_DOCUMENT_ROOT ."/core/lib/files.lib.php";
1427
1428
        dol_syslog(get_class($this)."::build_exportfile Build export file format=".$format.", type=".$type.", cachedelay=".$cachedelay.", filename=".$filename.", filters size=".count($filters), LOG_DEBUG);
1429
1430
        // Check parameters
1431
        if (empty($format)) return -1;
1432
1433
        // Clean parameters
1434
        if (! $filename)
1435
        {
1436
            $extension='vcs';
1437
            if ($format == 'ical') $extension='ics';
1438
            $filename=$format.'.'.$extension;
1439
        }
1440
1441
        // Create dir and define output file (definitive and temporary)
1442
        $result=dol_mkdir($conf->agenda->dir_temp);
1443
        $outputfile=$conf->agenda->dir_temp.'/'.$filename;
1444
1445
        $result=0;
1446
1447
        $buildfile=true;
1448
        $login='';$logina='';$logind='';$logint='';
1449
1450
        $now = dol_now();
1451
1452
        if ($cachedelay)
1453
        {
1454
            $nowgmt = dol_now();
1455
            include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1456
            if (dol_filemtime($outputfile) > ($nowgmt - $cachedelay))
1457
            {
1458
                dol_syslog(get_class($this)."::build_exportfile file ".$outputfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay."). Build is canceled");
1459
                $buildfile = false;
1460
            }
1461
        }
1462
1463
        if ($buildfile)
1464
        {
1465
            // Build event array
1466
            $eventarray=array();
1467
1468
            $sql = "SELECT a.id,";
1469
            $sql.= " a.datep,";		// Start
1470
            $sql.= " a.datep2,";	// End
1471
            $sql.= " a.durationp,";			// deprecated
1472
            $sql.= " a.datec, a.tms as datem,";
1473
            $sql.= " a.label, a.code, a.note, a.fk_action as type_id,";
1474
            $sql.= " a.fk_soc,";
1475
            $sql.= " a.fk_user_author, a.fk_user_mod,";
1476
            $sql.= " a.fk_user_action,";
1477
            $sql.= " a.fk_contact, a.percent as percentage,";
1478
            $sql.= " a.fk_element, a.elementtype,";
1479
            $sql.= " a.priority, a.fulldayevent, a.location, a.punctual, a.transparency,";
1480
            $sql.= " u.firstname, u.lastname,";
1481
            $sql.= " s.nom as socname,";
1482
            $sql.= " c.id as type_id, c.code as type_code, c.libelle";
1483
            $sql.= " FROM (".MAIN_DB_PREFIX."c_actioncomm as c, ".MAIN_DB_PREFIX."actioncomm as a)";
1484
            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author";	// Link to get author of event for export
1485
            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc";
1486
1487
			$parameters=array('filters' => $filters);
1488
			$reshook=$hookmanager->executeHooks('printFieldListFrom', $parameters);    // Note that $action and $object may have been modified by hook
1489
			$sql.=$hookmanager->resPrint;
1490
1491
			// We must filter on assignement table
1492
			if ($filters['logint']) $sql.=", ".MAIN_DB_PREFIX."actioncomm_resources as ar";
1493
			$sql.= " WHERE a.fk_action=c.id";
1494
            $sql.= " AND a.entity IN (".getEntity('agenda').")";
1495
            foreach ($filters as $key => $value)
1496
            {
1497
                if ($key == 'notolderthan' && $value != '') $sql.=" AND a.datep >= '".$this->db->idate($now-($value*24*60*60))."'";
1498
                if ($key == 'year')         $sql.=" AND a.datep BETWEEN '".$this->db->idate(dol_get_first_day($value, 1))."' AND '".$this->db->idate(dol_get_last_day($value, 12))."'";
1499
                if ($key == 'id')           $sql.=" AND a.id=".(is_numeric($value)?$value:0);
1500
                if ($key == 'idfrom')       $sql.=" AND a.id >= ".(is_numeric($value)?$value:0);
1501
                if ($key == 'idto')         $sql.=" AND a.id <= ".(is_numeric($value)?$value:0);
1502
                if ($key == 'project')      $sql.=" AND a.fk_project=".(is_numeric($value)?$value:0);
1503
                if ($key == 'actiontype')    $sql.=" AND c.type = '".$this->db->escape($value)."'";
1504
                if ($key == 'notactiontype') $sql.=" AND c.type <> '".$this->db->escape($value)."'";
1505
                // We must filter on assignement table
1506
				if ($key == 'logint')       $sql.= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'";
1507
                if ($key == 'logina')
1508
                {
1509
                    $logina=$value;
1510
                    $condition='=';
1511
                    if (preg_match('/^!/', $logina))
1512
                    {
1513
                        $logina=preg_replace('/^!/', '', $logina);
1514
                        $condition='<>';
1515
                    }
1516
                    $userforfilter=new User($this->db);
1517
                    $result=$userforfilter->fetch('', $logina);
1518
                    if ($result > 0) $sql.= " AND a.fk_user_author ".$condition." ".$userforfilter->id;
1519
                    elseif ($result < 0 || $condition == '=') $sql.= " AND a.fk_user_author = 0";
1520
                }
1521
                if ($key == 'logint')
1522
                {
1523
                    $logint=$value;
1524
                    $condition='=';
1525
                    if (preg_match('/^!/', $logint))
1526
                    {
1527
                        $logint=preg_replace('/^!/', '', $logint);
1528
                        $condition='<>';
1529
                    }
1530
                    $userforfilter=new User($this->db);
1531
                    $result=$userforfilter->fetch('', $logint);
1532
                    if ($result > 0) $sql.= " AND ar.fk_element = ".$userforfilter->id;
1533
                    elseif ($result < 0 || $condition == '=') $sql.= " AND ar.fk_element = 0";
1534
                }
1535
            }
1536
1537
            $sql.= " AND a.datep IS NOT NULL";		// To exclude corrupted events and avoid errors in lightning/sunbird import
1538
1539
			$parameters=array('filters' => $filters);
1540
			$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters);    // Note that $action and $object may have been modified by hook
1541
			$sql.=$hookmanager->resPrint;
1542
1543
            $sql.= " ORDER by datep";
1544
            //print $sql;exit;
1545
1546
            dol_syslog(get_class($this)."::build_exportfile select events", LOG_DEBUG);
1547
            $resql=$this->db->query($sql);
1548
            if ($resql)
1549
            {
1550
                // Note: Output of sql request is encoded in $conf->file->character_set_client
1551
                // This assignment in condition is not a bug. It allows walking the results.
1552
				$diff = 0;
1553
                while ($obj=$this->db->fetch_object($resql))
1554
                {
1555
                    $qualified=true;
1556
1557
                    // 'eid','startdate','duration','enddate','title','summary','category','email','url','desc','author'
1558
                    $event=array();
1559
                    $event['uid']='dolibarragenda-'.$this->db->database_name.'-'.$obj->id."@".$_SERVER["SERVER_NAME"];
1560
                    $event['type']=$type;
1561
                    $datestart=$this->db->jdate($obj->datep)-(empty($conf->global->AGENDA_EXPORT_FIX_TZ)?0:($conf->global->AGENDA_EXPORT_FIX_TZ*3600));
1562
                    $dateend=$this->db->jdate($obj->datep2)-(empty($conf->global->AGENDA_EXPORT_FIX_TZ)?0:($conf->global->AGENDA_EXPORT_FIX_TZ*3600));
1563
                    $duration=($datestart && $dateend)?($dateend - $datestart):0;
1564
                    $event['summary']=$obj->label.($obj->socname?" (".$obj->socname.")":"");
1565
                    $event['desc']=$obj->note;
1566
                    $event['startdate']=$datestart;
1567
                    $event['enddate']=$dateend;		// Not required with type 'journal'
1568
                    $event['duration']=$duration;	// Not required with type 'journal'
1569
                    $event['author']=dolGetFirstLastname($obj->firstname, $obj->lastname);
1570
                    $event['priority']=$obj->priority;
1571
                    $event['fulldayevent']=$obj->fulldayevent;
1572
                    $event['location']=$obj->location;
1573
                    $event['transparency']=(($obj->transparency > 0)?'OPAQUE':'TRANSPARENT');		// OPAQUE (busy) or TRANSPARENT (not busy)
1574
                    $event['punctual']=$obj->punctual;
1575
                    $event['category']=$obj->libelle;	// libelle type action
1576
					// Define $urlwithroot
1577
					$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1578
					$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;			// This is to use external domain name found into config file
1579
					//$urlwithroot=DOL_MAIN_URL_ROOT;						// This is to use same domain name than current
1580
                    $url=$urlwithroot.'/comm/action/card.php?id='.$obj->id;
1581
                    $event['url']=$url;
1582
                    $event['created']=$this->db->jdate($obj->datec)-(empty($conf->global->AGENDA_EXPORT_FIX_TZ)?0:($conf->global->AGENDA_EXPORT_FIX_TZ*3600));
1583
                    $event['modified']=$this->db->jdate($obj->datem)-(empty($conf->global->AGENDA_EXPORT_FIX_TZ)?0:($conf->global->AGENDA_EXPORT_FIX_TZ*3600));
1584
1585
                    if ($qualified && $datestart)
1586
                    {
1587
                        $eventarray[]=$event;
1588
                    }
1589
                    $diff++;
1590
                }
1591
            }
1592
            else
1593
            {
1594
                $this->error=$this->db->lasterror();
1595
                return -1;
1596
            }
1597
1598
            $langs->load("agenda");
1599
1600
            // Define title and desc
1601
            $more='';
1602
            if ($login)  $more=$langs->transnoentities("User").' '.$login;
1603
            if ($logina) $more=$langs->transnoentities("ActionsAskedBy").' '.$logina;
1604
            if ($logint) $more=$langs->transnoentities("ActionsToDoBy").' '.$logint;
1605
            if ($logind) $more=$langs->transnoentities("ActionsDoneBy").' '.$logind;
1606
            if ($more)
1607
            {
1608
                $title='Dolibarr actions '.$mysoc->name.' - '.$more;
1609
                $desc=$more;
1610
                $desc.=' ('.$mysoc->name.' - built by Dolibarr)';
1611
            }
1612
            else
1613
            {
1614
                $title='Dolibarr actions '.$mysoc->name;
1615
                $desc=$langs->transnoentities('ListOfActions');
1616
                $desc.=' ('.$mysoc->name.' - built by Dolibarr)';
1617
            }
1618
1619
            // Create temp file
1620
            $outputfiletmp=tempnam($conf->agenda->dir_temp, 'tmp');  // Temporary file (allow call of function by different threads
1621
            @chmod($outputfiletmp, octdec($conf->global->MAIN_UMASK));
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

1621
            /** @scrutinizer ignore-unhandled */ @chmod($outputfiletmp, octdec($conf->global->MAIN_UMASK));

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1622
1623
            // Write file
1624
            if ($format == 'vcal') $result=build_calfile($format, $title, $desc, $eventarray, $outputfiletmp);
1625
            elseif ($format == 'ical') $result=build_calfile($format, $title, $desc, $eventarray, $outputfiletmp);
1626
            elseif ($format == 'rss')  $result=build_rssfile($format, $title, $desc, $eventarray, $outputfiletmp);
1627
1628
            if ($result >= 0)
1629
            {
1630
                if (dol_move($outputfiletmp, $outputfile, 0, 1)) $result=1;
1631
                else
1632
                {
1633
                	$this->error='Failed to rename '.$outputfiletmp.' into '.$outputfile;
1634
                    dol_syslog(get_class($this)."::build_exportfile ".$this->error, LOG_ERR);
1635
                    dol_delete_file($outputfiletmp, 0, 1);
1636
                    $result=-1;
1637
                }
1638
            }
1639
            else
1640
            {
1641
                dol_syslog(get_class($this)."::build_exportfile build_xxxfile function fails to for format=".$format." outputfiletmp=".$outputfile, LOG_ERR);
1642
                dol_delete_file($outputfiletmp, 0, 1);
1643
                $langs->load("errors");
1644
                $this->error=$langs->trans("ErrorFailToCreateFile", $outputfile);
1645
            }
1646
        }
1647
1648
        return $result;
1649
    }
1650
1651
    /**
1652
     *  Initialise an instance with random values.
1653
     *  Used to build previews or test instances.
1654
     *  id must be 0 if object instance is a specimen.
1655
     *
1656
     *  @return	void
1657
     */
1658
    public function initAsSpecimen()
1659
    {
1660
        global $user;
1661
1662
        $now=dol_now();
1663
1664
        // Initialise parametres
1665
        $this->id=0;
1666
        $this->specimen=1;
1667
1668
        $this->type_code='AC_OTH';
1669
        $this->code='AC_SPECIMEN_CODE';
1670
        $this->label='Label of event Specimen';
1671
        $this->datec=$now;
1672
        $this->datem=$now;
1673
        $this->datep=$now;
1674
        $this->datef=$now;
1675
        $this->author=$user;
1 ignored issue
show
Deprecated Code introduced by
The property ActionComm::$author has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1675
        /** @scrutinizer ignore-deprecated */ $this->author=$user;
Loading history...
1676
        $this->usermod=$user;
1 ignored issue
show
Deprecated Code introduced by
The property ActionComm::$usermod has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1676
        /** @scrutinizer ignore-deprecated */ $this->usermod=$user;
Loading history...
1677
        $this->usertodo=$user;
1 ignored issue
show
Deprecated Code introduced by
The property ActionComm::$usertodo has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1677
        /** @scrutinizer ignore-deprecated */ $this->usertodo=$user;
Loading history...
1678
        $this->fulldayevent=0;
1679
        $this->punctual=0;
1 ignored issue
show
Deprecated Code introduced by
The property ActionComm::$punctual has been deprecated: Milestone is already event with end date = start date ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1679
        /** @scrutinizer ignore-deprecated */ $this->punctual=0;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
1680
        $this->percentage=0;
1681
        $this->location='Location';
1682
        $this->transparency=1;	// 1 means opaque
1683
        $this->priority=1;
1684
        $this->note = 'Note';
1 ignored issue
show
Deprecated Code introduced by
The property CommonObject::$note has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1684
        /** @scrutinizer ignore-deprecated */ $this->note = 'Note';
Loading history...
1685
1686
        $this->userownerid=$user->id;
1687
        $this->userassigned[$user->id]=array('id'=>$user->id, 'transparency'=> 1);
1688
    }
1689
1690
	/**
1691
	 *  Function used to replace a thirdparty id with another one.
1692
	 *
1693
	 *  @param DoliDB $db Database handler
1694
	 *  @param int $origin_id Old thirdparty id
1695
	 *  @param int $dest_id New thirdparty id
1696
	 *  @return bool
1697
	 */
1698
	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
1699
	{
1700
		$tables = array(
1701
			'actioncomm'
1702
		);
1703
1704
		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
1705
	}
1706
1707
    /**
1708
     *  Is the action delayed?
1709
     *
1710
     *  @return bool
1711
     */
1712
    public function hasDelay()
1713
    {
1714
        global $conf;
1715
1716
        $now = dol_now();
1717
1718
        return $this->datep && ($this->datep < ($now - $conf->agenda->warning_delay));
1719
    }
1720
1721
1722
    /**
1723
     *  Send reminders by emails
1724
     *  CAN BE A CRON TASK
1725
     *
1726
     *  @return int         0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
1727
     */
1728
    public function sendEmailsReminder()
1729
    {
1730
    	global $conf, $langs;
1731
1732
    	$error = 0;
1733
    	$this->output = '';
1734
		$this->error='';
1735
1736
    	if (empty($conf->agenda->enabled))	// Should not happen. If module disabled, cron job should not be visible.
1737
		{
1738
			$langs->load("agenda");
1739
			$this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Agenda"));
1740
			return 0;
1741
		}
1742
		if (empty($conf->global->AGENDA_REMINDER_EMAIL))
1743
    	{
1744
    		$langs->load("agenda");
1745
    		$this->output = $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Agenda"));
1746
    		return 0;
1747
    	}
1748
1749
    	$now = dol_now();
1750
1751
    	dol_syslog(__METHOD__, LOG_DEBUG);
1752
1753
    	$this->db->begin();
1754
1755
        // TODO Scan events of type 'email' into table llx_actioncomm_reminder with status todo, send email, then set status to done
1756
1757
        // Delete also very old past events (we do not keep more than 1 month record in past)
1758
        $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder WHERE dateremind < '".$this->db->jdate($now - (3600 * 24 * 32))."'";
1759
        $this->db->query($sql);
1760
1761
        $this->db->commit();
1762
1763
        return $error;
1764
    }
1765
}
1766