dolibarr  13.0.2
actioncomm.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2002-2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004-2011 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
5  * Copyright (C) 2011-2017 Juanjo Menent <jmenent@2byte.es>
6  * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
7  * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
8  * Copyright (C) 2018-2020 Frédéric France <frederic.france@netlogic.fr>
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 <https://www.gnu.org/licenses/>.
22  */
23 
29 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php';
30 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
31 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
32 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
33 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncommreminder.class.php';
34 
35 
39 class ActionComm extends CommonObject
40 {
44  public $element = 'action';
45 
49  public $table_element = 'actioncomm';
50 
54  public $table_rowid = 'id';
55 
59  public $picto = 'action';
60 
64  public $ismultientitymanaged = 1;
65 
71  public $restrictiononfksoc = 2;
72 
76  public $id;
77 
81  public $ref;
82 
86  public $type_id;
87 
91  public $type_code;
92 
96  public $type_label;
97 
101  public $type;
102 
106  public $type_color;
107 
111  public $code;
112 
116  public $label;
117 
121  public $datec;
122 
126  public $datef;
127 
131  public $duree;
132 
136  public $datem;
137 
143  public $author;
144 
150  public $usermod;
151 
155  public $authorid;
156 
160  public $usermodid;
161 
165  public $datep;
166 
170  public $datep2;
171 
176  public $durationp = -1;
177 
181  public $fulldayevent = 0;
182 
186  public $percentage;
187 
191  public $location;
192 
196  public $transparency;
197 
201  public $priority;
202 
206  public $userassigned = array();
207 
211  public $userownerid;
212 
217  public $userdoneid;
218 
222  public $socpeopleassigned = array();
223 
227  public $otherassigned = array();
228 
232  public $reminders = array();
233 
239  public $usertodo;
240 
246  public $userdone;
247 
251  public $socid;
252 
256  public $contactid;
257 
263  public $societe;
264 
270  public $contact;
271 
272  // Properties for links to other objects
276  public $fk_element; // Id of record
277 
281  public $elementid;
282 
286  public $elementtype;
287 
291  public $icalname;
292 
296  public $icalcolor;
297 
301  public $extraparams;
302 
306  public $actions = array();
307 
311  public $email_msgid;
312 
316  public $email_from;
317 
321  public $email_sender;
322 
326  public $email_to;
327 
331  public $email_tocc;
335  public $email_tobcc;
336 
340  public $email_subject;
341 
345  public $errors_to;
346 
350  const EVENT_TODO = 0;
351 
355  const EVENT_IN_PROGRESS = 50;
356 
360  const EVENT_FINISHED = 100;
361 
367  public function __construct(DoliDB $db)
368  {
369  $this->db = $db;
370  }
371 
380  public function create(User $user, $notrigger = 0)
381  {
382  global $langs, $conf, $hookmanager;
383 
384  $error = 0;
385  $now = dol_now();
386 
387  // Check parameters
388  if (!isset($this->userownerid) || $this->userownerid === '') // $this->userownerid may be 0 (anonymous event) of > 0
389  {
390  dol_syslog("You tried to create an event but mandatory property ownerid was not defined", LOG_WARNING);
391  $this->errors[] = 'ErrorPropertyUserowneridNotDefined';
392  return -1;
393  }
394 
395  // Clean parameters
396  $this->label = dol_trunc(trim($this->label), 128);
397  $this->location = dol_trunc(trim($this->location), 128);
398  $this->note_private = dol_htmlcleanlastbr(trim(empty($this->note_private) ? $this->note : $this->note_private));
399  if (empty($this->percentage)) $this->percentage = 0;
400  if (empty($this->priority) || !is_numeric($this->priority)) $this->priority = 0;
401  if (empty($this->fulldayevent)) $this->fulldayevent = 0;
402  if (empty($this->transparency)) $this->transparency = 0;
403  if ($this->percentage > 100) $this->percentage = 100;
404  //if ($this->percentage == 100 && ! $this->dateend) $this->dateend = $this->date;
405  if (!empty($this->datep) && !empty($this->datef)) $this->durationp = ($this->datef - $this->datep); // deprecated
406  //if (! empty($this->date) && ! empty($this->dateend)) $this->durationa=($this->dateend - $this->date);
407  if (!empty($this->datep) && !empty($this->datef) && $this->datep > $this->datef) $this->datef = $this->datep;
408  //if (! empty($this->date) && ! empty($this->dateend) && $this->date > $this->dateend) $this->dateend=$this->date;
409  if (!isset($this->fk_project) || $this->fk_project < 0) $this->fk_project = 0;
410  // For backward compatibility
411  if ($this->elementtype == 'facture') $this->elementtype = 'invoice';
412  if ($this->elementtype == 'commande') $this->elementtype = 'order';
413  if ($this->elementtype == 'contrat') $this->elementtype = 'contract';
414 
415  if (!is_array($this->userassigned) && !empty($this->userassigned)) // For backward compatibility when userassigned was an int instead fo array
416  {
417  $tmpid = $this->userassigned;
418  $this->userassigned = array();
419  $this->userassigned[$tmpid] = array('id'=>$tmpid, 'transparency'=>$this->transparency);
420  }
421 
422  $userownerid = $this->userownerid;
423  $userdoneid = $this->userdoneid;
424 
425  // Be sure assigned user is defined as an array of array('id'=>,'mandatory'=>,...).
426  if (empty($this->userassigned) || count($this->userassigned) == 0 || !is_array($this->userassigned))
427  $this->userassigned = array($userownerid=>array('id'=>$userownerid, 'transparency'=>$this->transparency));
428 
429  if (!$this->type_id || !$this->type_code)
430  {
431  $key = empty($this->type_id) ? $this->type_code : $this->type_id;
432 
433  // Get id from code
434  $cactioncomm = new CActionComm($this->db);
435  $result = $cactioncomm->fetch($key);
436 
437  if ($result > 0)
438  {
439  $this->type_id = $cactioncomm->id;
440  $this->type_code = $cactioncomm->code;
441  } elseif ($result == 0)
442  {
443  $this->error = 'Failed to get record with id '.$this->type_id.' code '.$this->type_code.' from dictionary "type of events"';
444  return -1;
445  } else {
446  $this->error = $cactioncomm->error;
447  return -1;
448  }
449  }
450  $code = empty($this->code) ? $this->type_code : $this->code;
451 
452  // Check parameters
453  if (!$this->type_id)
454  {
455  $this->error = "ErrorWrongParameters";
456  return -1;
457  }
458 
459  $this->db->begin();
460 
461  $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm";
462  $sql .= "(datec,";
463  $sql .= "datep,";
464  $sql .= "datep2,";
465  $sql .= "durationp,"; // deprecated
466  $sql .= "fk_action,";
467  $sql .= "code,";
468  $sql .= "ref_ext,";
469  $sql .= "fk_soc,";
470  $sql .= "fk_project,";
471  $sql .= "note,";
472  $sql .= "fk_contact,";
473  $sql .= "fk_user_author,";
474  $sql .= "fk_user_action,";
475  $sql .= "fk_user_done,";
476  $sql .= "label,percent,priority,fulldayevent,location,";
477  $sql .= "transparency,";
478  $sql .= "fk_element,";
479  $sql .= "elementtype,";
480  $sql .= "entity,";
481  $sql .= "extraparams,";
482  // Fields emails
483  $sql .= "email_msgid,";
484  $sql .= "email_from,";
485  $sql .= "email_sender,";
486  $sql .= "email_to,";
487  $sql .= "email_tocc,";
488  $sql .= "email_tobcc,";
489  $sql .= "email_subject,";
490  $sql .= "errors_to";
491  $sql .= ") VALUES (";
492  $sql .= "'".$this->db->idate($now)."', ";
493  $sql .= (strval($this->datep) != '' ? "'".$this->db->idate($this->datep)."'" : "null").", ";
494  $sql .= (strval($this->datef) != '' ? "'".$this->db->idate($this->datef)."'" : "null").", ";
495  $sql .= ((isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '') ? "'".$this->db->escape($this->durationp)."'" : "null").", "; // deprecated
496  $sql .= (isset($this->type_id) ? $this->type_id : "null").",";
497  $sql .= ($code ? ("'".$this->db->escape($code)."'") : "null").", ";
498  $sql .= (!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").", ";
499  $sql .= ((isset($this->socid) && $this->socid > 0) ? $this->socid : "null").", ";
500  $sql .= ((isset($this->fk_project) && $this->fk_project > 0) ? $this->fk_project : "null").", ";
501  $sql .= " '".$this->db->escape($this->note_private)."', ";
502  $sql .= ((isset($this->contact_id) && $this->contact_id > 0) ? $this->contact_id : "null").", "; // deprecated, use ->socpeopleassigned
503  $sql .= (isset($user->id) && $user->id > 0 ? $user->id : "null").", ";
504  $sql .= ($userownerid > 0 ? $userownerid : "null").", ";
505  $sql .= ($userdoneid > 0 ? $userdoneid : "null").", ";
506  $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)."', ";
507  $sql .= "'".$this->db->escape($this->transparency)."', ";
508  $sql .= (!empty($this->fk_element) ? $this->fk_element : "null").", ";
509  $sql .= (!empty($this->elementtype) ? "'".$this->db->escape($this->elementtype)."'" : "null").", ";
510  $sql .= $conf->entity.",";
511  $sql .= (!empty($this->extraparams) ? "'".$this->db->escape($this->extraparams)."'" : "null").", ";
512  // Fields emails
513  $sql .= (!empty($this->email_msgid) ? "'".$this->db->escape($this->email_msgid)."'" : "null").", ";
514  $sql .= (!empty($this->email_from) ? "'".$this->db->escape($this->email_from)."'" : "null").", ";
515  $sql .= (!empty($this->email_sender) ? "'".$this->db->escape($this->email_sender)."'" : "null").", ";
516  $sql .= (!empty($this->email_to) ? "'".$this->db->escape($this->email_to)."'" : "null").", ";
517  $sql .= (!empty($this->email_tocc) ? "'".$this->db->escape($this->email_tocc)."'" : "null").", ";
518  $sql .= (!empty($this->email_tobcc) ? "'".$this->db->escape($this->email_tobcc)."'" : "null").", ";
519  $sql .= (!empty($this->email_subject) ? "'".$this->db->escape($this->email_subject)."'" : "null").", ";
520  $sql .= (!empty($this->errors_to) ? "'".$this->db->escape($this->errors_to)."'" : "null");
521  $sql .= ")";
522 
523  dol_syslog(get_class($this)."::add", LOG_DEBUG);
524  $resql = $this->db->query($sql);
525  if ($resql)
526  {
527  $this->ref = $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."actioncomm", "id");
528 
529  // Now insert assigned users
530  if (!$error)
531  {
532  //dol_syslog(var_export($this->userassigned, true));
533  foreach ($this->userassigned as $key => $val)
534  {
535  if (!is_array($val)) // For backward compatibility when val=id
536  {
537  $val = array('id'=>$val);
538  }
539 
540  if ($val['id'] > 0)
541  {
542  $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
543  $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']).")";
544 
545  $resql = $this->db->query($sql);
546  if (!$resql)
547  {
548  $error++;
549  dol_syslog('Error to process userassigned: '.$this->db->lasterror(), LOG_ERR);
550  $this->errors[] = $this->db->lasterror();
551  }
552  //var_dump($sql);exit;
553  }
554  }
555  }
556 
557  if (!$error)
558  {
559  if (!empty($this->socpeopleassigned))
560  {
561  foreach ($this->socpeopleassigned as $id => $val)
562  {
563  $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
564  $sql .= " VALUES(".$this->id.", 'socpeople', ".$id.", 0, 0, 0)";
565 
566  $resql = $this->db->query($sql);
567  if (!$resql)
568  {
569  $error++;
570  dol_syslog('Error to process socpeopleassigned: '.$this->db->lasterror(), LOG_ERR);
571  $this->errors[] = $this->db->lasterror();
572  }
573  }
574  }
575  }
576 
577  if (!$error)
578  {
579  // Actions on extra fields
580  $result = $this->insertExtraFields();
581  if ($result < 0)
582  {
583  $error++;
584  }
585  }
586 
587  if (!$error && !$notrigger)
588  {
589  // Call trigger
590  $result = $this->call_trigger('ACTION_CREATE', $user);
591  if ($result < 0) { $error++; }
592  // End call triggers
593  }
594 
595  if (!$error)
596  {
597  $this->db->commit();
598  return $this->id;
599  } else {
600  $this->db->rollback();
601  return -1;
602  }
603  } else {
604  $this->db->rollback();
605  $this->error = $this->db->lasterror();
606  return -1;
607  }
608  }
609 
617  public function createFromClone(User $fuser, $socid)
618  {
619  global $db, $conf, $hookmanager;
620 
621  $error = 0;
622  $now = dol_now();
623 
624  $this->db->begin();
625 
626  // Load source object
627  $objFrom = clone $this;
628 
629  // Retrieve all extrafield
630  // fetch optionals attributes and labels
631  $this->fetch_optionals();
632 
633  //$this->fetch_userassigned();
634  $this->fetchResources();
635 
636  $this->id = 0;
637 
638  // Create clone
639  $this->context['createfromclone'] = 'createfromclone';
640  $result = $this->create($fuser);
641  if ($result < 0) $error++;
642 
643  if (!$error)
644  {
645  // Hook of thirdparty module
646  if (is_object($hookmanager))
647  {
648  $parameters = array('objFrom'=>$objFrom);
649  $action = '';
650  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
651  if ($reshook < 0) $error++;
652  }
653 
654  // Call trigger
655  $result = $this->call_trigger('ACTION_CLONE', $fuser);
656  if ($result < 0) { $error++; }
657  // End call triggers
658  }
659 
660  unset($this->context['createfromclone']);
661 
662  // End
663  if (!$error)
664  {
665  $this->db->commit();
666  return $this->id;
667  } else {
668  $this->db->rollback();
669  return -1;
670  }
671  }
672 
682  public function fetch($id, $ref = '', $ref_ext = '', $email_msgid = '')
683  {
684  global $langs;
685 
686  $sql = "SELECT a.id,";
687  $sql .= " a.id as ref,";
688  $sql .= " a.entity,";
689  $sql .= " a.ref_ext,";
690  $sql .= " a.datep,";
691  $sql .= " a.datep2,";
692  $sql .= " a.durationp,"; // deprecated
693  $sql .= " a.datec,";
694  $sql .= " a.tms as datem,";
695  $sql .= " a.code, a.label, a.note,";
696  $sql .= " a.fk_soc,";
697  $sql .= " a.fk_project,";
698  $sql .= " a.fk_user_author, a.fk_user_mod,";
699  $sql .= " a.fk_user_action, a.fk_user_done,";
700  $sql .= " a.fk_contact, a.percent as percentage,";
701  $sql .= " a.fk_element as elementid, a.elementtype,";
702  $sql .= " a.priority, a.fulldayevent, a.location, a.transparency,";
703  $sql .= " a.email_msgid, a.email_subject, a.email_from, a.email_to, a.email_tocc, a.email_tobcc, a.errors_to,";
704  $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,";
705  $sql .= " s.nom as socname,";
706  $sql .= " u.firstname, u.lastname as lastname";
707  $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a ";
708  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action=c.id ";
709  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author";
710  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc";
711  $sql .= " WHERE ";
712  if ($ref) $sql .= " a.id = ".((int) $ref); // No field ref, we use id
713  elseif ($ref_ext) $sql .= " a.ref_ext = '".$this->db->escape($ref_ext)."'";
714  elseif ($email_msgid) $sql .= " a.email_msgid = '".$this->db->escape($email_msgid)."'";
715  else $sql .= " a.id = ".((int) $id);
716 
717  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
718  $resql = $this->db->query($sql);
719  if ($resql)
720  {
721  $num = $this->db->num_rows($resql);
722  if ($num)
723  {
724  $obj = $this->db->fetch_object($resql);
725 
726  $this->id = $obj->id;
727  $this->entity = $obj->entity;
728  $this->ref = $obj->ref;
729  $this->ref_ext = $obj->ref_ext;
730 
731  // Properties of parent table llx_c_actioncomm
732  $this->type_id = $obj->type_id;
733  $this->type_code = $obj->type_code;
734  $this->type_color = $obj->type_color;
735  $this->type_picto = $obj->type_picto;
736  $transcode = $langs->trans("Action".$obj->type_code);
737  $this->type = (($transcode != "Action".$obj->type_code) ? $transcode : $obj->type_label);
738  $transcode = $langs->trans("Action".$obj->type_code.'Short');
739  $this->type_short = (($transcode != "Action".$obj->type_code.'Short') ? $transcode : '');
740 
741  $this->code = $obj->code;
742  $this->label = $obj->label;
743  $this->datep = $this->db->jdate($obj->datep);
744  $this->datef = $this->db->jdate($obj->datep2);
745 
746  $this->datec = $this->db->jdate($obj->datec);
747  $this->datem = $this->db->jdate($obj->datem);
748 
749  $this->note = $obj->note; // deprecated
750  $this->note_private = $obj->note;
751  $this->percentage = $obj->percentage;
752 
753  $this->authorid = $obj->fk_user_author;
754  $this->usermodid = $obj->fk_user_mod;
755 
756  if (!is_object($this->author)) $this->author = new stdClass(); // To avoid warning
757  $this->author->id = $obj->fk_user_author; // deprecated
758  $this->author->firstname = $obj->firstname; // deprecated
759  $this->author->lastname = $obj->lastname; // deprecated
760  if (!is_object($this->usermod)) $this->usermod = new stdClass(); // To avoid warning
761  $this->usermod->id = $obj->fk_user_mod; // deprecated
762 
763  $this->userownerid = $obj->fk_user_action;
764  $this->userdoneid = $obj->fk_user_done;
765  $this->priority = $obj->priority;
766  $this->fulldayevent = $obj->fulldayevent;
767  $this->location = $obj->location;
768  $this->transparency = $obj->transparency;
769 
770  $this->socid = $obj->fk_soc; // To have fetch_thirdparty method working
771  $this->contact_id = $obj->fk_contact; // To have fetch_contact method working
772  $this->fk_project = $obj->fk_project; // To have fetch_projet method working
773 
774  //$this->societe->id = $obj->fk_soc; // deprecated
775  //$this->contact->id = $obj->fk_contact; // deprecated
776 
777  $this->fk_element = $obj->elementid;
778  $this->elementid = $obj->elementid;
779  $this->elementtype = $obj->elementtype;
780 
781  $this->fetchResources();
782  }
783  $this->db->free($resql);
784  } else {
785  $this->error = $this->db->lasterror();
786  return -1;
787  }
788 
789  return $num;
790  }
791 
797  public function fetchResources()
798  {
799  $this->userassigned = array();
800  $this->socpeopleassigned = array();
801 
802  $sql = 'SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency';
803  $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm_resources';
804  $sql .= ' WHERE fk_actioncomm = '.$this->id;
805  $sql .= " AND element_type IN ('user', 'socpeople')";
806  $resql = $this->db->query($sql);
807  if ($resql)
808  {
809  // If owner is known, we must but id first into list
810  if ($this->userownerid > 0) $this->userassigned[$this->userownerid] = array('id'=>$this->userownerid); // Set first so will be first into list.
811 
812  while ($obj = $this->db->fetch_object($resql))
813  {
814  if ($obj->fk_element > 0)
815  {
816  switch ($obj->element_type) {
817  case 'user':
818  $this->userassigned[$obj->fk_element] = array('id'=>$obj->fk_element, 'mandatory'=>$obj->mandatory, 'answer_status'=>$obj->answer_status, 'transparency'=>$obj->transparency);
819  if (empty($this->userownerid)) $this->userownerid = $obj->fk_element; // If not defined (should not happened, we fix this)
820  break;
821  case 'socpeople':
822  $this->socpeopleassigned[$obj->fk_element] = array('id'=>$obj->fk_element, 'mandatory'=>$obj->mandatory, 'answer_status'=>$obj->answer_status, 'transparency'=>$obj->transparency);
823  break;
824  }
825  }
826  }
827 
828  return 1;
829  } else {
830  dol_print_error($this->db);
831  return -1;
832  }
833  }
834 
835  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
842  public function fetch_userassigned($override = true)
843  {
844  // phpcs:enable
845  $sql = "SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency";
846  $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm_resources";
847  $sql .= " WHERE element_type = 'user' AND fk_actioncomm = ".$this->id;
848 
849  $resql2 = $this->db->query($sql);
850  if ($resql2)
851  {
852  $this->userassigned = array();
853 
854  // If owner is known, we must but id first into list
855  if ($this->userownerid > 0)
856  {
857  // Set first so will be first into list.
858  $this->userassigned[$this->userownerid] = array('id'=>$this->userownerid);
859  }
860 
861  while ($obj = $this->db->fetch_object($resql2))
862  {
863  if ($obj->fk_element > 0)
864  {
865  $this->userassigned[$obj->fk_element] = array('id'=>$obj->fk_element,
866  'mandatory'=>$obj->mandatory,
867  'answer_status'=>$obj->answer_status,
868  'transparency'=>$obj->transparency);
869  }
870 
871  if ($override === true)
872  {
873  // If not defined (should not happened, we fix this)
874  if (empty($this->userownerid))
875  {
876  $this->userownerid = $obj->fk_element;
877  }
878  }
879  }
880 
881  return 1;
882  } else {
883  dol_print_error($this->db);
884  return -1;
885  }
886  }
887 
894  public function delete($notrigger = 0)
895  {
896  global $user;
897 
898  $error = 0;
899 
900  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
901 
902  $this->db->begin();
903 
904  // remove categorie association
905  if (!$error) {
906  $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_actioncomm";
907  $sql .= " WHERE fk_actioncomm=".$this->id;
908 
909  $res = $this->db->query($sql);
910  if (!$res) {
911  $this->error = $this->db->lasterror();
912  $error++;
913  }
914  }
915 
916  // remove actioncomm_resources
917  if (!$error) {
918  $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources";
919  $sql .= " WHERE fk_actioncomm=".$this->id;
920 
921  $res = $this->db->query($sql);
922  if (!$res) {
923  $this->error = $this->db->lasterror();
924  $error++;
925  }
926  }
927 
928  if (!$error)
929  {
930  $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
931  $sql .= " WHERE fk_actioncomm = ".$this->id;
932 
933  $res = $this->db->query($sql);
934  if (!$res) {
935  $this->error = $this->db->lasterror();
936  $error++;
937  }
938  }
939 
940  // Removed extrafields
941  if (!$error) {
942  $result = $this->deleteExtraFields();
943  if ($result < 0)
944  {
945  $error++;
946  dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
947  }
948  }
949 
950  // remove actioncomm
951  if (!$error) {
952  $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm";
953  $sql .= " WHERE id=".$this->id;
954 
955  $res = $this->db->query($sql);
956  if (!$res) {
957  $this->error = $this->db->lasterror();
958  $error++;
959  }
960  }
961 
962  if (!$error)
963  {
964  if (!$notrigger)
965  {
966  // Call trigger
967  $result = $this->call_trigger('ACTION_DELETE', $user);
968  if ($result < 0) { $error++; }
969  // End call triggers
970  }
971 
972  if (!$error)
973  {
974  $this->db->commit();
975  return 1;
976  } else {
977  $this->db->rollback();
978  return -2;
979  }
980  } else {
981  $this->db->rollback();
982  $this->error = $this->db->lasterror();
983  return -1;
984  }
985  }
986 
995  public function update($user, $notrigger = 0)
996  {
997  global $langs, $conf, $hookmanager;
998 
999  $error = 0;
1000 
1001  // Clean parameters
1002  $this->label = trim($this->label);
1003  $this->note_private = dol_htmlcleanlastbr(trim(!isset($this->note_private) ? $this->note : $this->note_private));
1004  if (empty($this->percentage)) $this->percentage = 0;
1005  if (empty($this->priority) || !is_numeric($this->priority)) $this->priority = 0;
1006  if (empty($this->transparency)) $this->transparency = 0;
1007  if (empty($this->fulldayevent)) $this->fulldayevent = 0;
1008  if ($this->percentage > 100) $this->percentage = 100;
1009  //if ($this->percentage == 100 && ! $this->dateend) $this->dateend = $this->date;
1010  if ($this->datep && $this->datef) $this->durationp = ($this->datef - $this->datep); // deprecated
1011  //if ($this->date && $this->dateend) $this->durationa=($this->dateend - $this->date);
1012  if ($this->datep && $this->datef && $this->datep > $this->datef) $this->datef = $this->datep;
1013  //if ($this->date && $this->dateend && $this->date > $this->dateend) $this->dateend=$this->date;
1014  if ($this->fk_project < 0) $this->fk_project = 0;
1015 
1016  // Check parameters
1017  if ($this->percentage == 0 && $this->userdoneid > 0)
1018  {
1019  $this->error = "ErrorCantSaveADoneUserWithZeroPercentage";
1020  return -1;
1021  }
1022 
1023  $socid = (($this->socid > 0) ? $this->socid : 0);
1024  $contactid = (($this->contact_id > 0) ? $this->contact_id : 0);
1025  $userownerid = ($this->userownerid ? $this->userownerid : 0);
1026  $userdoneid = ($this->userdoneid ? $this->userdoneid : 0);
1027 
1028  $this->db->begin();
1029 
1030  $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm ";
1031  $sql .= " SET percent = '".$this->db->escape($this->percentage)."'";
1032  if ($this->type_id > 0) $sql .= ", fk_action = '".$this->db->escape($this->type_id)."'";
1033  $sql .= ", label = ".($this->label ? "'".$this->db->escape($this->label)."'" : "null");
1034  $sql .= ", datep = ".(strval($this->datep) != '' ? "'".$this->db->idate($this->datep)."'" : 'null');
1035  $sql .= ", datep2 = ".(strval($this->datef) != '' ? "'".$this->db->idate($this->datef)."'" : 'null');
1036  $sql .= ", durationp = ".(isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '' ? "'".$this->db->escape($this->durationp)."'" : "null"); // deprecated
1037  $sql .= ", note = '".$this->db->escape($this->note_private)."'";
1038  $sql .= ", fk_project =".($this->fk_project > 0 ? $this->fk_project : "null");
1039  $sql .= ", fk_soc =".($socid > 0 ? $socid : "null");
1040  $sql .= ", fk_contact =".($contactid > 0 ? $contactid : "null");
1041  $sql .= ", priority = '".$this->db->escape($this->priority)."'";
1042  $sql .= ", fulldayevent = '".$this->db->escape($this->fulldayevent)."'";
1043  $sql .= ", location = ".($this->location ? "'".$this->db->escape($this->location)."'" : "null");
1044  $sql .= ", transparency = '".$this->db->escape($this->transparency)."'";
1045  $sql .= ", fk_user_mod = ".$user->id;
1046  $sql .= ", fk_user_action = ".($userownerid > 0 ? "'".$this->db->escape($userownerid)."'" : "null");
1047  $sql .= ", fk_user_done = ".($userdoneid > 0 ? "'".$this->db->escape($userdoneid)."'" : "null");
1048  if (!empty($this->fk_element)) $sql .= ", fk_element=".($this->fk_element ? $this->db->escape($this->fk_element) : "null");
1049  if (!empty($this->elementtype)) $sql .= ", elementtype=".($this->elementtype ? "'".$this->db->escape($this->elementtype)."'" : "null");
1050  $sql .= " WHERE id=".$this->id;
1051 
1052  dol_syslog(get_class($this)."::update", LOG_DEBUG);
1053  if ($this->db->query($sql))
1054  {
1055  $action = 'update';
1056 
1057  // Actions on extra fields
1058  if (!$error)
1059  {
1060  $result = $this->insertExtraFields();
1061  if ($result < 0)
1062  {
1063  $error++;
1064  }
1065  }
1066 
1067  // Now insert assignedusers
1068  if (!$error)
1069  {
1070  $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources where fk_actioncomm = ".$this->id." AND element_type = 'user'";
1071  $resql = $this->db->query($sql);
1072 
1073  foreach ($this->userassigned as $key => $val)
1074  {
1075  if (!is_array($val)) // For backward compatibility when val=id
1076  {
1077  $val = array('id'=>$val);
1078  }
1079  $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
1080  $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']).")";
1081 
1082  $resql = $this->db->query($sql);
1083  if (!$resql)
1084  {
1085  $error++;
1086  $this->errors[] = $this->db->lasterror();
1087  }
1088  //var_dump($sql);exit;
1089  }
1090  }
1091 
1092  if (!$error)
1093  {
1094  $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources where fk_actioncomm = ".$this->id." AND element_type = 'socpeople'";
1095  $resql = $this->db->query($sql);
1096 
1097  if (!empty($this->socpeopleassigned))
1098  {
1099  foreach (array_keys($this->socpeopleassigned) as $id)
1100  {
1101  $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
1102  $sql .= " VALUES(".$this->id.", 'socpeople', ".$id.", 0, 0, 0)";
1103 
1104  $resql = $this->db->query($sql);
1105  if (!$resql)
1106  {
1107  $error++;
1108  $this->errors[] = $this->db->lasterror();
1109  }
1110  }
1111  }
1112  }
1113 
1114  if (!$error && !$notrigger)
1115  {
1116  // Call trigger
1117  $result = $this->call_trigger('ACTION_MODIFY', $user);
1118  if ($result < 0) { $error++; }
1119  // End call triggers
1120  }
1121 
1122  if (!$error)
1123  {
1124  $this->db->commit();
1125  return 1;
1126  } else {
1127  $this->db->rollback();
1128  dol_syslog(get_class($this)."::update ".join(',', $this->errors), LOG_ERR);
1129  return -2;
1130  }
1131  } else {
1132  $this->db->rollback();
1133  $this->error = $this->db->lasterror();
1134  return -1;
1135  }
1136  }
1137 
1152  public static function getActions($db, $socid = 0, $fk_element = 0, $elementtype = '', $filter = '', $sortfield = 'a.datep', $sortorder = 'DESC', $limit = 0)
1153  {
1154  global $conf, $langs;
1155 
1156  $resarray = array();
1157 
1158  dol_syslog(get_class()."::getActions", LOG_DEBUG);
1159 
1160  $sql = "SELECT a.id";
1161  $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
1162  $sql .= " WHERE a.entity IN (".getEntity('agenda').")";
1163  if (!empty($socid)) $sql .= " AND a.fk_soc = ".$socid;
1164  if (!empty($elementtype))
1165  {
1166  if ($elementtype == 'project') {
1167  $sql .= ' AND a.fk_project = '.$fk_element;
1168  }
1169  elseif ($elementtype == 'contact') {
1170  $sql .= ' AND a.id IN';
1171  $sql .= " (SELECT fk_actioncomm FROM ".MAIN_DB_PREFIX."actioncomm_resources WHERE";
1172  $sql .= " element_type = 'socpeople' AND fk_element = ".$fk_element.')';
1173  }
1174  else {
1175  $sql .= " AND a.fk_element = ".(int) $fk_element." AND a.elementtype = '".$db->escape($elementtype)."'";
1176  }
1177  }
1178  if (!empty($filter)) $sql .= $filter;
1179  if ($sortorder && $sortfield) $sql .= $db->order($sortfield, $sortorder);
1180  $sql .= $db->plimit($limit, 0);
1181 
1182  $resql = $db->query($sql);
1183  if ($resql)
1184  {
1185  $num = $db->num_rows($resql);
1186 
1187  if ($num)
1188  {
1189  for ($i = 0; $i < $num; $i++)
1190  {
1191  $obj = $db->fetch_object($resql);
1192  $actioncommstatic = new ActionComm($db);
1193  $actioncommstatic->fetch($obj->id);
1194  $resarray[$i] = $actioncommstatic;
1195  }
1196  }
1197  $db->free($resql);
1198  return $resarray;
1199  } else {
1200  return $db->lasterror();
1201  }
1202  }
1203 
1204  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1212  public function load_board($user, $load_state_board = 0)
1213  {
1214  // phpcs:enable
1215  global $conf, $langs;
1216 
1217  if (empty($load_state_board)) {
1218  $sql = "SELECT a.id, a.datep as dp";
1219  } else {
1220  $this->nb = array();
1221  $sql = "SELECT count(a.id) as nb";
1222  }
1223  $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
1224  if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc";
1225  if (!$user->rights->agenda->allactions->read) {
1226  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."actioncomm_resources AS ar ON a.id = ar.fk_actioncomm AND ar.element_type ='user' AND ar.fk_element = ".$user->id;
1227  }
1228  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid";
1229  $sql .= " WHERE 1 = 1";
1230  if (empty($load_state_board)) $sql .= " AND a.percent >= 0 AND a.percent < 100";
1231  $sql .= " AND a.entity IN (".getEntity('agenda').")";
1232  if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND (a.fk_soc IS NULL OR sc.fk_user = ".$user->id.")";
1233  if ($user->socid) $sql .= " AND a.fk_soc = ".$user->socid;
1234  if (!$user->rights->agenda->allactions->read) {
1235  $sql .= " AND (a.fk_user_author = ".$user->id." OR a.fk_user_action = ".$user->id." OR a.fk_user_done = ".$user->id;
1236  $sql .= " OR ar.fk_element = ".$user->id; // Added by PV
1237  $sql .= ")";
1238  }
1239 
1240  $resql = $this->db->query($sql);
1241  if ($resql)
1242  {
1243  if (empty($load_state_board)) {
1244  $agenda_static = new ActionComm($this->db);
1245  $response = new WorkboardResponse();
1246  $response->warning_delay = $conf->agenda->warning_delay / 60 / 60 / 24;
1247  $response->label = $langs->trans("ActionsToDo");
1248  $response->labelShort = $langs->trans("ActionsToDoShort");
1249  $response->url = DOL_URL_ROOT.'/comm/action/list.php?action=show_list&actioncode=0&status=todo&mainmenu=agenda';
1250  if ($user->rights->agenda->allactions->read) $response->url .= '&filtert=-1';
1251  $response->img = img_object('', "action", 'class="inline-block valigntextmiddle"');
1252  }
1253  // This assignment in condition is not a bug. It allows walking the results.
1254  while ($obj = $this->db->fetch_object($resql)) {
1255  if (empty($load_state_board)) {
1256  $response->nbtodo++;
1257  $agenda_static->datep = $this->db->jdate($obj->dp);
1258  if ($agenda_static->hasDelay()) $response->nbtodolate++;
1259  } else {
1260  $this->nb["actionscomm"] = $obj->nb;
1261  }
1262  }
1263 
1264  $this->db->free($resql);
1265  if (empty($load_state_board)) return $response;
1266  else return 1;
1267  } else {
1268  dol_print_error($this->db);
1269  $this->error = $this->db->error();
1270  return -1;
1271  }
1272  }
1273 
1274 
1281  public function info($id)
1282  {
1283  $sql = 'SELECT ';
1284  $sql .= ' a.id,';
1285  $sql .= ' datec,';
1286  $sql .= ' tms as datem,';
1287  $sql .= ' fk_user_author,';
1288  $sql .= ' fk_user_mod';
1289  $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm as a';
1290  $sql .= ' WHERE a.id = '.$id;
1291 
1292  dol_syslog(get_class($this)."::info", LOG_DEBUG);
1293  $result = $this->db->query($sql);
1294  if ($result)
1295  {
1296  if ($this->db->num_rows($result))
1297  {
1298  $obj = $this->db->fetch_object($result);
1299  $this->id = $obj->id;
1300  if ($obj->fk_user_author)
1301  {
1302  $cuser = new User($this->db);
1303  $cuser->fetch($obj->fk_user_author);
1304  $this->user_creation = $cuser;
1305  }
1306  if ($obj->fk_user_mod)
1307  {
1308  $muser = new User($this->db);
1309  $muser->fetch($obj->fk_user_mod);
1310  $this->user_modification = $muser;
1311  }
1312 
1313  $this->date_creation = $this->db->jdate($obj->datec);
1314  if (!empty($obj->fk_user_mod)) $this->date_modification = $this->db->jdate($obj->datem);
1315  }
1316  $this->db->free($result);
1317  } else {
1318  dol_print_error($this->db);
1319  }
1320  }
1321 
1322 
1330  public function getLibStatut($mode, $hidenastatus = 0)
1331  {
1332  return $this->LibStatut($this->percentage, $mode, $hidenastatus, $this->datep);
1333  }
1334 
1335  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1345  public function LibStatut($percent, $mode, $hidenastatus = 0, $datestart = '')
1346  {
1347  // phpcs:enable
1348  global $langs;
1349 
1350  $labelStatus = $langs->trans('StatusNotApplicable');
1351  if ($percent == -1 && !$hidenastatus) $labelStatus = $langs->trans('StatusNotApplicable');
1352  elseif ($percent == 0) $labelStatus = $langs->trans('StatusActionToDo').' (0%)';
1353  elseif ($percent > 0 && $percent < 100) $labelStatus = $langs->trans('StatusActionInProcess').' ('.$percent.'%)';
1354  elseif ($percent >= 100) $labelStatus = $langs->trans('StatusActionDone').' (100%)';
1355 
1356  $labelStatusShort = $langs->trans('StatusNotApplicable');
1357  if ($percent == -1 && !$hidenastatus) $labelStatusShort = $langs->trans('NA');
1358  elseif ($percent == 0) $labelStatusShort = '0%';
1359  elseif ($percent > 0 && $percent < 100) $labelStatusShort = $percent.'%';
1360  elseif ($percent >= 100) $labelStatusShort = '100%';
1361 
1362  $statusType = 'status9';
1363  if ($percent == -1 && !$hidenastatus) $statusType = 'status9';
1364  if ($percent == 0) $statusType = 'status1';
1365  if ($percent > 0 && $percent < 100) $statusType = 'status3';
1366  if ($percent >= 100) $statusType = 'status6';
1367 
1368  return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
1369  }
1370 
1384  public function getNomUrl($withpicto = 0, $maxlength = 0, $classname = '', $option = '', $overwritepicto = 0, $notooltip = 0, $save_lastsearch_value = -1)
1385  {
1386  global $conf, $langs, $user, $hookmanager, $action;
1387 
1388  if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
1389 
1390  $canread = 0;
1391  if ($user->rights->agenda->myactions->read && $this->authorid == $user->id) $canread = 1; // Can read my event
1392  if ($user->rights->agenda->myactions->read && array_key_exists($user->id, $this->userassigned)) $canread = 1; // Can read my event i am assigned
1393  if ($user->rights->agenda->allactions->read) $canread = 1; // Can read all event of other
1394  if (!$canread)
1395  {
1396  $option = 'nolink';
1397  }
1398 
1399  $label = $this->label;
1400  if (empty($label)) $label = $this->libelle; // For backward compatibility
1401 
1402  $result = '';
1403 
1404  // Set label of type
1405  $labeltype = '';
1406  if ($this->type_code)
1407  {
1408  $labeltype = ($langs->transnoentities("Action".$this->type_code) != "Action".$this->type_code) ? $langs->transnoentities("Action".$this->type_code) : $this->type_label;
1409  }
1410  if (empty($conf->global->AGENDA_USE_EVENT_TYPE))
1411  {
1412  if ($this->type_code != 'AC_OTH_AUTO') $labeltype = $langs->trans('ActionAC_MANUAL');
1413  }
1414 
1415  $tooltip = img_picto('', $this->picto).' <u>'.$langs->trans('Action').'</u>';
1416  if (!empty($this->ref))
1417  $tooltip .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1418  if (!empty($label))
1419  $tooltip .= '<br><b>'.$langs->trans('Title').':</b> '.$label;
1420  if (!empty($labeltype))
1421  $tooltip .= '<br><b>'.$langs->trans('Type').':</b> '.$labeltype;
1422  if (!empty($this->location))
1423  $tooltip .= '<br><b>'.$langs->trans('Location').':</b> '.$this->location;
1424  if (isset($this->transparency))
1425  $tooltip .= '<br><b>'.$langs->trans('Busy').':</b> '.yn($this->transparency);
1426  if (!empty($this->note_private))
1427  $tooltip .= '<br><b>'.$langs->trans('Note').':</b> '.(dol_textishtml($this->note_private) ? str_replace(array("\r", "\n"), "", $this->note_private) : str_replace(array("\r", "\n"), '<br>', $this->note_private));
1428  $linkclose = '';
1429  if (!empty($conf->global->AGENDA_USE_EVENT_TYPE) && $this->type_color)
1430  $linkclose = ' style="background-color:#'.$this->type_color.'"';
1431 
1432  if (empty($notooltip))
1433  {
1434  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1435  {
1436  $label = $langs->trans("ShowAction");
1437  $linkclose .= ' alt="'.dol_escape_htmltag($tooltip, 1).'"';
1438  }
1439  $linkclose .= ' title="'.dol_escape_htmltag($tooltip, 1).'"';
1440  $linkclose .= ' class="'.$classname.' classfortooltip"';
1441 
1442  /*
1443  $hookmanager->initHooks(array('actiondao'));
1444  $parameters=array('id'=>$this->id);
1445  $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
1446  $linkclose = ($hookmanager->resPrint ? $hookmanager->resPrint : $linkclose);
1447  */
1448  } else $linkclose .= ' class="'.$classname.'"';
1449 
1450  $url = '';
1451  if ($option == 'birthday')
1452  $url = DOL_URL_ROOT.'/contact/perso.php?id='.$this->id;
1453  elseif ($option == 'holiday')
1454  $url = DOL_URL_ROOT.'/holiday/card.php?id='.$this->id;
1455  else $url = DOL_URL_ROOT.'/comm/action/card.php?id='.$this->id;
1456  if ($option !== 'nolink')
1457  {
1458  // Add param to save lastsearch_values or not
1459  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1460  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
1461  if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
1462  }
1463 
1464  $linkstart = '<a href="'.$url.'"';
1465  $linkstart .= $linkclose.'>';
1466  $linkend = '</a>';
1467 
1468  if ($option == 'nolink') {
1469  $linkstart = '';
1470  $linkend = '';
1471  }
1472 
1473  if ($withpicto == 2)
1474  {
1475  $libelle = $label;
1476  if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) $libelle = $labeltype;
1477  $libelleshort = '';
1478  } else {
1479  $libelle = (empty($this->libelle) ? $label : $this->libelle.(($label && $label != $this->libelle) ? ' '.$label : ''));
1480  if (!empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($libelle)) $libelle = $labeltype;
1481  if ($maxlength < 0) $libelleshort = $this->ref;
1482  else $libelleshort = dol_trunc($libelle, $maxlength);
1483  }
1484 
1485  if ($withpicto)
1486  {
1487  if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) // Add code into ()
1488  {
1489  if ($labeltype)
1490  {
1491  $libelle .= (preg_match('/'.preg_quote($labeltype, '/').'/', $libelle) ? '' : ' ('.$langs->transnoentities("Action".$this->type_code).')');
1492  }
1493  }
1494  }
1495 
1496  $result .= $linkstart;
1497  if ($withpicto) $result .= img_object(($notooltip ? '' : $langs->trans("ShowAction").': '.$libelle), ($overwritepicto ? $overwritepicto : 'action'), ($notooltip ? 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"' : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1498  $result .= $libelleshort;
1499  $result .= $linkend;
1500 
1501  global $action;
1502  $hookmanager->initHooks(array('actiondao'));
1503  $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
1504  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1505  if ($reshook > 0) $result = $hookmanager->resPrint;
1506  else $result .= $hookmanager->resPrint;
1507 
1508  return $result;
1509  }
1510 
1521  public function setCategories($categories)
1522  {
1523  // Handle single category
1524  if (!is_array($categories)) {
1525  $categories = array($categories);
1526  }
1527 
1528  // Get current categories
1529  include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1530  $c = new Categorie($this->db);
1531  $existing = $c->containing($this->id, Categorie::TYPE_ACTIONCOMM, 'id');
1532 
1533  // Diff
1534  if (is_array($existing)) {
1535  $to_del = array_diff($existing, $categories);
1536  $to_add = array_diff($categories, $existing);
1537  } else {
1538  $to_del = array(); // Nothing to delete
1539  $to_add = $categories;
1540  }
1541 
1542  // Process
1543  foreach ($to_del as $del) {
1544  if ($c->fetch($del) > 0) {
1545  $c->del_type($this, Categorie::TYPE_ACTIONCOMM);
1546  }
1547  }
1548  foreach ($to_add as $add) {
1549  if ($c->fetch($add) > 0) {
1550  $c->add_type($this, Categorie::TYPE_ACTIONCOMM);
1551  }
1552  }
1553  return;
1554  }
1555 
1556  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1568  public function build_exportfile($format, $type, $cachedelay, $filename, $filters, $exportholiday = 0)
1569  {
1570  global $hookmanager;
1571 
1572  // phpcs:enable
1573  global $conf, $langs, $dolibarr_main_url_root, $mysoc;
1574 
1575  require_once DOL_DOCUMENT_ROOT."/core/lib/xcal.lib.php";
1576  require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php";
1577  require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php";
1578 
1579  dol_syslog(get_class($this)."::build_exportfile Build export file format=".$format.", type=".$type.", cachedelay=".$cachedelay.", filename=".$filename.", filters size=".count($filters), LOG_DEBUG);
1580 
1581  // Check parameters
1582  if (empty($format)) return -1;
1583 
1584  // Clean parameters
1585  if (!$filename)
1586  {
1587  $extension = 'vcs';
1588  if ($format == 'ical') $extension = 'ics';
1589  $filename = $format.'.'.$extension;
1590  }
1591 
1592  // Create dir and define output file (definitive and temporary)
1593  $result = dol_mkdir($conf->agenda->dir_temp);
1594  $outputfile = $conf->agenda->dir_temp.'/'.$filename;
1595 
1596  $result = 0;
1597 
1598  $buildfile = true;
1599  $login = ''; $logina = ''; $logind = ''; $logint = '';
1600 
1601  $now = dol_now();
1602 
1603  if ($cachedelay)
1604  {
1605  $nowgmt = dol_now();
1606  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1607  if (dol_filemtime($outputfile) > ($nowgmt - $cachedelay))
1608  {
1609  dol_syslog(get_class($this)."::build_exportfile file ".$outputfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay."). Build is canceled");
1610  $buildfile = false;
1611  }
1612  }
1613 
1614  if ($buildfile)
1615  {
1616  // Build event array
1617  $eventarray = array();
1618 
1619  $sql = "SELECT a.id,";
1620  $sql .= " a.datep,"; // Start
1621  $sql .= " a.datep2,"; // End
1622  $sql .= " a.durationp,"; // deprecated
1623  $sql .= " a.datec, a.tms as datem,";
1624  $sql .= " a.label, a.code, a.note, a.fk_action as type_id,";
1625  $sql .= " a.fk_soc,";
1626  $sql .= " a.fk_user_author, a.fk_user_mod,";
1627  $sql .= " a.fk_user_action,";
1628  $sql .= " a.fk_contact, a.percent as percentage,";
1629  $sql .= " a.fk_element, a.elementtype,";
1630  $sql .= " a.priority, a.fulldayevent, a.location, a.transparency,";
1631  $sql .= " u.firstname, u.lastname, u.email,";
1632  $sql .= " s.nom as socname,";
1633  $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label";
1634  $sql .= " FROM (".MAIN_DB_PREFIX."c_actioncomm as c, ".MAIN_DB_PREFIX."actioncomm as a)";
1635  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author"; // Link to get author of event for export
1636  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc";
1637 
1638  $parameters = array('filters' => $filters);
1639  $reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters); // Note that $action and $object may have been modified by hook
1640  $sql .= $hookmanager->resPrint;
1641 
1642  // We must filter on assignement table
1643  if ($filters['logint']) $sql .= ", ".MAIN_DB_PREFIX."actioncomm_resources as ar";
1644  $sql .= " WHERE a.fk_action=c.id";
1645  $sql .= " AND a.entity IN (".getEntity('agenda').")";
1646  foreach ($filters as $key => $value)
1647  {
1648  if ($key == 'notolderthan' && $value != '') $sql .= " AND a.datep >= '".$this->db->idate($now - ($value * 24 * 60 * 60))."'";
1649  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))."'";
1650  if ($key == 'id') $sql .= " AND a.id=".(is_numeric($value) ? $value : 0);
1651  if ($key == 'idfrom') $sql .= " AND a.id >= ".(is_numeric($value) ? $value : 0);
1652  if ($key == 'idto') $sql .= " AND a.id <= ".(is_numeric($value) ? $value : 0);
1653  if ($key == 'project') $sql .= " AND a.fk_project=".(is_numeric($value) ? $value : 0);
1654  if ($key == 'actiontype') $sql .= " AND c.type = '".$this->db->escape($value)."'";
1655  if ($key == 'notactiontype') $sql .= " AND c.type <> '".$this->db->escape($value)."'";
1656  // We must filter on assignement table
1657  if ($key == 'logint') $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'";
1658  if ($key == 'logina')
1659  {
1660  $logina = $value;
1661  $condition = '=';
1662  if (preg_match('/^!/', $logina))
1663  {
1664  $logina = preg_replace('/^!/', '', $logina);
1665  $condition = '<>';
1666  }
1667  $userforfilter = new User($this->db);
1668  $result = $userforfilter->fetch('', $logina);
1669  if ($result > 0) $sql .= " AND a.fk_user_author ".$condition." ".$userforfilter->id;
1670  elseif ($result < 0 || $condition == '=') $sql .= " AND a.fk_user_author = 0";
1671  }
1672  if ($key == 'logint')
1673  {
1674  $logint = $value;
1675  $condition = '=';
1676  if (preg_match('/^!/', $logint))
1677  {
1678  $logint = preg_replace('/^!/', '', $logint);
1679  $condition = '<>';
1680  }
1681  $userforfilter = new User($this->db);
1682  $result = $userforfilter->fetch('', $logint);
1683  if ($result > 0) $sql .= " AND ar.fk_element = ".$userforfilter->id;
1684  elseif ($result < 0 || $condition == '=') $sql .= " AND ar.fk_element = 0";
1685  }
1686  }
1687 
1688  $sql .= " AND a.datep IS NOT NULL"; // To exclude corrupted events and avoid errors in lightning/sunbird import
1689 
1690  $parameters = array('filters' => $filters);
1691  $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
1692  $sql .= $hookmanager->resPrint;
1693 
1694  $sql .= " ORDER by datep";
1695  //print $sql;exit;
1696 
1697  dol_syslog(get_class($this)."::build_exportfile select events", LOG_DEBUG);
1698  $resql = $this->db->query($sql);
1699  if ($resql)
1700  {
1701  // Note: Output of sql request is encoded in $conf->file->character_set_client
1702  // This assignment in condition is not a bug. It allows walking the results.
1703  $diff = 0;
1704  while ($obj = $this->db->fetch_object($resql))
1705  {
1706  $qualified = true;
1707 
1708  // 'eid','startdate','duration','enddate','title','summary','category','email','url','desc','author'
1709  $event = array();
1710  $event['uid'] = 'dolibarragenda-'.$this->db->database_name.'-'.$obj->id."@".$_SERVER["SERVER_NAME"];
1711  $event['type'] = $type;
1712  $datestart = $this->db->jdate($obj->datep) - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600));
1713 
1714  // fix for -> Warning: A non-numeric value encountered
1715  if (is_numeric($this->db->jdate($obj->datep2)))
1716  {
1717  $dateend = $this->db->jdate($obj->datep2)
1718  - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600));
1719  } else {
1720  // use start date as fall-back to avoid import erros on empty end date
1721  $dateend = $datestart;
1722  }
1723 
1724  $duration = ($datestart && $dateend) ? ($dateend - $datestart) : 0;
1725  $event['summary'] = $obj->label.($obj->socname ? " (".$obj->socname.")" : "");
1726  $event['desc'] = $obj->note;
1727  $event['startdate'] = $datestart;
1728  $event['enddate'] = $dateend; // Not required with type 'journal'
1729  $event['duration'] = $duration; // Not required with type 'journal'
1730  $event['author'] = dolGetFirstLastname($obj->firstname, $obj->lastname);
1731  $event['priority'] = $obj->priority;
1732  $event['fulldayevent'] = $obj->fulldayevent;
1733  $event['location'] = $obj->location;
1734  $event['transparency'] = (($obj->transparency > 0) ? 'OPAQUE' : 'TRANSPARENT'); // OPAQUE (busy) or TRANSPARENT (not busy)
1735  $event['category'] = $obj->type_label;
1736  $event['email'] = $obj->email;
1737  // Define $urlwithroot
1738  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1739  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
1740  //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1741  $url = $urlwithroot.'/comm/action/card.php?id='.$obj->id;
1742  $event['url'] = $url;
1743  $event['created'] = $this->db->jdate($obj->datec) - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600));
1744  $event['modified'] = $this->db->jdate($obj->datem) - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600));
1745 
1746  // TODO: find a way to call "$this->fetch_userassigned();" without override "$this" properties
1747  $this->id = $obj->id;
1748  $this->fetch_userassigned(false);
1749 
1750  $assignedUserArray = array();
1751 
1752  foreach ($this->userassigned as $key => $value)
1753  {
1754  $assignedUser = new User($this->db);
1755  $assignedUser->fetch($value['id']);
1756 
1757  $assignedUserArray[$key] = $assignedUser;
1758  }
1759 
1760  $event['assignedUsers'] = $assignedUserArray;
1761 
1762  if ($qualified && $datestart)
1763  {
1764  $eventarray[] = $event;
1765  }
1766  $diff++;
1767  }
1768 
1769  $parameters = array('filters' => $filters, 'eventarray' => &$eventarray);
1770  $reshook = $hookmanager->executeHooks('addMoreEventsExport', $parameters); // Note that $action and $object may have been modified by hook
1771  if ($reshook > 0)
1772  {
1773  $eventarray = $hookmanager->resArray;
1774  }
1775  } else {
1776  $this->error = $this->db->lasterror();
1777  return -1;
1778  }
1779 
1780  if ($exportholiday == 1)
1781  {
1782  $langs->load("holidays");
1783  $title = $langs->trans("Holidays");
1784 
1785  $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.email, u.statut, x.rowid, x.date_debut as date_start, x.date_fin as date_end, x.halfday, x.statut as status";
1786  $sql .= " FROM ".MAIN_DB_PREFIX."holiday as x, ".MAIN_DB_PREFIX."user as u";
1787  $sql .= " WHERE u.rowid = x.fk_user";
1788  $sql .= " AND u.statut = '1'"; // Show only active users (0 = inactive user, 1 = active user)
1789  $sql .= " AND (x.statut = '2' OR x.statut = '3')"; // Show only public leaves (2 = leave wait for approval, 3 = leave approved)
1790 
1791  $resql = $this->db->query($sql);
1792  if ($resql)
1793  {
1794  $num = $this->db->num_rows($resql);
1795  $i = 0;
1796 
1797  while ($i < $num)
1798  {
1799  $obj = $this->db->fetch_object($resql);
1800  $event = array();
1801 
1802  if ($obj->halfday == -1)
1803  {
1804  $event['fulldayevent'] = false;
1805 
1806  $timestampStart = dol_stringtotime($obj->date_start." 00:00:00", 0);
1807  $timestampEnd = dol_stringtotime($obj->date_end." 12:00:00", 0);
1808  } elseif ($obj->halfday == 1)
1809  {
1810  $event['fulldayevent'] = false;
1811 
1812  $timestampStart = dol_stringtotime($obj->date_start." 12:00:00", 0);
1813  $timestampEnd = dol_stringtotime($obj->date_end." 23:59:59", 0);
1814  } else {
1815  $event['fulldayevent'] = true;
1816 
1817  $timestampStart = dol_stringtotime($obj->date_start." 00:00:00", 0);
1818  $timestampEnd = dol_stringtotime($obj->date_end." 23:59:59", 0);
1819  }
1820 
1821  if (!empty($conf->global->AGENDA_EXPORT_FIX_TZ))
1822  {
1823  $timestampStart = - ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600);
1824  $timestampEnd = - ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600);
1825  }
1826 
1827  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1828  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1829  $url = $urlwithroot.'/holiday/card.php?id='.$obj->rowid;
1830 
1831  $event['uid'] = 'dolibarrholiday-'.$this->db->database_name.'-'.$obj->rowid."@".$_SERVER["SERVER_NAME"];
1832  $event['author'] = dolGetFirstLastname($obj->firstname, $obj->lastname);
1833  $event['type'] = 'event';
1834  $event['category'] = "Holiday";
1835  $event['transparency'] = 'OPAQUE';
1836  $event['email'] = $obj->email;
1837  $event['created'] = $timestampStart;
1838  $event['modified'] = $timestampStart;
1839  $event['startdate'] = $timestampStart;
1840  $event['enddate'] = $timestampEnd;
1841  $event['duration'] = $timestampEnd - $timestampStart;
1842  $event['url'] = $url;
1843 
1844  if ($obj->status == 2)
1845  {
1846  // 2 = leave wait for approval
1847  $event['summary'] = $title." - ".$obj->lastname." (wait for approval)";
1848  } else {
1849  // 3 = leave approved
1850  $event['summary'] = $title." - ".$obj->lastname;
1851  }
1852 
1853  $eventarray[] = $event;
1854 
1855  $i++;
1856  }
1857  }
1858  }
1859 
1860  $langs->load("agenda");
1861 
1862  // Define title and desc
1863  $more = '';
1864  if ($login) $more = $langs->transnoentities("User").' '.$login;
1865  if ($logina) $more = $langs->transnoentities("ActionsAskedBy").' '.$logina;
1866  if ($logint) $more = $langs->transnoentities("ActionsToDoBy").' '.$logint;
1867  if ($logind) $more = $langs->transnoentities("ActionsDoneBy").' '.$logind;
1868  if ($more)
1869  {
1870  $title = 'Dolibarr actions '.$mysoc->name.' - '.$more;
1871  $desc = $more;
1872  $desc .= ' ('.$mysoc->name.' - built by Dolibarr)';
1873  } else {
1874  $title = 'Dolibarr actions '.$mysoc->name;
1875  $desc = $langs->transnoentities('ListOfActions');
1876  $desc .= ' ('.$mysoc->name.' - built by Dolibarr)';
1877  }
1878 
1879  // Create temp file
1880  $outputfiletmp = tempnam($conf->agenda->dir_temp, 'tmp'); // Temporary file (allow call of function by different threads
1881  @chmod($outputfiletmp, octdec($conf->global->MAIN_UMASK));
1882 
1883  // Write file
1884  if ($format == 'vcal') $result = build_calfile($format, $title, $desc, $eventarray, $outputfiletmp);
1885  elseif ($format == 'ical') $result = build_calfile($format, $title, $desc, $eventarray, $outputfiletmp);
1886  elseif ($format == 'rss') $result = build_rssfile($format, $title, $desc, $eventarray, $outputfiletmp);
1887 
1888  if ($result >= 0)
1889  {
1890  if (dol_move($outputfiletmp, $outputfile, 0, 1)) $result = 1;
1891  else {
1892  $this->error = 'Failed to rename '.$outputfiletmp.' into '.$outputfile;
1893  dol_syslog(get_class($this)."::build_exportfile ".$this->error, LOG_ERR);
1894  dol_delete_file($outputfiletmp, 0, 1);
1895  $result = -1;
1896  }
1897  } else {
1898  dol_syslog(get_class($this)."::build_exportfile build_xxxfile function fails to for format=".$format." outputfiletmp=".$outputfile, LOG_ERR);
1899  dol_delete_file($outputfiletmp, 0, 1);
1900  $langs->load("errors");
1901  $this->error = $langs->trans("ErrorFailToCreateFile", $outputfile);
1902  }
1903  }
1904 
1905  return $result;
1906  }
1907 
1915  public function initAsSpecimen()
1916  {
1917  global $user;
1918 
1919  $now = dol_now();
1920 
1921  // Initialise parametres
1922  $this->id = 0;
1923  $this->specimen = 1;
1924 
1925  $this->type_code = 'AC_OTH';
1926  $this->code = 'AC_SPECIMEN_CODE';
1927  $this->label = 'Label of event Specimen';
1928  $this->datec = $now;
1929  $this->datem = $now;
1930  $this->datep = $now;
1931  $this->datef = $now;
1932  $this->fulldayevent = 0;
1933  $this->percentage = 0;
1934  $this->location = 'Location';
1935  $this->transparency = 1; // 1 means opaque
1936  $this->priority = 1;
1937  //$this->note_public = "This is a 'public' note.";
1938  $this->note_private = "This is a 'private' note.";
1939 
1940  $this->userownerid = $user->id;
1941  $this->userassigned[$user->id] = array('id'=>$user->id, 'transparency'=> 1);
1942  return 1;
1943  }
1944 
1953  public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
1954  {
1955  $tables = array(
1956  'actioncomm'
1957  );
1958 
1959  return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
1960  }
1961 
1967  public function hasDelay()
1968  {
1969  global $conf;
1970 
1971  $now = dol_now();
1972 
1973  return $this->datep && ($this->datep < ($now - $conf->agenda->warning_delay));
1974  }
1975 
1976 
1985  public function loadReminders($type = '', $fk_user = 0, $onlypast = true)
1986  {
1987  global $conf, $langs, $user;
1988 
1989  $error = 0;
1990 
1991  $this->reminders = array();
1992 
1993  //Select all action comm reminders for event
1994  $sql = "SELECT rowid as id, typeremind, dateremind, status, offsetvalue, offsetunit, fk_user";
1995  $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
1996  $sql .= " WHERE fk_actioncomm = ".$this->id;
1997  if ($onlypast) {
1998  $sql .= " AND dateremind <= '".$this->db->idate(dol_now())."'";
1999  }
2000  if ($type) {
2001  $sql .= " AND typeremind ='".$this->db->escape($type)."'";
2002  }
2003  if ($fk_user > 0) {
2004  $sql .= " AND fk_user = ".((int) $fk_user);
2005  }
2006  if (empty($conf->global->AGENDA_REMINDER_EMAIL)) $sql .= " AND typeremind != 'email'";
2007  if (empty($conf->global->AGENDA_REMINDER_BROWSER)) $sql .= " AND typeremind != 'browser'";
2008 
2009  $sql .= $this->db->order("dateremind", "ASC");
2010  $resql = $this->db->query($sql);
2011 
2012  if ($resql) {
2013  while ($obj = $this->db->fetch_object($resql)) {
2014  $tmpactioncommreminder = new ActionCommReminder($this->db);
2015  $tmpactioncommreminder->id = $obj->id;
2016  $tmpactioncommreminder->typeremind = $obj->typeremind;
2017  $tmpactioncommreminder->dateremind = $obj->dateremind;
2018  $tmpactioncommreminder->offsetvalue = $obj->offsetvalue;
2019  $tmpactioncommreminder->offsetunit = $obj->offsetunit;
2020  $tmpactioncommreminder->status = $obj->status;
2021  $tmpactioncommreminder->fk_user = $obj->fk_user;
2022 
2023  $this->reminders[$obj->id] = $tmpactioncommreminder;
2024  }
2025  } else {
2026  $this->error = $this->db->lasterror();
2027  $error++;
2028  }
2029 
2030  return count($this->reminders);
2031  }
2032 
2033 
2040  public function sendEmailsReminder()
2041  {
2042  global $conf, $langs, $user;
2043 
2044  $error = 0;
2045  $this->output = '';
2046  $this->error = '';
2047  $nbMailSend = 0;
2048  $errorsMsg = array();
2049 
2050  if (empty($conf->agenda->enabled)) // Should not happen. If module disabled, cron job should not be visible.
2051  {
2052  $langs->load("agenda");
2053  $this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Agenda"));
2054  return 0;
2055  }
2056  if (empty($conf->global->AGENDA_REMINDER_EMAIL))
2057  {
2058  $langs->load("agenda");
2059  $this->output = $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Agenda"));
2060  return 0;
2061  }
2062 
2063  $now = dol_now();
2064  $actionCommReminder = new ActionCommReminder($this->db);
2065 
2066  dol_syslog(__METHOD__, LOG_DEBUG);
2067 
2068  $this->db->begin();
2069 
2070  //Select all action comm reminder
2071  $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
2072  $sql .= " WHERE typeremind = 'email' AND status = 0";
2073  $sql .= " AND dateremind <= '".$this->db->idate(dol_now())."'";
2074  $sql .= $this->db->order("dateremind", "ASC");
2075  $resql = $this->db->query($sql);
2076 
2077  if ($resql) {
2078  $formmail = new FormMail($this->db);
2079 
2080  while ($obj = $this->db->fetch_object($resql)) {
2081  $res = $actionCommReminder->fetch($obj->id);
2082  if ($res < 0) {
2083  $error++;
2084  $errorsMsg[] = "Failed to load invoice ActionComm Reminder";
2085  }
2086 
2087  if (!$error) {
2088  //Select email template
2089  $arraymessage = $formmail->getEMailTemplate($this->db, 'actioncomm_send', $user, $langs, (!empty($actionCommReminder->fk_email_template)) ? $actionCommReminder->fk_email_template : -1, 1);
2090 
2091  // Load event
2092  $res = $this->fetch($actionCommReminder->fk_actioncomm);
2093  if ($res > 0) {
2094  // PREPARE EMAIL
2095  $errormesg = '';
2096 
2097  // Make substitution in email content
2098  $substitutionarray = getCommonSubstitutionArray($langs, 0, '', $this);
2099 
2100  complete_substitutions_array($substitutionarray, $langs, $this);
2101 
2102  // Content
2103  $sendContent = make_substitutions($langs->trans($arraymessage->content), $substitutionarray);
2104 
2105  //Topic
2106  $sendTopic = (!empty($arraymessage->topic)) ? $arraymessage->topic : html_entity_decode($langs->trans('EventReminder'));
2107 
2108  // Recipient
2109  $recipient = new User($this->db);
2110  $res = $recipient->fetch($actionCommReminder->fk_user);
2111  if ($res > 0) {
2112  if (!empty($recipient->email)) {
2113  $to = $recipient->email;
2114  } else {
2115  $errormesg = "Failed to send remind to user id=".$actionCommReminder->fk_user.". No email defined for user.";
2116  $error++;
2117  }
2118  } else {
2119  $errormesg = "Failed to load recipient with user id=".$actionCommReminder->fk_user;
2120  $error++;
2121  }
2122 
2123  // Sender
2124  $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
2125  if (empty($from)) {
2126  $errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
2127  $error++;
2128  }
2129 
2130  if (!$error) {
2131  // Errors Recipient
2132  $errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
2133 
2134  // Mail Creation
2135  $cMailFile = new CMailFile($sendTopic, $to, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', '', '', '', '');
2136 
2137  // Sending Mail
2138  if ($cMailFile->sendfile()) {
2139  $nbMailSend++;
2140  } else {
2141  $errormesg = $cMailFile->error.' : '.$to;
2142  $error++;
2143  }
2144  }
2145 
2146  if (!$error) {
2147  $actionCommReminder->status = $actionCommReminder::STATUS_DONE;
2148 
2149  $res = $actionCommReminder->update($user);
2150  if ($res < 0) {
2151  $errorsMsg[] = "Failed to update status to done of ActionComm Reminder";
2152  $error++;
2153  break; // This is to avoid to have this error on all the selected email. If we fails here for one record, it may fails for others. We must solve first.
2154  }
2155  } else {
2156  $actionCommReminder->status = $actionCommReminder::STATUS_ERROR;
2157  $actionCommReminder->lasterror = dol_trunc($errormesg, 128, 'right', 'UTF-8', 1);
2158 
2159  $res = $actionCommReminder->update($user);
2160  if ($res < 0) {
2161  $errorsMsg[] = "Failed to update status to error of ActionComm Reminder";
2162  $error++;
2163  break; // This is to avoid to have this error on all the selected email. If we fails here for one record, it may fails for others. We must solve first.
2164  } else {
2165  $errorsMsg[] = $errormesg;
2166  }
2167  }
2168  } else {
2169  $errorsMsg[] = 'Failed to fetch record actioncomm with ID = '.$actionCommReminder->fk_actioncomm;
2170  $error++;
2171  }
2172  }
2173  }
2174  } else {
2175  $error++;
2176  }
2177 
2178  if (!$error) {
2179  // Delete also very old past events (we do not keep more than 1 month record in past)
2180  $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
2181  $sql .= " WHERE dateremind < '".$this->db->idate($now - (3600 * 24 * 32))."'";
2182  $sql .= " AND status = ".$actionCommReminder::STATUS_DONE;
2183  $resql = $this->db->query($sql);
2184 
2185  if (!$resql) {
2186  $errorsMsg[] = 'Failed to delete old reminders';
2187  //$error++; // If this fails, we must not rollback other SQL requests already done. Never mind.
2188  }
2189  }
2190 
2191  if (!$error) {
2192  $this->output = 'Nb of emails sent : '.$nbMailSend;
2193  $this->db->commit();
2194  return 0;
2195  } else {
2196  $this->db->commit(); // We commit also on error, to have the error message recorded.
2197  $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg)) ? join(', ', $errorsMsg) : $error;
2198  return $error;
2199  }
2200  }
2201 
2209  public function updatePercent($id, $percent)
2210  {
2211  $this->db->begin();
2212 
2213  $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm ";
2214  $sql .= " SET percent = ".(int) $percent;
2215  $sql .= " WHERE id=".$id;
2216 
2217  if ($this->db->query($sql))
2218  {
2219  $this->db->commit();
2220  return 1;
2221  } else {
2222  $this->db->rollback();
2223  $this->error = $this->db->lasterror();
2224  return -1;
2225  }
2226  }
2227 }
Class to manage different types of events.
Classe permettant la generation du formulaire html d&#39;envoi de mail unitaire Usage: $formail = new For...
yn($yesno, $case=1, $color=0)
Return yes or no in current language.
Class for ActionCommReminder.
if(!empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'] country if(!empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'] typent code
Definition: list.php:566
loadReminders($type= '', $fk_user=0, $onlypast=true)
Load event reminder of events.
Class to manage agenda events (actions)
updatePercent($id, $percent)
Udpate the percent value of a event with the given id.
LibStatut($percent, $mode, $hidenastatus=0, $datestart= '')
Return label of action status.
const EVENT_FINISHED
Typical value for a event that is in a finished state.
dol_now($mode= 'auto')
Return date for now.
create(User $user, $notrigger=0)
Add an action/event into database.
fetchResources()
Initialize $this-&gt;userassigned &amp; this-&gt;socpeopleassigned array with list of id of user and contact as...
Class to manage Dolibarr users.
Definition: user.class.php:44
Class to manage Dolibarr database access.
setCategories($categories)
Sets object to supplied categories.
build_exportfile($format, $type, $cachedelay, $filename, $filters, $exportholiday=0)
Export events from database into a cal file.
info($id)
Charge les informations d&#39;ordre info dans l&#39;objet facture.
load_board($user, $load_state_board=0)
Load indicators for dashboard (this-&gt;nbtodo and this-&gt;nbtodolate)
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition: date.lib.php:481
dol_stringtotime($string, $gm=1)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition: date.lib.php:319
createFromClone(User $fuser, $socid)
Load an object from its id and create a new one in database.
build_calfile($format, $title, $desc, $events_array, $outputfile)
Build a file from an array of events All input params and data must be encoded in $conf-&gt;charset_outp...
Definition: xcal.lib.php:35
getNomUrl($withpicto=0, $maxlength=0, $classname= '', $option= '', $overwritepicto=0, $notooltip=0, $save_lastsearch_value=-1)
Return URL of event Use $this-&gt;id, $this-&gt;type_code, $this-&gt;label and $this-&gt;type_label.
$conf db
API class for accounts.
Definition: inc.php:54
__construct(DoliDB $db)
Constructor.
sendEmailsReminder()
Send reminders by emails CAN BE A CRON TASK.
dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=1)
Move a file into another name.
Definition: files.lib.php:817
insertExtraFields($trigger= '', $userused=null)
Add/Update all extra fields values for the current object.
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null)
Return array of possible common substitutions.
initAsSpecimen()
Initialise an instance with random values.
const EVENT_IN_PROGRESS
Typical value for a event that is in a progress state.
Class to manage categories.
update($user, $notrigger=0)
Update action into database If percentage = 100, on met a jour date 100%.
build_rssfile($format, $title, $desc, $events_array, $outputfile, $filter= '', $url= '', $langcode= '')
Build a file from an array of events.
Definition: xcal.lib.php:336
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,$sendto,$replyto,$message,$filepath,$mimetype,$filename,$cc,$ccc,$deliveryreceipt,$msgishtml,$errors_to,$css,$trackid,$moreinheader,$sendcontext,$replyto); $mailfile-&gt;sendfile();.
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
img_picto($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt= '', $morecss= '', $marginleftonlyshort=2)
Show picto whatever it&#39;s its name (generic function)
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
const EVENT_TODO
Typical value for a event that is in a todo state.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1)
Remove a file or several files with a mask.
Definition: files.lib.php:1144
img_object($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
deleteExtraFields()
Delete all extra fields values for the current object.
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this-&gt;array_options This method is in most cases call...
hasDelay()
Is the action delayed?
print $_SERVER["PHP_SELF"]
Edit parameters.
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition: date.lib.php:498
call_trigger($triggerName, $user)
Call trigger based on this instance.
dol_filemtime($pathoffile)
Return time of a file.
Definition: files.lib.php:567
static getActions($db, $socid=0, $fk_element=0, $elementtype= '', $filter= '', $sortfield= 'a.datep', $sortorder= 'DESC', $limit=0)
Load all objects with filters.
dol_htmlcleanlastbr($stringtodecode)
This function remove all ending and br at end.
if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->don->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1232
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
fetch($id, $ref= '', $ref_ext= '', $email_msgid= '')
Load object from database.
dol_trunc($string, $size=40, $trunc= 'right', $stringencoding= 'UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding &#39;...&#39; if string larger than length.
dolGetStatus($statusLabel= '', $statusLabelShort= '', $html= '', $statusType= 'status0', $displayMode=0, $url= '', $params=array())
Output the badge of a status.
make_substitutions($text, $substitutionarray, $outputlangs=null)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=&gt;newva...
getLibStatut($mode, $hidenastatus=0)
Return label of status.
if(!defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN'
Draft customers invoices.
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition: repair.php:105
Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
if(!empty($search_group)) natural_search(array("g.nom"g note
Definition: list.php:122
dol_mkdir($dir, $dataroot= '', $newmask=null)
Creation of a directory (this can create recursive subdir)
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the &quot;subst...
static replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
dol_textishtml($msg, $option=0)
Return if a text is a html content.
fetch_userassigned($override=true)
Initialize this-&gt;userassigned array with list of id of user assigned to event.