dolibarr 25.0.0-alpha
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-2026 Frédéric France <frederic.france@free.fr>
9 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
10 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 3 of the License, or
15 * (at your option) any later version.
16 *
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <https://www.gnu.org/licenses/>.
24 */
25
31require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php';
32require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
33require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
34require_once DOL_DOCUMENT_ROOT.'/core/class/CSMSFile.class.php';
35require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncommreminder.class.php';
36
37
42{
46 public $element = 'action';
47
52 public $TRIGGER_PREFIX = 'ACTION';
53
57 public $table_element = 'actioncomm';
58
62 public $table_rowid = 'id';
63
67 public $picto = 'action';
68
74 public $restrictiononfksoc = 2;
75
79 public $id;
80
84 public $ref;
85
90 public $type_id;
91
96 public $type;
97
102 public $type_code;
103
107 public $type_label;
108
112 public $type_color;
113
117 public $type_picto;
118
123 public $code;
124
128 public $label;
129
133 public $datec;
134
138 public $duree;
139
143 public $datem;
144
150 public $author;
151
157 public $usermod;
158
162 public $authorid;
163
167 public $usermodid;
168
172 public $datep;
173
177 public $datef;
178
182 public $date_start_in_calendar;
183
187 public $date_end_in_calendar;
188
192 public $datep2;
193
198 public $durationp = -1;
199
203 public $fulldayevent = 0;
204
208 public $ponctuel;
209
213 public $percentage;
214
218 public $location;
219
223 public $max_participants;
224
228 public $transparency;
229
233 public $priority;
234
238 public $userassigned = array();
239
243 public $userownerid;
244
249 public $uid;
250
254 public $socpeopleassigned = array();
255
259 public $otherassigned = array();
260
264 public $reminders = array();
265
269 public $socid;
270
274 public $contact_id;
275
279 public $fk_task;
280
286 public $societe;
287
293 public $contact;
294
295 // Properties for links to other objects
300 public $fk_element; // Id of record
301
305 public $elementid;
306
310 public $elementtype;
311
315 public $fk_bookcal_calendar;
316
320 public $icalname;
321
325 public $icalcolor;
326
330 public $icaldetails = array();
331
335 public $extraparams;
336
340 public $actions = array();
341
345 public $email_msgid;
346
350 public $email_from;
351
355 public $email_reply_to;
356
360 public $email_sender;
361
365 public $email_to;
366
370 public $email_tocc;
374 public $email_tobcc;
375
379 public $email_subject;
380
384 public $errors_to;
385
389 public $num_vote;
390
394 public $event_paid;
395
399 public $status;
400
404 public $ip;
405
406 /*
407 * Properties to manage the recurring events
408 */
410 public $recurid;
412 public $recurrule;
414 public $recurdateend;
415
417 public $calling_duration;
418
419
423 const EVENT_TODO = 0;
424
429
433 const EVENT_FINISHED = 100;
434
435
436 // BEGIN MODULEBUILDER PROPERTIES
441 public $fields = array(
442 "id" => array("type" => "integer", "label" => "Ref", "enabled" => "1", 'position' => 10, 'notnull' => 1, "visible" => "1",),
443 "ref" => array("type" => "varchar(30)", "label" => "Ref", "enabled" => "1", 'position' => 15, 'notnull' => 1, "visible" => "0", "csslist" => "tdoverflowmax150", "showoncombobox" => "1",),
444 "ref_ext" => array("type" => "varchar(255)", "label" => "Refext", "enabled" => "1", 'position' => 20, 'notnull' => 0, "visible" => "0",),
445 "uid" => array("type" => "varchar(36)", "label" => "Uid", "enabled" => "1", 'position' => 21, 'notnull' => 0, "visible" => "0",),
446 "datep" => array("type" => "datetime", "label" => "DateStart", "enabled" => "1", 'position' => 25, 'notnull' => 0, "visible" => "1",),
447 "datep2" => array("type" => "datetime", "label" => "DateEnd", "enabled" => "1", 'position' => 26, 'notnull' => 0, "visible" => "-1",),
448 "fk_action" => array("type" => "integer", "label" => "Fkaction", "enabled" => "1", 'position' => 40, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
449 "code" => array("type" => "varchar(50)", "label" => "Code", "enabled" => "1", 'position' => 45, 'notnull' => 0, "visible" => "0", "showoncombobox" => "1",),
450 "label" => array("type" => "varchar(255)", "label" => "Title", "enabled" => "1", 'position' => 50, 'notnull' => 1, "visible" => "1", "alwayseditable" => "1", "css" => "minwidth300", "cssview" => "wordbreak", "csslist" => "tdoverflowmax150",),
451 "note" => array("type" => "mediumtext", "label" => "Description", "enabled" => "1", 'position' => 51, 'notnull' => 0, "visible" => "-1",),
452 "fk_project" => array("type" => "integer", "label" => "Project", "picto" => "project", "enabled" => "1", 'position' => 75, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
453 "fk_soc" => array("type" => "integer", "label" => "ThirdParty", "picto" => "company", "enabled" => "1", 'position' => 80, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
454 "fk_contact" => array("type" => "integer", "label" => "Contact", "picto" => "contact", "enabled" => "1", 'position' => 85, 'notnull' => 0, "visible" => "-1", "css" => "maxwidth500 widthcentpercentminusxx",),
455 "fk_parent" => array("type" => "integer", "label" => "Parent", "enabled" => "1", 'position' => 90, 'notnull' => 1, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
456 "fk_user_action" => array("type" => "integer", "label" => "Fkuseraction", "picto" => "user", "enabled" => "1", 'position' => 95, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
457 "transparency" => array("type" => "integer", "label" => "Transparency", "enabled" => "1", 'position' => 100, 'notnull' => 0, "visible" => "0",),
458 "fk_user_done" => array("type" => "integer", "label" => "Fkuserdone", "picto" => "user", "enabled" => "1", 'position' => 105, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
459 "priority" => array("type" => "smallint(6)", "label" => "Priority", "enabled" => "1", 'position' => 110, 'notnull' => 0, "visible" => "0",),
460 "fulldayevent" => array("type" => "smallint(6)", "label" => "Fulldayevent", "enabled" => "1", 'position' => 115, 'notnull' => 1, "visible" => "0",),
461 "location" => array("type" => "varchar(128)", "label" => "Location", "enabled" => "1", 'position' => 125, 'notnull' => 0, "visible" => "0",),
462 "max_participants" => array("type" => "integer", "label" => "MaxNbOfAttendees", "enabled" => "1", 'position' => 126, 'notnull' => 0, "visible" => "0",),
463 "durationp" => array("type" => "double", "label" => "Durationp", "enabled" => "1", 'position' => 130, 'notnull' => 0, "visible" => "0",),
464 "durationa" => array("type" => "double", "label" => "Durationa", "enabled" => "1", 'position' => 135, 'notnull' => 0, "visible" => "0",),
465 "fk_element" => array("type" => "integer", "label" => "LinkedObject", "enabled" => "getDolGlobalString('AGENDA_SHOW_LINKED_OBJECT')", 'position' => 145, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
466 "elementtype" => array("type" => "varchar(255)", "label" => "Elementtype", "enabled" => "1", 'position' => 150, 'notnull' => 0, "visible" => "0",),
467 "email_msgid" => array("type" => "varchar(256)", "label" => "Emailmsgid", "enabled" => "1", 'position' => 155, 'notnull' => 0, "visible" => "0",),
468 "email_subject" => array("type" => "varchar(256)", "label" => "Emailsubject", "enabled" => "1", 'position' => 160, 'notnull' => 0, "visible" => "0",),
469 "email_from" => array("type" => "varchar(256)", "label" => "Emailfrom", "enabled" => "1", 'position' => 165, 'notnull' => 0, "visible" => "0",),
470 "email_sender" => array("type" => "varchar(256)", "label" => "Emailsender", "enabled" => "1", 'position' => 170, 'notnull' => 0, "visible" => "0",),
471 "email_to" => array("type" => "varchar(256)", "label" => "Emailto", "enabled" => "1", 'position' => 175, 'notnull' => 0, "visible" => "0",),
472 "email_tocc" => array("type" => "varchar(256)", "label" => "Emailtocc", "enabled" => "1", 'position' => 180, 'notnull' => 0, "visible" => "0",),
473 "email_tobcc" => array("type" => "varchar(256)", "label" => "Emailtobcc", "enabled" => "1", 'position' => 185, 'notnull' => 0, "visible" => "0",),
474 "errors_to" => array("type" => "varchar(256)", "label" => "Errorsto", "enabled" => "1", 'position' => 190, 'notnull' => 0, "visible" => "0",),
475 "recurid" => array("type" => "varchar(128)", "label" => "Recurid", "enabled" => "1", 'position' => 195, 'notnull' => 0, "visible" => "0",),
476 "recurrule" => array("type" => "varchar(128)", "label" => "Recurrule", "enabled" => "1", 'position' => 200, 'notnull' => 0, "visible" => "0",),
477 "recurdateend" => array("type" => "datetime", "label" => "Recurdateend", "enabled" => "1", 'position' => 205, 'notnull' => 0, "visible" => "0",),
478 "import_key" => array("type" => "varchar(14)", "label" => "ImportId", "enabled" => "1", 'position' => 900, 'notnull' => 0, "visible" => "-1",),
479 "extraparams" => array("type" => "varchar(255)", "label" => "Extraparams", "enabled" => "1", 'position' => 215, 'notnull' => 0, "visible" => "0",),
480 "calling_duration" => array("type" => "integer", "label" => "Callingduration", "enabled" => "1", 'position' => 220, 'notnull' => 0, "visible" => "0",),
481 "visibility" => array("type" => "varchar(12)", "label" => "Visibility", "enabled" => "1", 'position' => 225, 'notnull' => 0, "visible" => "0",),
482 "reply_to" => array("type" => "varchar(255)", "label" => "Replyto", "enabled" => "1", 'position' => 230, 'notnull' => 0, "visible" => "0",),
483 "num_vote" => array("type" => "integer", "label" => "Numvote", "enabled" => "1", 'position' => 235, 'notnull' => 0, "visible" => "0",),
484 "event_paid" => array("type" => "smallint(6)", "label" => "Eventpaid", "enabled" => "1", 'position' => 240, 'notnull' => 1, "visible" => "0",),
485 "status" => array("type" => "smallint(6)", "label" => "Status", "enabled" => "1", 'position' => 500, 'notnull' => 1, "visible" => "0",),
486 "ip" => array("type" => "varchar(250)", "label" => "Ip", "enabled" => "1", 'position' => 250, 'notnull' => 0, "visible" => "0",),
487 "fk_bookcal_calendar" => array("type" => "integer", "label" => "Fkbookcalcalendar", "enabled" => "1", 'position' => 255, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
488 "fk_task" => array("type" => "integer", "label" => "Task", "picto" => "task", "enabled" => "1", 'position' => 260, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
489 "fk_user_author" => array("type" => "integer", "label" => "UserCreation", "picto" => "user", "enabled" => "1", 'position' => 505, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
490 "fk_user_mod" => array("type" => "integer", "label" => "UserModification", "picto" => "user", "enabled" => "1", 'position' => 506, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
491 "datec" => array("type" => "datetime", "label" => "DateCreation", "enabled" => "1", 'position' => 510, 'notnull' => 0, "visible" => "-1",),
492 "tms" => array("type" => "timestamp", "label" => "DateModification", "enabled" => "1", 'position' => 520, 'notnull' => 1, "visible" => "-1",),
493 "percent" => array("type" => "smallint(6)", "label" => "Status", "enabled" => "1", 'position' => 1000, 'notnull' => 1, "visible" => "1",), // status
494 );
495 // END MODULEBUILDER PROPERTIES
496
497
503 public function __construct(DoliDB $db)
504 {
505 $this->db = $db;
506
507 $this->ismultientitymanaged = 1;
508 }
509
515 protected static function generateUid()
516 {
517 $hex = dolGetRandomBytes(32); // 16 random bytes as 32 hex chars
518 $hex[12] = '4'; // version 4
519 $hex[16] = dechex((hexdec($hex[16]) & 0x3) | 0x8); // variant 10xx
520
521 return substr($hex, 0, 8).'-'.substr($hex, 8, 4).'-'.substr($hex, 12, 4).'-'.substr($hex, 16, 4).'-'.substr($hex, 20, 12);
522 }
523
534 protected function backfillUid()
535 {
536 $newuid = self::generateUid();
537
538 $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm SET uid = '".$this->db->escape($newuid)."', tms = tms";
539 $sql .= " WHERE id = ".((int) $this->id)." AND uid IS NULL";
540 $resql = $this->db->query($sql);
541 if ($resql && $this->db->affected_rows($resql) > 0) {
542 return $newuid;
543 }
544
545 // Another request backfilled it concurrently: read back whatever it set instead of
546 // leaving two different uids in play for the same event.
547 $sql = "SELECT uid FROM ".MAIN_DB_PREFIX."actioncomm WHERE id = ".((int) $this->id);
548 $resql = $this->db->query($sql);
549 if ($resql && ($obj = $this->db->fetch_object($resql)) && !empty($obj->uid)) {
550 return $obj->uid;
551 }
552
553 return $newuid;
554 }
555
564 public function create(User $user, $notrigger = 0)
565 {
566 global $langs, $conf;
567
568 $error = 0;
569 $now = dol_now();
570
571 // Check parameters
572 if (!isset($this->userownerid) || (string) $this->userownerid === '') { // $this->userownerid may be 0 (anonymous event) or > 0
573 dol_syslog("You tried to create an event but mandatory property userownerid was empty (you can define it to 0 for anonymous event)", LOG_WARNING);
574 $this->errors[] = 'ErrorActionCommPropertyUserowneridNotDefined';
575 return -1;
576 }
577
578 // Clean parameters
579 $this->label = dol_trunc(sanitizeVal($this->label, 'alphawithlgt'), 128);
580 $this->location = (!empty($this->location) ? dol_trunc(trim($this->location), 128) : "");
581 $this->note_private = dol_htmlcleanlastbr(trim(empty($this->note_private) ? $this->note : $this->note_private));
582 if (empty($this->percentage)) {
583 $this->percentage = 0;
584 }
585 if (empty($this->priority) || !is_numeric($this->priority)) {
586 $this->priority = 0;
587 }
588 if (empty($this->fulldayevent)) {
589 $this->fulldayevent = 0;
590 }
591 if (empty($this->transparency)) {
592 $this->transparency = 0;
593 }
594 if ($this->percentage > 100) {
595 $this->percentage = 100;
596 }
597 if (empty($this->datep) && $this->datep != '0') { // We should not insert event in calendar without a start date
598 $this->datep = $now;
599 }
600 if (!empty($this->datep) && !empty($this->datef)) {
601 $this->durationp = ($this->datef - $this->datep); // deprecated
602 }
603 if (!empty($this->datep) && !empty($this->datef) && $this->datep > $this->datef) {
604 $this->datef = $this->datep;
605 }
606 if (!isset($this->fk_project) || $this->fk_project < 0) {
607 $this->fk_project = 0;
608 }
609 if (!isset($this->fk_task) || $this->fk_task < 0) {
610 $this->fk_task = 0;
611 }
612 // For backward compatibility
613 if ($this->elementtype == 'facture') {
614 $this->elementtype = 'invoice';
615 }
616 if ($this->elementtype == 'commande') {
617 $this->elementtype = 'order';
618 }
619 if ($this->elementtype == 'contrat') {
620 $this->elementtype = 'contract';
621 }
622 if (empty($this->fk_element) && !empty($this->elementid)) {
623 $this->fk_element = $this->elementid;
624 }
625 if (empty($this->elementid) && !empty($this->fk_element)) {
626 $this->elementid = $this->fk_element;
627 }
628
629 if (!is_array($this->userassigned) && !empty($this->userassigned)) { // For backward compatibility when userassigned was an int instead of an array
630 $tmpid = (int) $this->userassigned;
631 $this->userassigned = array();
632 $this->userassigned[$tmpid] = array('id' => $tmpid, 'transparency' => $this->transparency);
633 }
634
635 $userownerid = $this->userownerid;
636
637 // Be sure assigned user is defined as an array of array('id'=>,'mandatory'=>,...).
638 if (empty($this->userassigned) || count($this->userassigned) == 0 || !is_array($this->userassigned)) {
639 $this->userassigned = array($userownerid => array('id' => $userownerid, 'transparency' => $this->transparency));
640 }
641
642 if (!$this->type_id || !$this->type_code) {
643 $key = empty($this->type_id) ? $this->type_code : $this->type_id;
644
645 // Get id from code
646 $cactioncomm = new CActionComm($this->db);
647 $result = $cactioncomm->fetch($key);
648
649 if ($result > 0) {
650 $this->type_id = $cactioncomm->id;
651 $this->type_code = $cactioncomm->code;
652 } elseif ($result == 0) {
653 $this->error = $langs->trans('ErrorActionCommBadType', $this->type_id, $this->type_code);
654 return -1;
655 } else {
656 $this->error = $cactioncomm->error;
657 return -1;
658 }
659 }
660 $code = empty($this->code) ? $this->type_code : $this->code;
661
662 // Check parameters
663 if (!$this->type_id) {
664 $this->error = "ErrorWrongParameters";
665 return -1;
666 }
667
668 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
669 $extraparams = dol_trunc($extraparams, 250);
670
671 if (empty($this->uid)) {
672 $this->uid = self::generateUid();
673 }
674
675 $this->db->begin();
676
677 $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm";
678 $sql .= "(ref,";
679 $sql .= "datec,";
680 $sql .= "datep,";
681 $sql .= "datep2,";
682 $sql .= "durationp,"; // deprecated
683 $sql .= "fk_action,";
684 $sql .= "code,";
685 $sql .= "ref_ext,";
686 $sql .= "uid,";
687 $sql .= "fk_soc,";
688 $sql .= "fk_project,";
689 $sql .= "note,";
690 $sql .= "fk_contact,";
691 $sql .= "fk_user_author,";
692 $sql .= "fk_user_action,";
693 $sql .= "fk_task,";
694 $sql .= "label,percent,priority,fulldayevent,location,max_participants,";
695 $sql .= "transparency,";
696 $sql .= "fk_element,";
697 $sql .= "elementtype,";
698 $sql .= "fk_bookcal_calendar,";
699 $sql .= "entity,";
700 $sql .= "extraparams,";
701 // Fields emails
702 $sql .= "email_msgid,";
703 $sql .= "email_from,";
704 $sql .= "email_sender,";
705 $sql .= "email_to,";
706 $sql .= "email_tocc,";
707 $sql .= "email_tobcc,";
708 $sql .= "email_subject,";
709 $sql .= "errors_to,";
710 $sql .= "recurid,";
711 $sql .= "recurrule,";
712 $sql .= "recurdateend,";
713 $sql .= "num_vote,";
714 $sql .= "event_paid,";
715 $sql .= "status,";
716 $sql .= "ip";
717 $sql .= ") VALUES (";
718 $sql .= "'(PROV)', ";
719 $sql .= "'".$this->db->idate($now)."', "; // date creation
720 $sql .= "'".$this->db->idate($this->datep)."', "; // date start event
721 $sql .= (strval($this->datef) != '' ? "'".$this->db->idate($this->datef)."'" : "null").", ";
722 $sql .= ((isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '') ? "'".$this->db->escape((string) $this->durationp)."'" : "null").", "; // deprecated
723 $sql .= (isset($this->type_id) ? ((int) $this->type_id) : "null").",";
724 $sql .= ($code ? ("'".$this->db->escape($code)."'") : "null").", ";
725 $sql .= (!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").", ";
726 $sql .= "'".$this->db->escape($this->uid)."', ";
727 $sql .= ((isset($this->socid) && $this->socid > 0) ? ((int) $this->socid) : "null").", ";
728 $sql .= ((isset($this->fk_project) && $this->fk_project > 0) ? ((int) $this->fk_project) : "null").", ";
729 $sql .= " '".$this->db->escape($this->note_private)."', ";
730 $sql .= ((isset($this->contact_id) && $this->contact_id > 0) ? ((int) $this->contact_id) : "null").", "; // deprecated, use ->socpeopleassigned
731 $sql .= (isset($user->id) && $user->id > 0 ? ((int) $user->id) : "null").", ";
732 $sql .= ($userownerid > 0 ? ((int) $userownerid) : "null").", ";
733 $sql .= (!empty($this->fk_task) ? ((int) $this->fk_task) : "null").", ";
734 $sql .= "'".$this->db->escape($this->label)."', ";
735 $sql .= "'".$this->db->escape((string) $this->percentage)."', ";
736 $sql .= "'".$this->db->escape((string) $this->priority)."', ";
737 $sql .= "'".$this->db->escape((string) $this->fulldayevent)."', ";
738 $sql .= "'".$this->db->escape($this->location)."', ";
739 $sql .= (isset($this->max_participants) && $this->max_participants > 0 ? ((int) $this->max_participants) : "null").", ";
740 $sql .= "'".$this->db->escape((string) $this->transparency)."', ";
741 $sql .= (!empty($this->elementid) ? ((int) $this->elementid) : "null").", ";
742 $sql .= (!empty($this->elementtype) ? "'".$this->db->escape($this->elementtype)."'" : "null").", ";
743 $sql .= (!empty($this->fk_bookcal_calendar) ? "'".$this->db->escape((string) $this->fk_bookcal_calendar)."'" : "null").", ";
744 $sql .= ((int) $conf->entity).",";
745 $sql .= (!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null").", ";
746 // Fields emails
747 $sql .= (!empty($this->email_msgid) ? "'".$this->db->escape($this->email_msgid)."'" : "null").", ";
748 $sql .= (!empty($this->email_from) ? "'".$this->db->escape($this->email_from)."'" : "null").", ";
749 $sql .= (!empty($this->email_sender) ? "'".$this->db->escape($this->email_sender)."'" : "null").", ";
750 $sql .= (!empty($this->email_to) ? "'".$this->db->escape($this->email_to)."'" : "null").", ";
751 $sql .= (!empty($this->email_tocc) ? "'".$this->db->escape($this->email_tocc)."'" : "null").", ";
752 $sql .= (!empty($this->email_tobcc) ? "'".$this->db->escape($this->email_tobcc)."'" : "null").", ";
753 $sql .= (!empty($this->email_subject) ? "'".$this->db->escape($this->email_subject)."'" : "null").", ";
754 $sql .= (!empty($this->errors_to) ? "'".$this->db->escape($this->errors_to)."'" : "null").", ";
755 $sql .= (!empty($this->recurid) ? "'".$this->db->escape($this->recurid)."'" : "null").", ";
756 $sql .= (!empty($this->recurrule) ? "'".$this->db->escape($this->recurrule)."'" : "null").", ";
757 $sql .= (!empty($this->recurdateend) ? "'".$this->db->idate($this->recurdateend)."'" : "null").", ";
758 $sql .= (!empty($this->num_vote) ? (int) $this->num_vote : "null").", ";
759 $sql .= (!empty($this->event_paid) ? (int) $this->event_paid : 0).", ";
760 $sql .= (!empty($this->status) ? (int) $this->status : "0").", ";
761 $sql .= (!empty($this->ip) ? "'".$this->db->escape($this->ip)."'" : "null");
762 $sql .= ")";
763
764 dol_syslog(get_class($this)."::add", LOG_DEBUG);
765 $resql = $this->db->query($sql);
766 if ($resql) {
767 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."actioncomm", "id");
768 $this->ref = (string) $this->id;
769 $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm SET ref='".$this->db->escape($this->ref)."' WHERE id=".((int) $this->id);
770 $resql = $this->db->query($sql);
771 if (!$resql) {
772 $error++;
773 dol_syslog('Error to process ref: '.$this->db->lasterror(), LOG_ERR);
774 $this->errors[] = $this->db->lasterror();
775 }
776 // Now insert assigned users
777 if (!$error) {
778 //dol_syslog(var_export($this->userassigned, true));
779 $already_inserted = array();
780 foreach ($this->userassigned as $key => $val) {
781 // Common value with new behavior is to have $val = array('id'=>iduser, 'transparency'=>0|1) and $this->userassigned is an array of iduser => $val.
782 if (!is_array($val)) { // For backward compatibility when $val='id'.
783 $val = array('id' => $val);
784 }
785
786 if ($val['id'] > 0) {
787 if (!empty($already_inserted[$val['id']])) {
788 continue;
789 }
790
791 $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
792 $sql .= " VALUES(".((int) $this->id).", 'user', ".((int) $val['id']).", ".(empty($val['mandatory']) ? '0' : ((int) $val['mandatory'])).", ".(empty($val['transparency']) ? '0' : ((int) $val['transparency'])).", ".(empty($val['answer_status']) ? '0' : ((int) $val['answer_status'])).")";
793
794 $resql = $this->db->query($sql);
795 if (!$resql) {
796 $error++;
797 dol_syslog('Error to process userassigned: ' . $this->db->lasterror(), LOG_ERR);
798 $this->errors[] = $this->db->lasterror();
799 } else {
800 $already_inserted[$val['id']] = true;
801 }
802 //var_dump($sql);exit;
803 }
804 }
805 }
806
807 if (!$error) {
808 if (!empty($this->socpeopleassigned)) {
809 $already_inserted = array();
810 foreach ($this->socpeopleassigned as $id => $val) {
811 // Common value with new behavior is to have $this->socpeopleassigned an array of idcontact => dummyvalue
812 if (!empty($already_inserted[$id])) {
813 continue;
814 }
815
816 $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
817 $sql .= " VALUES(".((int) $this->id).", 'socpeople', ".((int) $id).", 0, 0, 0)";
818
819 $resql = $this->db->query($sql);
820 if (!$resql) {
821 $error++;
822 dol_syslog('Error to process socpeopleassigned: ' . $this->db->lasterror(), LOG_ERR);
823 $this->errors[] = $this->db->lasterror();
824 } else {
825 $already_inserted[$id] = true;
826 }
827 }
828 }
829 }
830
831 if (!$error) {
832 // Actions on extra fields
833 $result = $this->insertExtraFields();
834 if ($result < 0) {
835 $error++;
836 }
837 }
838
839 if (!$error && !$notrigger) {
840 // Call trigger
841 $result = $this->call_trigger('ACTION_CREATE', $user);
842 if ($result < 0) {
843 $error++;
844 }
845 // End call triggers
846 }
847
848 if (!$error) {
849 $this->db->commit();
850 return $this->id;
851 } else {
852 $this->db->rollback();
853 return -1;
854 }
855 } else {
856 $this->db->rollback();
857 $this->error = $this->db->lasterror();
858 return -1;
859 }
860 }
861
869 public function createFromClone(User $fuser, $socid)
870 {
871 global $hookmanager;
872
873 $error = 0;
874
875 $this->db->begin();
876
877 // Load source object
878 $objFrom = clone $this;
879
880 // Retrieve all extrafield
881 // fetch optionals attributes and labels
882 $this->fetch_optionals();
883
884 //$this->fetch_userassigned();
885 $this->fetchResources();
886
887 $this->id = 0;
888 $this->recurid = '';
889 $this->recurrule = '';
890 $this->recurdateend = '';
891
892 // Create clone
893 $this->context['createfromclone'] = 'createfromclone';
894 $result = $this->create($fuser);
895 if ($result < 0) {
896 $error++;
897 } else {
898 $resultcat = $this->cloneCategories($objFrom->id, $this->id);
899 if ($resultcat < 0) {
900 $error++;
901 }
902 }
903
904 if (!$error) {
905 // Hook of thirdparty module
906 if (is_object($hookmanager)) {
907 $parameters = array('objFrom' => $objFrom);
908 $action = '';
909 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
910 if ($reshook < 0) {
911 $this->setErrorsFromObject($hookmanager);
912 $error++;
913 }
914 }
915
916 // Call trigger
917 $result = $this->call_trigger('ACTION_CLONE', $fuser);
918 if ($result < 0) {
919 $error++;
920 }
921 // End call triggers
922 }
923
924 unset($this->context['createfromclone']);
925
926 // End
927 if (!$error) {
928 $this->db->commit();
929 return $this->id;
930 } else {
931 $this->db->rollback();
932 return -1;
933 }
934 }
935
946 public function fetch($id, $ref = '', $ref_ext = '', $email_msgid = '', $loadresources = 1)
947 {
948 if (empty($id) && empty($ref) && empty($ref_ext) && empty($email_msgid)) {
949 dol_syslog(get_class($this)."::fetch Bad parameters", LOG_WARNING);
950 return -1;
951 }
952
953 $sql = "SELECT a.id,";
954 $sql .= " a.ref as ref,";
955 $sql .= " a.entity,";
956 $sql .= " a.ref_ext,";
957 $sql .= " a.uid,";
958 $sql .= " a.datep,";
959 $sql .= " a.datep2,";
960 $sql .= " a.durationp,"; // deprecated
961 $sql .= " a.datec,";
962 $sql .= " a.tms as datem,";
963 $sql .= " a.code, a.label, a.note as note_private,";
964 $sql .= " a.fk_soc,";
965 $sql .= " a.fk_project,";
966 $sql .= " a.fk_user_author, a.fk_user_mod,";
967 $sql .= " a.fk_user_action,";
968 $sql .= " a.fk_task,";
969 $sql .= " a.fk_contact, a.percent as percentage,";
970 $sql .= " a.fk_element as elementid, a.elementtype,";
971 $sql .= " a.priority, a.fulldayevent, a.location, a.max_participants, a.transparency,";
972 $sql .= " a.email_msgid, a.email_subject, a.email_from, a.email_sender, a.email_to, a.email_tocc, a.email_tobcc, a.errors_to,";
973 $sql .= " a.recurid, a.recurrule, a.recurdateend,";
974 $sql .= " c.id as type_id, c.type as type_type, c.code as type_code, c.libelle as type_label, c.color as type_color, c.picto as type_picto,";
975 $sql .= " s.nom as socname,";
976 $sql .= " u.firstname, u.lastname as lastname,";
977 $sql .= " num_vote, event_paid, a.status";
978 $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a ";
979 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action=c.id ";
980 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author";
981 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc";
982 $sql .= " WHERE ";
983 if ($ref) {
984 $sql .= " a.ref = '".$this->db->escape($ref)."'";
985 } elseif ($ref_ext) {
986 $sql .= " a.ref_ext = '".$this->db->escape($ref_ext)."'";
987 } elseif ($email_msgid) {
988 $sql .= " a.email_msgid = '".$this->db->escape($email_msgid)."'";
989 } else {
990 $sql .= " a.id = ".((int) $id);
991 }
992
993 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
994 $resql = $this->db->query($sql);
995 if ($resql) {
996 $num = $this->db->num_rows($resql);
997 if ($num) {
998 $obj = $this->db->fetch_object($resql);
999
1000 $this->id = $obj->id;
1001 $this->entity = $obj->entity;
1002 $this->ref = $obj->ref;
1003 $this->ref_ext = $obj->ref_ext;
1004 $this->uid = $obj->uid;
1005 if (empty($this->uid)) {
1006 $this->uid = $this->backfillUid();
1007 }
1008
1009 // Properties of parent table llx_c_actioncomm
1010 $this->type_id = $obj->type_id;
1011 $this->type_code = $obj->type_code;
1012 $this->type_color = $obj->type_color;
1013 $this->type_picto = $obj->type_picto;
1014 $this->type = $obj->type_type;
1015 $this->type_label = $obj->type_label;
1016
1017 $this->code = $obj->code;
1018 $this->label = $obj->label;
1019 $this->datep = $this->db->jdate($obj->datep);
1020 $this->datef = $this->db->jdate($obj->datep2);
1021
1022 $this->datec = $this->db->jdate($obj->datec);
1023 $this->datem = $this->db->jdate($obj->datem);
1024
1025 $this->note = $obj->note_private; // deprecated
1026 $this->note_private = $obj->note_private;
1027 $this->percentage = $obj->percentage;
1028
1029 $this->authorid = $obj->fk_user_author;
1030 $this->usermodid = $obj->fk_user_mod;
1031
1032 if (!is_object($this->author)) {
1033 $this->author = new User($this->db); // To avoid warning
1034 }
1035 $this->author->id = $obj->fk_user_author; // deprecated
1036 $this->author->firstname = $obj->firstname; // deprecated
1037 $this->author->lastname = $obj->lastname; // deprecated
1038 if (!is_object($this->usermod)) {
1039 $this->usermod = new User($this->db); // To avoid warning
1040 }
1041 $this->usermod->id = $obj->fk_user_mod; // deprecated
1042
1043 $this->userownerid = $obj->fk_user_action;
1044 $this->fk_task = $obj->fk_task;
1045 $this->priority = $obj->priority;
1046 $this->fulldayevent = $obj->fulldayevent;
1047 $this->location = $obj->location;
1048 $this->max_participants = $obj->max_participants;
1049 $this->transparency = $obj->transparency;
1050
1051 $this->socid = $obj->fk_soc; // To have fetch_thirdparty method working
1052 if (!empty($obj->socname)) {
1053 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1054 $this->thirdparty = new Societe($this->db);
1055 $this->thirdparty->id = $obj->fk_soc;
1056 $this->thirdparty->name = $obj->socname;
1057 }
1058 $this->contact_id = $obj->fk_contact; // To have fetch_contact method working
1059 $this->fk_project = $obj->fk_project; // To have fetch_projet method working
1060
1061 //$this->societe->id = $obj->fk_soc; // deprecated
1062 //$this->contact->id = $obj->fk_contact; // deprecated
1063
1064 $this->fk_element = $obj->elementid;
1065 $this->elementid = $obj->elementid;
1066 $this->elementtype = $obj->elementtype;
1067
1068 $this->recurid = $obj->recurid;
1069 $this->recurrule = $obj->recurrule;
1070 $this->recurdateend = $this->db->jdate($obj->recurdateend);
1071
1072 $this->num_vote = $obj->num_vote;
1073 $this->event_paid = $obj->event_paid;
1074 $this->status = $obj->status;
1075
1076 //email information
1077 $this->email_msgid = $obj->email_msgid;
1078 $this->email_from = $obj->email_from;
1079 $this->email_sender = $obj->email_sender;
1080 $this->email_to = $obj->email_to;
1081 $this->email_tocc = $obj->email_tocc;
1082 $this->email_tobcc = $obj->email_tobcc;
1083 $this->email_subject = $obj->email_subject;
1084 $this->errors_to = $obj->errors_to;
1085
1086 $this->fetch_optionals();
1087
1088 if ($loadresources) {
1089 $this->fetchResources();
1090 }
1091 }
1092
1093 $this->db->free($resql);
1094 } else {
1095 $this->error = $this->db->lasterror();
1096 return -1;
1097 }
1098
1099 return $num;
1100 }
1101
1107 public function fetchResources()
1108 {
1109 $this->userassigned = array();
1110 $this->socpeopleassigned = array();
1111
1112 $sql = 'SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency';
1113 $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm_resources';
1114 $sql .= ' WHERE fk_actioncomm = '.((int) $this->id);
1115 $sql .= " AND element_type IN ('user', 'socpeople')";
1116 $resql = $this->db->query($sql);
1117 if ($resql) {
1118 // If owner is known, we must but id first into list
1119 if ($this->userownerid > 0) {
1120 $this->userassigned[$this->userownerid] = array('id' => $this->userownerid); // Set first so will be first into list.
1121 }
1122
1123 while ($obj = $this->db->fetch_object($resql)) {
1124 if ($obj->fk_element > 0) {
1125 switch ($obj->element_type) {
1126 case 'user':
1127 $this->userassigned[$obj->fk_element] = array('id' => $obj->fk_element, 'mandatory' => $obj->mandatory, 'answer_status' => $obj->answer_status, 'transparency' => $obj->transparency);
1128 if (empty($this->userownerid)) {
1129 $this->userownerid = $obj->fk_element; // If not defined (should not happened, we fix this)
1130 }
1131 break;
1132 case 'socpeople':
1133 $this->socpeopleassigned[$obj->fk_element] = array('id' => $obj->fk_element, 'mandatory' => $obj->mandatory, 'answer_status' => $obj->answer_status, 'transparency' => $obj->transparency);
1134 break;
1135 }
1136 }
1137 }
1138
1139 return 1;
1140 } else {
1141 dol_print_error($this->db);
1142 return -1;
1143 }
1144 }
1145
1146 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1153 public function fetch_userassigned($override = true)
1154 {
1155 // phpcs:enable
1156 $sql = "SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency";
1157 $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm_resources";
1158 $sql .= " WHERE element_type = 'user' AND fk_actioncomm = ".((int) $this->id);
1159
1160 $resql2 = $this->db->query($sql);
1161 if ($resql2) {
1162 $this->userassigned = array();
1163
1164 // If owner is known, we must but id first into list
1165 if ($this->userownerid > 0) {
1166 // Set first so will be first into list.
1167 $this->userassigned[$this->userownerid] = array('id' => $this->userownerid);
1168 }
1169
1170 while ($obj = $this->db->fetch_object($resql2)) {
1171 if ($obj->fk_element > 0) {
1172 $this->userassigned[$obj->fk_element] = array('id' => $obj->fk_element,
1173 'mandatory' => $obj->mandatory,
1174 'answer_status' => $obj->answer_status,
1175 'transparency' => $obj->transparency);
1176 }
1177
1178 if ($override === true) {
1179 // If not defined (should not happened, we fix this)
1180 if (empty($this->userownerid)) {
1181 $this->userownerid = $obj->fk_element;
1182 }
1183 }
1184 }
1185
1186 return 1;
1187 } else {
1188 dol_print_error($this->db);
1189 return -1;
1190 }
1191 }
1192
1202 public function getIdsOfRecurringSerie()
1203 {
1204 if (empty($this->recurid)) {
1205 return array();
1206 }
1207
1208 $sql = "SELECT a.id";
1209 $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
1210 $sql .= " WHERE a.recurid = '".$this->db->escape($this->recurid)."'";
1211 $sql .= " AND a.entity IN (".getEntity('agenda').")";
1212 $sql .= " ORDER BY a.datep ASC, a.id ASC";
1213
1214 dol_syslog(get_class($this)."::getIdsOfRecurringSerie", LOG_DEBUG);
1215 $resql = $this->db->query($sql);
1216 if (!$resql) {
1217 $this->error = $this->db->lasterror();
1218 $this->errors[] = $this->error;
1219 return -1;
1220 }
1221
1222 $ids = array();
1223 while ($obj = $this->db->fetch_object($resql)) {
1224 $ids[] = (int) $obj->id;
1225 }
1226 $this->db->free($resql);
1227
1228 return $ids;
1229 }
1230
1238 public function delete($user, $notrigger = 0)
1239 {
1240 $error = 0;
1241
1242 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1243
1244 $this->db->begin();
1245
1246 // remove categorie association
1247 if (!$error) {
1248 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_actioncomm";
1249 $sql .= " WHERE fk_actioncomm=".((int) $this->id);
1250
1251 $res = $this->db->query($sql);
1252 if (!$res) {
1253 $this->error = $this->db->lasterror();
1254 $error++;
1255 }
1256 }
1257
1258 // remove actioncomm_resources
1259 if (!$error) {
1260 $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources";
1261 $sql .= " WHERE fk_actioncomm=".((int) $this->id);
1262
1263 $res = $this->db->query($sql);
1264 if (!$res) {
1265 $this->error = $this->db->lasterror();
1266 $error++;
1267 }
1268 }
1269
1270 if (!$error) {
1271 $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
1272 $sql .= " WHERE fk_actioncomm = ".((int) $this->id);
1273
1274 $res = $this->db->query($sql);
1275 if (!$res) {
1276 $this->error = $this->db->lasterror();
1277 $error++;
1278 }
1279 }
1280
1281 // Removed extrafields
1282 if (!$error) {
1283 $result = $this->deleteExtraFields();
1284 if ($result < 0) {
1285 $error++;
1286 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1287 }
1288 }
1289
1290 // remove actioncomm
1291 if (!$error) {
1292 $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm";
1293 $sql .= " WHERE id=".((int) $this->id);
1294
1295 $res = $this->db->query($sql);
1296 if (!$res) {
1297 $this->error = $this->db->lasterror();
1298 $error++;
1299 }
1300 }
1301
1302 if (!$error) {
1303 if (!$notrigger) {
1304 // Call trigger
1305 $result = $this->call_trigger('ACTION_DELETE', $user);
1306 if ($result < 0) {
1307 $error++;
1308 }
1309 // End call triggers
1310 }
1311
1312 if (!$error) {
1313 $this->db->commit();
1314 return 1;
1315 } else {
1316 $this->db->rollback();
1317 return -2;
1318 }
1319 } else {
1320 $this->db->rollback();
1321 $this->error = $this->db->lasterror();
1322 return -1;
1323 }
1324 }
1325
1334 public function update(User $user, $notrigger = 0)
1335 {
1336 $error = 0;
1337
1338 // Clean parameters
1339 $this->label = dol_trunc(sanitizeVal($this->label, 'alphawithlgt'), 128);
1340 $this->note_private = dol_htmlcleanlastbr(trim(!isset($this->note_private) ? $this->note : $this->note_private));
1341 if (empty($this->percentage)) {
1342 $this->percentage = 0;
1343 }
1344 if (empty($this->priority) || !is_numeric($this->priority)) {
1345 $this->priority = 0;
1346 }
1347 if (empty($this->transparency)) {
1348 $this->transparency = 0;
1349 }
1350 if (empty($this->fulldayevent)) {
1351 $this->fulldayevent = 0;
1352 }
1353 if ($this->percentage > 100) {
1354 $this->percentage = 100;
1355 }
1356 //if ($this->percentage == 100 && ! $this->dateend) $this->dateend = $this->date;
1357 if ($this->datep && $this->datef) {
1358 $this->durationp = ($this->datef - $this->datep); // deprecated
1359 }
1360 //if ($this->date && $this->dateend) $this->durationa=($this->dateend - $this->date);
1361 if ($this->datep && $this->datef && $this->datep > $this->datef) {
1362 $this->datef = $this->datep;
1363 }
1364 //if ($this->date && $this->dateend && $this->date > $this->dateend) $this->dateend=$this->date;
1365 if ($this->fk_project < 0) {
1366 $this->fk_project = 0;
1367 }
1368
1369 $socid = (($this->socid > 0) ? $this->socid : 0);
1370 $contactid = (($this->contact_id > 0) ? $this->contact_id : 0);
1371 $userownerid = ($this->userownerid ? $this->userownerid : 0);
1372
1373 // If a type_id is set, we must also have the type_code set
1374 if ($this->type_id > 0) {
1375 if (empty($this->type_code)) {
1376 $cactioncomm = new CActionComm($this->db);
1377 $result = $cactioncomm->fetch($this->type_id);
1378 if ($result >= 0 && !empty($cactioncomm->code)) {
1379 $this->type_code = $cactioncomm->code;
1380 }
1381 }
1382 }
1383
1384 $code = $this->code;
1385 if (empty($code) || (!empty($this->oldcopy) && $this->oldcopy->type_code != $this->type_code)) { // If code unknown or if we change the type, we reset $code too
1386 $code = $this->type_code;
1387 }
1388
1389 $this->db->begin();
1390
1391 $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm";
1392 $sql .= " SET percent = '".$this->db->escape((string) $this->percentage)."'";
1393 $sql .= ", fk_action = ".(int) $this->type_id;
1394 $sql .= ", code = " . ($code ? "'".$this->db->escape($code)."'" : "null");
1395 $sql .= ", label = ".($this->label ? "'".$this->db->escape($this->label)."'" : "null");
1396 $sql .= ", datep = ".(strval($this->datep) != '' ? "'".$this->db->idate($this->datep)."'" : 'null');
1397 $sql .= ", datep2 = ".(strval($this->datef) != '' ? "'".$this->db->idate($this->datef)."'" : 'null');
1398 $sql .= ", durationp = ".(isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '' ? "'".$this->db->escape((string) $this->durationp)."'" : "null"); // deprecated
1399 $sql .= ", note = '".$this->db->escape($this->note_private)."'";
1400 $sql .= ", fk_project =".($this->fk_project > 0 ? ((int) $this->fk_project) : "null");
1401 $sql .= ", fk_soc =".($socid > 0 ? ((int) $socid) : "null");
1402 $sql .= ", fk_contact =".($contactid > 0 ? ((int) $contactid) : "null");
1403 $sql .= ", priority = '".$this->db->escape((string) $this->priority)."'";
1404 $sql .= ", fulldayevent = '".$this->db->escape((string) $this->fulldayevent)."'";
1405 $sql .= ", location = ".($this->location ? "'".$this->db->escape($this->location)."'" : "null");
1406 $sql .= ", max_participants = ".(isset($this->max_participants) && $this->max_participants > 0 ? ((int) $this->max_participants) : "null");
1407 $sql .= ", transparency = '".$this->db->escape((string) $this->transparency)."'";
1408 $sql .= ", fk_user_mod = ".((int) $user->id);
1409 $sql .= ", fk_user_action = ".($userownerid > 0 ? ((int) $userownerid) : "null");
1410 $sql .= ", fk_task = ".(!empty($this->fk_task) ? ((int) $this->fk_task) : "null");
1411 if (!empty($this->fk_element)) {
1412 $sql .= ", fk_element=".($this->fk_element ? ((int) $this->fk_element) : "null");
1413 }
1414 if (!empty($this->elementtype)) {
1415 $sql .= ", elementtype=".($this->elementtype ? "'".$this->db->escape($this->elementtype)."'" : "null");
1416 }
1417 if (!empty($this->num_vote)) {
1418 $sql .= ", num_vote=".($this->num_vote ? (int) $this->num_vote : null);
1419 }
1420 if (!empty($this->event_paid)) {
1421 $sql .= ", event_paid=".($this->event_paid ? (int) $this->event_paid : 0);
1422 }
1423 if (!empty($this->status)) {
1424 $sql .= ", status=".($this->status ? (int) $this->status : 0);
1425 }
1426 $sql .= " WHERE id=".((int) $this->id);
1427
1428 dol_syslog(get_class($this)."::update", LOG_DEBUG);
1429 if ($this->db->query($sql)) {
1430 $action = 'update';
1431
1432 // Actions on extra fields
1433 if (!$error) {
1434 $result = $this->insertExtraFields();
1435 if ($result < 0) {
1436 $error++;
1437 }
1438 }
1439
1440 // Now insert assignedusers
1441 if (!$error) {
1442 $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources where fk_actioncomm = ".((int) $this->id)." AND element_type = 'user'";
1443 $resql = $this->db->query($sql);
1444
1445 $already_inserted = array();
1446 foreach ($this->userassigned as $key => $val) {
1447 if (!is_array($val)) { // For backward compatibility when val=id
1448 $val = array('id' => $val);
1449 }
1450 if (!isset($val['id']) || !is_scalar($val['id'])) {
1451 continue;
1452 }
1453 if (!empty($already_inserted[$val['id']])) {
1454 continue;
1455 }
1456
1457 $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
1458 $sql .= " VALUES(".((int) $this->id).", 'user', ".((int) $val['id']).", ".(empty($val['mandatory']) ? '0' : ((int) $val['mandatory'])).", ".(empty($val['transparency']) ? '0' : ((int) $val['transparency'])).", ".(empty($val['answer_status']) ? '0' : ((int) $val['answer_status'])).")";
1459
1460 $resql = $this->db->query($sql);
1461 if (!$resql) {
1462 $error++;
1463 $this->errors[] = $this->db->lasterror();
1464 } else {
1465 $already_inserted[$val['id']] = true;
1466 }
1467 //var_dump($sql);exit;
1468 }
1469 }
1470
1471 if (!$error) {
1472 $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources where fk_actioncomm = ".((int) $this->id)." AND element_type = 'socpeople'";
1473 $resql = $this->db->query($sql);
1474
1475 if (!empty($this->socpeopleassigned)) {
1476 $already_inserted = array();
1477 foreach ($this->socpeopleassigned as $val) {
1478 if (!is_array($val)) { // For backward compatibility when val=id
1479 $val = array('id' => $val);
1480 }
1481 if (!empty($already_inserted[$val['id']])) {
1482 continue;
1483 }
1484
1485 $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
1486 $sql .= " VALUES(".((int) $this->id).", 'socpeople', ".((int) $val['id']).", 0, 0, 0)";
1487
1488 $resql = $this->db->query($sql);
1489 if (!$resql) {
1490 $error++;
1491 $this->errors[] = $this->db->lasterror();
1492 } else {
1493 $already_inserted[$val['id']] = true;
1494 }
1495 }
1496 }
1497 }
1498
1499 if (!$error && !$notrigger) {
1500 // Call trigger
1501 $result = $this->call_trigger('ACTION_MODIFY', $user);
1502 if ($result < 0) {
1503 $error++;
1504 }
1505 // End call triggers
1506 }
1507
1508 if (!$error) {
1509 $this->db->commit();
1510 return 1;
1511 } else {
1512 $this->db->rollback();
1513 dol_syslog(get_class($this)."::update ".implode(',', $this->errors), LOG_ERR);
1514 return -2;
1515 }
1516 } else {
1517 $this->db->rollback();
1518 $this->error = $this->db->lasterror();
1519 return -1;
1520 }
1521 }
1522
1533 public function checkResourceConflicts($newdatep, $newdatef)
1534 {
1535 if (!getDolGlobalString('RESOURCE_USED_IN_EVENT_CHECK') || $this->element != 'action') {
1536 return array();
1537 }
1538
1539 $sql = "SELECT er.rowid, r.ref as r_ref, ac.id as ac_id, ac.label as ac_label";
1540 $sql .= " FROM ".MAIN_DB_PREFIX."element_resources as er";
1541 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."resource as r ON r.rowid = er.resource_id AND er.resource_type = 'dolresource'";
1542 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm as ac ON ac.id = er.element_id AND er.element_type = '".$this->db->escape($this->element)."'";
1543 $sql .= " WHERE ac.id <> ".((int) $this->id);
1544 $sql .= " AND er.resource_id IN (";
1545 $sql .= " SELECT resource_id FROM ".MAIN_DB_PREFIX."element_resources";
1546 $sql .= " WHERE element_id = ".((int) $this->id);
1547 $sql .= " AND element_type = '".$this->db->escape($this->element)."'";
1548 $sql .= " AND busy = 1";
1549 $sql .= ")";
1550 $sql .= " AND er.busy = 1";
1551 $sql .= " AND (";
1552 $sql .= " (ac.datep <= '".$this->db->idate($newdatep)."' AND (ac.datep2 IS NULL OR ac.datep2 >= '".$this->db->idate($newdatep)."'))";
1553 if (!empty($newdatef)) {
1554 $sql .= " OR (ac.datep <= '".$this->db->idate($newdatef)."' AND (ac.datep2 >= '".$this->db->idate($newdatef)."'))";
1555 }
1556 $sql .= " OR (";
1557 $sql .= "ac.datep >= '".$this->db->idate($newdatep)."'";
1558 if (!empty($newdatef)) {
1559 $sql .= " AND (ac.datep2 IS NOT NULL AND ac.datep2 <= '".$this->db->idate($newdatef)."')";
1560 }
1561 $sql .= ")";
1562 $sql .= ")";
1563
1564 $resql = $this->db->query($sql);
1565 if (!$resql) {
1566 $this->error = $this->db->lasterror();
1567 return -1;
1568 }
1569
1570 $conflicts = array();
1571 while ($obj = $this->db->fetch_object($resql)) {
1572 $conflicts[] = array('r_ref' => $obj->r_ref, 'ac_id' => (int) $obj->ac_id, 'ac_label' => $obj->ac_label);
1573 }
1574 $this->db->free($resql);
1575
1576 return $conflicts;
1577 }
1578
1587 public function formatResourceConflicts($conflicts, $langs)
1588 {
1589 $message = $langs->trans('ErrorResourcesAlreadyInUse').' : ';
1590 foreach ($conflicts as $conflict) {
1591 $message .= '<br> - '.$langs->trans('ErrorResourceUseInEvent', $conflict['r_ref'], $conflict['ac_label'].' ['.$conflict['ac_id'].']');
1592 }
1593 return $message;
1594 }
1595
1610 public function getActions($socid = 0, $fk_element = 0, $elementtype = '', $sqlfilter = '', $sortfield = 'a.datep', $sortorder = 'DESC', $limit = 0)
1611 {
1612 global $hookmanager;
1613
1614 $resarray = array();
1615
1616 dol_syslog(get_class($this)."::getActions", LOG_DEBUG);
1617
1618 // Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
1619 if (!is_object($hookmanager)) {
1620 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
1621 $hookmanager = new HookManager($this->db);
1622 }
1623 $hookmanager->initHooks(array('agendadao'));
1624
1625 $sql = "SELECT a.id";
1626 if ($elementtype == 'user') {
1627 $sql .= ",a.datep";
1628 }
1629 $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
1630 // Fields from hook
1631 $parameters = array('sql' => &$sql, 'socid' => $socid, 'fk_element' => $fk_element, 'elementtype' => $elementtype);
1632 $reshook = $hookmanager->executeHooks('getActionsListFrom', $parameters); // Note that $action and $object may have been modified by hook
1633 if (!empty($hookmanager->resPrint)) {
1634 $sql .= $hookmanager->resPrint;
1635 }
1636 $sql .= " WHERE a.entity IN (".getEntity('agenda').")";
1637 if (!empty($socid)) {
1638 $sql .= " AND a.fk_soc = ".((int) $socid);
1639 }
1640 if (!empty($elementtype)) {
1641 if ($elementtype == 'project') {
1642 $sql .= ' AND a.fk_project = '.((int) $fk_element);
1643 } elseif ($elementtype == 'contact') {
1644 $sql .= ' AND EXISTS';
1645 $sql .= " (SELECT r.rowid FROM ".MAIN_DB_PREFIX."actioncomm_resources as r WHERE";
1646 $sql .= " r.element_type = 'socpeople' AND r.fk_element = ".((int) $fk_element).' AND r.fk_actioncomm = a.id)';
1647 } elseif ($elementtype == 'user') {
1648 $sql1 = $sql;
1649 $sql .= " AND a.fk_user_action = ".((int) $fk_element);
1650 $sql = "SELECT a.id FROM ((" . $sql . ") UNION (" . $sql1;
1651 $sql .= " AND EXISTS (SELECT r.rowid FROM ".MAIN_DB_PREFIX."actioncomm_resources as r WHERE";
1652 $sql .= " r.element_type = 'user' AND r.fk_element = ".((int) $fk_element).' AND r.fk_actioncomm = a.id)';
1653 $sql .= " AND a.fk_user_action <> ".((int) $fk_element);
1654 $sql .= ")) as a";
1655 } else {
1656 $sql .= " AND a.fk_element = ".((int) $fk_element)." AND a.elementtype = '".$this->db->escape($elementtype)."'";
1657 }
1658 }
1659 if (!empty($sqlfilter)) {
1660 $sql .= $sqlfilter;
1661 }
1662 // Fields where hook
1663 $parameters = array('sql' => &$sql, 'socid' => $socid, 'fk_element' => $fk_element, 'elementtype' => $elementtype);
1664 $reshook = $hookmanager->executeHooks('getActionsListWhere', $parameters); // Note that $action and $object may have been modified by hook
1665 if (!empty($hookmanager->resPrint)) {
1666 $sql .= $hookmanager->resPrint;
1667 }
1668 if ($sortorder && $sortfield) {
1669 $sql .= $this->db->order($sortfield, $sortorder);
1670 }
1671 $sql .= $this->db->plimit($limit, 0);
1672
1673 $resql = $this->db->query($sql);
1674 if ($resql) {
1675 $num = $this->db->num_rows($resql);
1676
1677 if ($num) {
1678 for ($i = 0; $i < $num; $i++) {
1679 $obj = $this->db->fetch_object($resql);
1680 $actioncommstatic = new ActionComm($this->db);
1681 $actioncommstatic->fetch($obj->id);
1682 $resarray[$i] = $actioncommstatic;
1683 }
1684 }
1685 $this->db->free($resql);
1686 return $resarray;
1687 } else {
1688 return $this->db->lasterror();
1689 }
1690 }
1691
1692 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1700 public function load_board($user, $load_state_board = 0)
1701 {
1702 // phpcs:enable
1703 global $conf, $langs;
1704
1705 if (empty($load_state_board)) {
1706 // The count and the number of late events are computed by the database instead of reading every event to do. An event
1707 // is late when it has a date and that date is before now minus the warning delay (the rule of hasDelay()).
1708 $sql = "SELECT COUNT(a.id) as nb,";
1709 $sql .= " SUM(CASE WHEN a.datep IS NOT NULL AND a.datep < '".$this->db->idate(dol_now() - $conf->agenda->warning_delay)."' THEN 1 ELSE 0 END) as nblate";
1710 } else {
1711 $this->nb = array();
1712 $sql = "SELECT count(a.id) as nb";
1713 }
1714 $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
1715 if (!$user->hasRight('agenda', 'allactions', 'read')) {
1716 $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 = ".((int) $user->id);
1717 }
1718 $sql .= " WHERE 1 = 1";
1719 if (empty($load_state_board)) {
1720 $sql .= " AND a.percent >= 0 AND a.percent < 100";
1721 }
1722 $sql .= " AND a.entity IN (".getEntity('agenda').")";
1723 if (!$user->hasRight('agenda', 'allactions', 'read')) {
1724 $sql .= " AND (a.fk_user_author = ".((int) $user->id)." OR a.fk_user_action = ".((int) $user->id);
1725 $sql .= " OR ar.fk_element = ".((int) $user->id);
1726 $sql .= ")";
1727 }
1728 // If the internal user must only see his customers, force searching by him
1729 $search_sale = 0;
1730 if (!$user->hasRight('societe', 'client', 'voir')) {
1731 $search_sale = $user->id;
1732 }
1733 // Search on sale representative
1734 if ($search_sale && $search_sale != '-1') {
1735 if ($search_sale == -2) {
1736 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = a.fk_soc)";
1737 } elseif ($search_sale > 0) {
1738 $sql .= " AND (a.fk_soc IS NULL OR EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = a.fk_soc AND sc.fk_user = ".((int) $search_sale)."))";
1739 }
1740 }
1741
1742 $resql = $this->db->query($sql);
1743 if ($resql) {
1744 $response = null; // Ensure the variable is defined
1745 if (empty($load_state_board)) {
1746 $response = new WorkboardResponse();
1747 $response->warning_delay = $conf->agenda->warning_delay / 60 / 60 / 24;
1748 $response->label = $langs->trans("ActionsToDo");
1749 $response->labelShort = $langs->trans("ActionsToDoShort");
1750 $response->url = DOL_URL_ROOT.'/comm/action/list.php?mode=show_list&actioncode=0&status=todo&mainmenu=agenda';
1751 if ($user->hasRight("agenda", "allactions", "read")) {
1752 $response->url .= '&filtert=-1';
1753 }
1754 $response->img = img_object('', "action", 'class="inline-block valigntextmiddle"');
1755
1756 $obj = $this->db->fetch_object($resql);
1757 if ($obj) {
1758 $response->nbtodo = (int) $obj->nb;
1759 $response->nbtodolate = (int) $obj->nblate;
1760 }
1761 } else {
1762 $obj = $this->db->fetch_object($resql);
1763 if ($obj) {
1764 $this->nb["actionscomm"] = $obj->nb;
1765 }
1766 }
1767
1768 $this->db->free($resql);
1769 if (empty($load_state_board) && $response instanceof WorkboardResponse) {
1770 return $response;
1771 } else {
1772 return 1;
1773 }
1774 } else {
1775 dol_print_error($this->db);
1776 $this->error = $this->db->error();
1777 return -1;
1778 }
1779 }
1780
1781
1788 public function info($id)
1789 {
1790 $sql = 'SELECT ';
1791 $sql .= ' a.id,';
1792 $sql .= ' datec,';
1793 $sql .= ' tms as datem,';
1794 $sql .= ' fk_user_author,';
1795 $sql .= ' fk_user_mod';
1796 $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm as a';
1797 $sql .= ' WHERE a.id = '.((int) $id);
1798
1799 dol_syslog(get_class($this)."::info", LOG_DEBUG);
1800 $result = $this->db->query($sql);
1801 if ($result) {
1802 if ($this->db->num_rows($result)) {
1803 $obj = $this->db->fetch_object($result);
1804
1805 $this->id = $obj->id;
1806
1807 $this->user_creation_id = $obj->fk_user_author;
1808 $this->user_modification_id = $obj->fk_user_mod;
1809 $this->date_creation = $this->db->jdate($obj->datec);
1810 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
1811 }
1812 $this->db->free($result);
1813 } else {
1814 dol_print_error($this->db);
1815 }
1816 }
1817
1818
1826 public function getLibStatut($mode, $hidenastatus = 0)
1827 {
1828 return $this->LibStatut($this->percentage, $mode, $hidenastatus, $this->datep);
1829 }
1830
1831 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1841 public function LibStatut($percent, $mode, $hidenastatus = 0, $datestart = '')
1842 {
1843 // phpcs:enable
1844 global $langs;
1845
1846 $labelStatus = $langs->transnoentitiesnoconv('StatusNotApplicable');
1847 if ($percent == -1 && !$hidenastatus) {
1848 $labelStatus = $langs->transnoentitiesnoconv('StatusNotApplicable');
1849 } elseif ($percent == 0) {
1850 $labelStatus = $langs->transnoentitiesnoconv('StatusActionToDo').' (0%)';
1851 } elseif ($percent > 0 && $percent < 100) {
1852 $labelStatus = $langs->transnoentitiesnoconv('StatusActionInProcess').' ('.$percent.'%)';
1853 } elseif ($percent >= 100) {
1854 $labelStatus = $langs->transnoentitiesnoconv('StatusActionDone').' (100%)';
1855 }
1856
1857 $labelStatusShort = $langs->transnoentitiesnoconv('StatusNotApplicable');
1858 if ($percent == -1 && !$hidenastatus) {
1859 $labelStatusShort = $langs->trans('NA');
1860 } elseif ($percent == 0) {
1861 $labelStatusShort = '0%';
1862 } elseif ($percent > 0 && $percent < 100) {
1863 $labelStatusShort = $percent.'%';
1864 } elseif ($percent >= 100) {
1865 $labelStatusShort = '100%';
1866 }
1867
1868 $statusType = 'status9';
1869 if ($percent == -1 && !$hidenastatus) {
1870 $statusType = 'status9';
1871 }
1872 if ($percent == 0) {
1873 $statusType = 'status1';
1874 }
1875 if ($percent > 0 && $percent < 100) {
1876 $statusType = 'status3';
1877 }
1878 if ($percent >= 100) {
1879 $statusType = 'status6';
1880 }
1881
1882 $params = array('badgeParams' => array('attr' => array('title' => '<b>'.$langs->trans("Progression").'</b> : '.$labelStatus)));
1883
1884 return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode, '', $params);
1885 }
1886
1893 public function getTooltipContentArray($params)
1894 {
1895 global $langs, $form;
1896
1897 $langs->load('agenda');
1898
1899 $datas = array();
1900 $nofetch = !empty($params['nofetch']);
1901
1902 // Set label of type
1903 $labeltype = '';
1904 if ($this->type_code) {
1905 $langs->load("commercial");
1906 $labeltype = ($langs->transnoentities("Action".$this->type_code) != "Action".$this->type_code) ? $langs->transnoentities("Action".$this->type_code) : $this->type_label;
1907 }
1908 if (!getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
1909 if ($this->type_code != 'AC_OTH_AUTO') {
1910 $labeltype = $langs->trans('ActionAC_MANUAL');
1911 }
1912 }
1913 $datas['picto'] = img_picto('', $this->picto).' <u>'.$langs->trans('Action').'</u>';
1914 if (!empty($this->ref)) {
1915 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.dol_escape_htmltag($this->ref);
1916 }
1917 $translatedlabel = $this->getTranslatedLabel();
1918 if (!empty($translatedlabel)) {
1919 $datas['title'] = '<br><b>'.$langs->trans('Title').':</b> '.dol_escape_htmltag($translatedlabel);
1920 }
1921 if (!empty($labeltype)) {
1922 $datas['labeltype'] = '<br><b>'.$langs->trans('Type').':</b> '.dol_escape_htmltag($labeltype);
1923 }
1924 if (!empty($this->location)) {
1925 $datas['location'] = '<br><b>'.$langs->trans('Location').':</b> '.dol_escape_htmltag($this->location);
1926 }
1927 if (isset($this->transparency) && $this->datef && $this->datep != $this->datef && isset($this->transparency)) {
1928 $datas['transparency'] = '<br><b>'.$langs->trans('Busy').':</b> '.yn($this->transparency);
1929 }
1930
1931 $datas['date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->datep, 'dayhourreduceformat', 'tzuserrel');
1932 if ($this->datef) {
1933 $tmpa = dol_getdate($this->datep);
1934 $tmpb = dol_getdate($this->datef);
1935 if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) {
1936 if ($tmpa['hours'] != $tmpb['hours'] || $tmpa['minutes'] != $tmpb['minutes']) {
1937 $datas['date'] .= '-'.dol_print_date($this->datef, 'hour', 'tzuserrel');
1938 }
1939 } else {
1940 $datas['date'] .= '-'.dol_print_date($this->datef, 'dayhourreduceformat', 'tzuserrel');
1941 }
1942 }
1943
1944 if (!empty($this->recurid)) {
1945 $datas['recurring'] = '<br><b>'.$langs->trans("RecurringEvent").':</b> ';
1946 $datas['recurring'] .= img_picto($langs->trans("EventPartOfARecurringSerie", $this->recurid), 'recurring', 'class="pictofixedwidth"');
1947 $reg = array();
1948 if (preg_match('/FREQ=MONTHLY_BYMONTHDAY(\d+)/', $this->recurrule, $reg)) {
1949 $datas['recurring'] .= $langs->trans("EveryMonth").' <span class="opacitymedium small">('.$langs->trans("DayOfMonth").' '.$reg[1].' - '.$langs->trans("Until").' '.dol_print_date($this->recurdateend, 'day').')</span>';
1950 }
1951 }
1952
1953 if (!empty($this->email_msgid)) {
1954 $langs->load("mails");
1955 $datas['space'] = '<br>';
1956 // $datas['email'] = '<br><b>'.img_picto('', 'email').' '.$langs->trans("Email").'</b>';
1957 $datas['mailtopic'] = '<br><b>'.$langs->trans('MailTopic').':</b> '.dol_escape_htmltag($this->email_subject);
1958 $datas['mailfrom'] = '<br><b>'.$langs->trans('MailFrom').':</b> '.dol_htmlentities($this->email_from);
1959 $datas['mailto'] = '<br><b>'.$langs->trans('MailTo').':</b> '.dol_htmlentities($this->email_to);
1960 if (!empty($this->email_tocc)) {
1961 $datas['mailcc'] = '<br><b>'.$langs->trans('MailCC').':</b> '.dol_htmlentities($this->email_tocc);
1962 }
1963 /* Disabled because bcc must remain by definition not visible
1964 if (!empty($this->email_tobcc)) {
1965 $datas['mailccc'] = '<br><b>'.$langs->trans('MailCCC').':</b> '.$this->email_tobcc;
1966 } */
1967 }
1968 if (!empty($this->note_private)) {
1969 $datas['description'] = '<br><hr>';
1970 // Try to limit length of content
1971 $texttoshow = dolGetFirstLineOfText($this->note_private, 10);
1972 // Restrict height of content into the tooltip
1973 $datas['note'] = '<div class="tenlinesmax">';
1974 $datas['note'] .= (dol_textishtml($texttoshow) ? str_replace(array("\r", "\n"), "", $texttoshow) : str_replace(array("\r", "\n"), '<br>', $texttoshow));
1975 $datas['note'] .= '</div>';
1976 }
1977
1978 // show categories for this record only in ajax to not overload lists
1979 if (isModEnabled('category') && !$nofetch) {
1980 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
1981 if (empty($form)) {
1982 include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
1983 $form = new Form($this->db);
1984 }
1985 $tmpcategstring = $form->showCategories($this->id, Categorie::TYPE_ACTIONCOMM, 1);
1986 if ($tmpcategstring) {
1987 $datas['categories'] = '<br>'.$tmpcategstring;
1988 }
1989 }
1990
1991 return $datas;
1992 }
1993
2007 public function getNomUrl($withpicto = 0, $maxlength = 0, $morecss = '', $option = '', $overwritepicto = 0, $notooltip = 0, $save_lastsearch_value = -1)
2008 {
2009 global $conf, $langs, $user, $hookmanager, $action;
2010
2011 if (!empty($conf->dol_no_mouse_hover)) {
2012 $notooltip = 1; // Force disable tooltips
2013 }
2014
2015 $canread = 0;
2016 if ($user->hasRight('agenda', 'myactions', 'read') && ($this->authorid == $user->id || $this->userownerid == $user->id)) {
2017 $canread = 1; // Can read my event
2018 }
2019 if ($user->hasRight('agenda', 'myactions', 'read') && array_key_exists($user->id, $this->userassigned)) {
2020 $canread = 1; // Can read my event i am assigned
2021 }
2022 if ($user->hasRight('agenda', 'allactions', 'read')) {
2023 $canread = 1; // Can read all event of other
2024 }
2025 if (!$canread) {
2026 $option = 'nolink';
2027 }
2028
2029 $label = $this->getTranslatedLabel();
2030
2031 $result = '';
2032
2033 // Set label of type
2034 $labeltype = $this->getTypeLabel(1);
2035
2036 $linkclose = '';
2037
2038 $params = [
2039 'id' => (string) $this->id,
2040 'objecttype' => $this->element.($this->module ? '@'.$this->module : ''),
2041 'option' => $option,
2042 'nofetch' => 1,
2043 ];
2044 $classfortooltip = 'classfortooltip';
2045 $dataparams = '';
2046 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2047 $classfortooltip = 'classforajaxtooltip';
2048 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2049 //$label = ''; // $label is used as ref when $maxlength is not negative, so we must not empty it.
2050 } else {
2051 $label = implode($this->getTooltipContentArray($params));
2052 }
2053
2054 if (empty($notooltip)) {
2055 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2056 $label = $langs->trans("ShowAction");
2057 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
2058 }
2059 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
2060 $linkclose .= $dataparams.' class="'.$morecss.' '.$classfortooltip.'"';
2061 } else {
2062 $linkclose .= ' class="'.$morecss.'"';
2063 }
2064
2065 $query = ['id' => $this->id];
2066 if ($option == 'birthday') {
2067 $baseurl = DOL_URL_ROOT.'/contact/perso.php';
2068 } elseif ($option == 'holiday') {
2069 $baseurl = DOL_URL_ROOT.'/holiday/card.php';
2070 } else {
2071 $baseurl = DOL_URL_ROOT.'/comm/action/card.php';
2072 }
2073
2074 if ($option !== 'nolink') {
2075 // Add param to save lastsearch_values or not
2076 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2077 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2078 $add_save_lastsearch_values = 1;
2079 }
2080 if ($add_save_lastsearch_values) {
2081 $query += ['save_lastsearch_values' => 1];
2082 }
2083 }
2084 $url = dolBuildUrl($baseurl, $query);
2085
2086 $linkstart = '<a href="'.$url.'"';
2087 $linkstart .= $linkclose.'>';
2088 $linkend = '</a>';
2089
2090 if ($option == 'nolink') {
2091 $linkstart = '';
2092 $linkend = '';
2093 }
2094
2095 if ($withpicto == 2) {
2096 if (getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
2097 $label = $labeltype;
2098 }
2099 $labelshort = '';
2100 } else {
2101 if (getDolGlobalString('AGENDA_USE_EVENT_TYPE') && empty($label)) {
2102 if (empty($this->label)) {
2103 $label = $labeltype;
2104 } else {
2105 $label = $this->getTranslatedLabel();
2106 }
2107 }
2108 if ($maxlength < 0) {
2109 $labelshort = $this->ref;
2110 } else {
2111 $labelshort = dol_trunc(empty($label) ? $labeltype : $label, $maxlength);
2112 }
2113 }
2114
2115 if ($withpicto) {
2116 if (getDolGlobalString('AGENDA_USE_EVENT_TYPE')) { // Add code into ()
2117 if ($labeltype) {
2118 $label .= (preg_match('/'.preg_quote($labeltype, '/').'/', $label) ? '' : ' ('.$langs->transnoentities("Action".$this->type_code).')');
2119 }
2120 }
2121 }
2122
2123 $result .= $linkstart;
2124 if ($withpicto) {
2125 $result .= img_object(($notooltip ? '' : $langs->trans("ShowAction").': '.$label), ($overwritepicto ? $overwritepicto : 'action'), (($this->type_color && $overwritepicto) ? 'style="color: #'.$this->type_color.' !important;" ' : '').($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : ' class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
2126 }
2127 $result .= dol_escape_htmltag($labelshort);
2128 $result .= $linkend;
2129
2130 global $action;
2131 $hookmanager->initHooks(array('actiondao'));
2132 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
2133 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2134 if ($reshook > 0) {
2135 $result = $hookmanager->resPrint;
2136 } else {
2137 $result .= $hookmanager->resPrint;
2138 }
2139
2140 return $result;
2141 }
2142
2148 public function getTranslatedLabel()
2149 {
2150 global $langs;
2151
2152 if ($this->code == 'AC_COMPANY_CREATE' && !empty($this->thirdparty->name)) {
2153 return $langs->transnoentitiesnoconv('NewCompanyToDolibarr', $this->thirdparty->name);
2154 }
2155
2156 return $this->label;
2157 }
2158
2167 public function getTypePicto($morecss = 'pictofixedwidth paddingright valignmiddle', $titlealt = '')
2168 {
2169 $imgpicto = '';
2170 if (getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
2171 $color = '';
2172 if ($this->type_color) {
2173 $color = 'style="color: #'.$this->type_color.' !important;"';
2174 }
2175 if ($this->type_picto) {
2176 $imgpicto = img_picto($titlealt, $this->type_picto, '', 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2177 } else {
2178 if ($this->type_code === 'AC_RDV') {
2179 $imgpicto = img_picto($titlealt, 'meeting', $color, 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2180 } elseif ($this->type_code === 'AC_TEL') {
2181 $imgpicto = img_picto($titlealt, 'object_phoning', $color, 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2182 } elseif ($this->type_code === 'AC_FAX') {
2183 $imgpicto = img_picto($titlealt, 'object_phoning_fax', $color, 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2184 } elseif ($this->type_code === 'AC_EMAIL' || $this->type_code === 'AC_EMAIL_IN' || $this->type_code === 'AC_EMAILING' || (!empty($this->code) && preg_match('/_SENTBYMAIL/', $this->code))) {
2185 $imgpicto = img_picto($titlealt, 'object_email', $color, 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2186 } elseif ($this->type_code === 'AC_INT') {
2187 $imgpicto = img_picto($titlealt, 'object_intervention', $color, 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2188 } elseif (!empty($this->code) && preg_match('/^TICKET_MSG/', $this->code)) {
2189 $imgpicto = img_picto($titlealt, 'object_conversation', $color, 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2190 } elseif ((string) $this->type != 'systemauto') {
2191 $imgpicto = img_picto($titlealt, 'user-cog', $color, 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2192 } else {
2193 $imgpicto = img_picto($titlealt, 'cog', $color, 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2194 }
2195 }
2196 } else {
2197 // 2 picto: 1 for auto, 1 for manual
2198 if ($this->type != 'systemauto') {
2199 $imgpicto = img_picto($titlealt, 'user-cog', '', 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2200 } else {
2201 $imgpicto = img_picto($titlealt, 'cog', '', 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2202 }
2203 }
2204
2205 return $imgpicto;
2206 }
2207
2208
2215 public function getTypeLabel($mode = 0)
2216 {
2217 global $conf, $langs;
2218
2219 // If cache for array of types unknown, we load it
2220 if (!empty($conf->cache['actioncommgetypelabel'])) {
2221 $arraylist = $conf->cache['actioncommgetypelabel'];
2222 } else {
2223 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php';
2224 $caction = new CActionComm($this->db);
2225 $arraylist = $caction->liste_array(1, 'code', '', (getDolGlobalString('AGENDA_USE_EVENT_TYPE') ? 0 : 1), '', 1);
2226 $conf->cache['actioncommgetypelabel'] = $arraylist;
2227 }
2228
2229 $labeltype = $this->type_code;
2230 if (!getDolGlobalString('AGENDA_USE_EVENT_TYPE') && empty($arraylist[$labeltype])) {
2231 $labeltype = 'AC_OTH';
2232 }
2233 if (!empty($this->code) && preg_match('/^TICKET_MSG/', $this->code)) {
2234 $labeltype = $langs->trans("Message");
2235 } else {
2236 if (!empty($arraylist[$labeltype])) {
2237 $labeltype = $arraylist[$labeltype];
2238 }
2239 if ($this->type_code == 'AC_OTH_AUTO' && ($this->type_code != $this->code) && $labeltype && !empty($arraylist[$this->code])) {
2240 $labeltype .= ' - '.$arraylist[$this->code]; // Use code in priority over type_code
2241 }
2242 }
2243
2244 if ($this->type == 'systemauto' && $mode == 1) {
2245 $labeltype .= ' ('.$langs->trans("auto").')';
2246 }
2247 if ($this->type == 'systemauto' && $mode == 2) {
2248 $labeltype = $langs->trans("AutoActions").($this->type_code == 'AC_OTH_AUTO' ? '' : ': '.$labeltype);
2249 } elseif ($this->type != 'systemauto' && $mode == 2) {
2250 $labeltype = $langs->trans("ManualActions").($this->type_code == 'AC_OTH' ? '' : ': '.$labeltype);
2251 }
2252
2253
2254 return $labeltype;
2255 }
2256
2267 public function setCategories($categories)
2268 {
2269 // Handle single category
2270 if (!is_array($categories)) {
2271 $categories = array($categories);
2272 }
2273
2274 // Get current categories
2275 include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2276 $c = new Categorie($this->db);
2277 $existing = $c->containing($this->id, Categorie::TYPE_ACTIONCOMM, 'id');
2278
2279 // Diff
2280 if (is_array($existing)) {
2281 $to_del = array_diff($existing, $categories);
2282 $to_add = array_diff($categories, $existing);
2283 } else {
2284 $to_del = array(); // Nothing to delete
2285 $to_add = $categories;
2286 }
2287
2288 // Process
2289 foreach ($to_del as $del) {
2290 if ($c->fetch($del) > 0) {
2291 $c->del_type($this, Categorie::TYPE_ACTIONCOMM);
2292 }
2293 }
2294 foreach ($to_add as $add) {
2295 if ($c->fetch($add) > 0) {
2296 $c->add_type($this, Categorie::TYPE_ACTIONCOMM);
2297 }
2298 }
2299 return 1;
2300 }
2301
2302 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2314 public function build_exportfile($format, $type, $cachedelay, $filename, $filters, $exportholiday = 0)
2315 {
2316 global $hookmanager;
2317
2318 // phpcs:enable
2319 global $conf, $langs, $dolibarr_main_url_root, $mysoc;
2320
2321 require_once DOL_DOCUMENT_ROOT."/core/lib/xcal.lib.php";
2322 require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php";
2323 require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php";
2324
2325 dol_syslog(get_class($this)."::build_exportfile Build export file format=".$format.", type=".$type.", cachedelay=".$cachedelay.", filename=".$filename.", filters size=".count($filters), LOG_DEBUG);
2326
2327 // Check parameters
2328 if (empty($format)) {
2329 return -1;
2330 }
2331
2332 // Clean parameters
2333 if (!$filename) {
2334 $extension = 'vcs';
2335 if ($format == 'ical') {
2336 $extension = 'ics';
2337 }
2338 $filename = $format.'.'.$extension;
2339 }
2340
2341 // Create dir and define output file (definitive and temporary)
2342 $result = dol_mkdir($conf->agenda->dir_temp);
2343 $outputfile = $conf->agenda->dir_temp.'/'.$filename;
2344
2345 $result = 0;
2346
2347 $buildfile = true;
2348 $login = '';
2349 $logina = '';
2350 $logint = '';
2351 $eventorganization = '';
2352
2353 $now = dol_now();
2354
2355 if ($cachedelay) {
2356 $nowgmt = dol_now();
2357 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2358 if (dol_filemtime($outputfile) > ($nowgmt - $cachedelay)) {
2359 dol_syslog(get_class($this)."::build_exportfile file ".$outputfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay."). Build is canceled");
2360 $buildfile = false;
2361 }
2362 }
2363
2364 if ($buildfile) {
2365 // Build event array
2366 $eventarray = array();
2367
2368 if (!empty($filters['module']) && $filters['module'] == 'project@eventorganization') {
2369 $sql = "SELECT p.rowid as id,";
2370 $sql .= " p.date_start_event as datep,"; // Start
2371 $sql .= " p.date_end_event as datep2,"; // End
2372 $sql .= " p.datec, p.tms as datem,";
2373 $sql .= " p.title as label, '' as code, p.note_public, p.note_private, 0 as type_id,";
2374 $sql .= " p.fk_soc,";
2375 $sql .= " p.fk_user_creat as fk_user_author, p.fk_user_modif as fk_user_mod,";
2376 $sql .= " 0 as fk_user_action,";
2377 $sql .= " 0 as fk_contact, 100 as percentage,";
2378 $sql .= " 0 as fk_element, '' as elementtype,";
2379 $sql .= " 1 as priority, 0 as fulldayevent, p.location, 0 as transparency,";
2380 $sql .= " u.firstname, u.lastname, '".$this->db->escape(getDolGlobalString("MAIN_INFO_SOCIETE_MAIL"))."' as email,";
2381 $sql .= " s.nom as socname,";
2382 $sql .= " 0 as type_id, '' as type_code, '' as type_label";
2383 $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
2384 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = p.fk_user_creat"; // Link to get author of event for export
2385 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = p.fk_soc";
2386
2387 $parameters = array('filters' => $filters);
2388 $reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters); // Note that $action and $object may have been modified by hook
2389 $sql .= $hookmanager->resPrint;
2390
2391 $sql .= " WHERE p.entity IN (".getEntity('project').")";
2392
2393 foreach ($filters as $key => $value) {
2394 if ($key == 'notolderthan' && $value != '') {
2395 $sql .= " AND p.date_start_event >= '".$this->db->idate($now - ($value * 24 * 60 * 60))."'";
2396 }
2397 if ($key == 'year') {
2398 $sql .= " AND p.date_start_event BETWEEN '".$this->db->idate(dol_get_first_day($value, 1))."' AND '".$this->db->idate(dol_get_last_day($value, 12))."'";
2399 }
2400 if ($key == 'id') {
2401 $sql .= " AND p.id = ".(is_numeric($value) ? $value : 0);
2402 }
2403 if ($key == 'idfrom') {
2404 $sql .= " AND p.id >= ".(is_numeric($value) ? $value : 0);
2405 }
2406 if ($key == 'idto') {
2407 $sql .= " AND p.id <= ".(is_numeric($value) ? $value : 0);
2408 }
2409 if ($key == 'project') {
2410 $sql .= " AND p.rowid = ".(is_numeric($value) ? $value : 0);
2411 }
2412 if ($key == 'status') {
2413 $sql .= " AND p.fk_statut = ".((int) $value);
2414 }
2415 // TODO Add filters on event code of meetings/talks only
2416 }
2417
2418 $sql .= " ORDER by date_start_event";
2419
2420 $eventorganization = 'project';
2421 } else {
2422 $sql = "SELECT a.id,";
2423 $sql .= " a.datep,"; // Start
2424 $sql .= " a.datep2,"; // End
2425 $sql .= " a.datec, a.tms as datem,";
2426 $sql .= " a.label, a.code, '' as note_public, a.note as note_private, a.fk_action as type_id,";
2427 $sql .= " a.fk_soc,";
2428 $sql .= " a.fk_user_author, a.fk_user_mod,";
2429 $sql .= " a.fk_user_action,";
2430 $sql .= " a.fk_contact, a.percent as percentage,";
2431 $sql .= " a.fk_element, a.elementtype,";
2432 $sql .= " a.priority, a.fulldayevent, a.location, a.transparency,";
2433 $sql .= " u.firstname, u.lastname, u.email,";
2434 $sql .= " s.nom as socname,";
2435 $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label,";
2436 $sql .= " num_vote, event_paid, a.status";
2437 $sql .= " FROM (".MAIN_DB_PREFIX."c_actioncomm as c, ".MAIN_DB_PREFIX."actioncomm as a)";
2438 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author"; // Link to get author of event for export
2439 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc";
2440
2441 $parameters = array('filters' => $filters);
2442 $reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters); // Note that $action and $object may have been modified by hook
2443 $sql .= $hookmanager->resPrint;
2444
2445 // We must filter on assignment table
2446 if (!empty($filters['logint']) && $filters['logint']) {
2447 $sql .= ", ".MAIN_DB_PREFIX."actioncomm_resources as ar";
2448 }
2449 $sql .= " WHERE a.fk_action = c.id";
2450 $sql .= " AND a.entity IN (".getEntity('agenda').")";
2451
2452 foreach ($filters as $key => $value) {
2453 if ($key == 'notolderthan' && $value != '') {
2454 $sql .= " AND a.datep >= '".$this->db->idate($now - ($value * 24 * 60 * 60))."'";
2455 }
2456 if ($key == 'year') {
2457 $sql .= " AND a.datep BETWEEN '".$this->db->idate(dol_get_first_day($value, 1))."' AND '".$this->db->idate(dol_get_last_day($value, 12))."'";
2458 }
2459 if ($key == 'id') {
2460 $sql .= " AND a.id = ".(is_numeric($value) ? $value : 0);
2461 }
2462 if ($key == 'idfrom') {
2463 $sql .= " AND a.id >= ".(is_numeric($value) ? $value : 0);
2464 }
2465 if ($key == 'idto') {
2466 $sql .= " AND a.id <= ".(is_numeric($value) ? $value : 0);
2467 }
2468 if ($key == 'project') {
2469 $sql .= " AND a.fk_project = ".(is_numeric($value) ? $value : 0);
2470 }
2471 if ($key == 'notactiontype') { // deprecated
2472 $sql .= " AND c.type <> '".$this->db->escape($value)."'";
2473 }
2474 if ($key == 'actiontype') { // 'system', 'systemauto', 'module', ...
2475 $newvalue = $value;
2476 $usenotin = 0;
2477 if (preg_match('/^!/', $newvalue)) {
2478 $newvalue = preg_replace('/^!/', '', $value);
2479 $usenotin = 1;
2480 }
2481 $arraynewvalue = explode(',', $newvalue);
2482 $newvalue = "";
2483 foreach ($arraynewvalue as $tmpval) {
2484 $newvalue .= ($newvalue ? "," : "")."'".$tmpval."'";
2485 }
2486 if ($usenotin) {
2487 $sql .= " AND c.type NOT IN (".$this->db->sanitize($newvalue, 1).")";
2488 } else {
2489 $sql .= " AND c.type IN (".$this->db->sanitize($newvalue, 1).")";
2490 }
2491 }
2492 if ($key == 'actioncode') { // 'AC_COMPANY_CREATE', 'AC_COMPANY_MODIFY', ...
2493 $newvalue = $value;
2494 $usenotin = 0;
2495 if (preg_match('/^!/', $newvalue)) {
2496 $newvalue = preg_replace('/^!/', '', $value);
2497 $usenotin = 1;
2498 }
2499 $arraynewvalue = explode(',', $newvalue);
2500 $newvalue = "";
2501 foreach ($arraynewvalue as $tmpval) {
2502 $newvalue .= ($newvalue ? "," : "")."'".$tmpval."'";
2503 }
2504 if ($usenotin) {
2505 $sql .= " AND a.code NOT IN (".$this->db->sanitize($newvalue, 1).")";
2506 } else {
2507 $sql .= " AND a.code IN (".$this->db->sanitize($newvalue, 1).")";
2508 }
2509 }
2510
2511 // We must filter on assignment table
2512 if ($key == 'logint') {
2513 $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'";
2514 }
2515 if ($key == 'logina') {
2516 $logina = $value;
2517 $sanitizedcondition = '=';
2518 if (preg_match('/^!/', $logina)) {
2519 $logina = preg_replace('/^!/', '', $logina);
2520 $sanitizedcondition = '<>';
2521 }
2522 $userforfilter = new User($this->db);
2523 $result = $userforfilter->fetch(0, $logina);
2524 if ($result > 0) {
2525 $sql .= " AND a.fk_user_author ".$sanitizedcondition." ".((int) $userforfilter->id);
2526 } elseif ($result < 0 || $sanitizedcondition == '=') {
2527 $sql .= " AND a.fk_user_author = 0";
2528 }
2529 }
2530 if ($key == 'logint') {
2531 $logint = $value;
2532 $sanitizedcondition = '=';
2533 if (preg_match('/^!/', $logint)) {
2534 $logint = preg_replace('/^!/', '', $logint);
2535 $sanitizedcondition = '<>';
2536 }
2537 $userforfilter = new User($this->db);
2538 $result = $userforfilter->fetch(0, $logint);
2539 if ($result > 0) {
2540 $sql .= " AND ar.fk_element = ".((int) $userforfilter->id);
2541 } elseif ($result < 0 || $sanitizedcondition == '=') {
2542 $sql .= " AND ar.fk_element = 0";
2543 }
2544 }
2545 if ($key == 'module') {
2546 if ($value == 'conforbooth@eventorganization') {
2547 $value = '@eventorganization';
2548 }
2549 $sql .= " AND c.module LIKE '%".$this->db->escape($value)."'";
2550 }
2551 if ($key == 'status') {
2552 $sql .= " AND a.status = ".((int) $value);
2553 }
2554 }
2555
2556 $sql .= " AND a.datep IS NOT NULL"; // To exclude corrupted events and avoid errors in lightning/sunbird import
2557
2558 $parameters = array('filters' => $filters);
2559 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
2560 $sql .= $hookmanager->resPrint;
2561
2562 $sql .= " ORDER by datep";
2563 }
2564
2565 if (!empty($filters['limit'])) {
2566 $sql .= $this->db->plimit((int) $filters['limit']);
2567 }
2568
2569 //print $sql;exit;
2570
2571 dol_syslog(get_class($this)."::build_exportfile select event(s)", LOG_DEBUG);
2572
2573 $resql = $this->db->query($sql);
2574 if ($resql) {
2575 $diff = 0;
2576 while ($obj = $this->db->fetch_object($resql)) {
2577 $qualified = true;
2578
2579 // 'eid','startdate','duration','enddate','title','summary','category','email','url','desc','author'
2580 $event = array();
2581 $event['uid'] = 'dolibarragenda-'.$obj->id."@".dol_getprefix('email');
2582 $event['type'] = $type;
2583
2584 $datestart = (int) $this->db->jdate($obj->datep) - (getDolGlobalInt('AGENDA_EXPORT_FIX_TZ') * 3600);
2585
2586 // fix for -> Warning: A non-numeric value encountered
2587 if (is_numeric($this->db->jdate($obj->datep2))) {
2588 $dateend = (int) $this->db->jdate($obj->datep2) - (getDolGlobalInt('AGENDA_EXPORT_FIX_TZ') * 3600);
2589 } else {
2590 // use start date as fall-back to avoid pb with empty end date on ICS readers
2591 $dateend = $datestart;
2592 }
2593
2594 $duration = ($datestart && $dateend) ? ($dateend - $datestart) : 0;
2595 $event['summary'] = $obj->label.($obj->socname ? " (".$obj->socname.")" : "");
2596
2597 if (!empty($filters['module']) && $filters['module'] == 'project@eventorganization') {
2598 $event['desc'] = $obj->note_public;
2599 } else {
2600 $event['desc'] = $obj->note_private;
2601 }
2602 $event['startdate'] = $datestart;
2603 $event['enddate'] = $dateend; // Not required with type 'journal'
2604 $event['duration'] = $duration; // Not required with type 'journal'
2605 $event['author'] = dolGetFirstLastname($obj->firstname, $obj->lastname);
2606 $event['priority'] = $obj->priority;
2607 $event['fulldayevent'] = $obj->fulldayevent;
2608 $event['location'] = $obj->location;
2609 $event['transparency'] = (($obj->transparency > 0) ? 'OPAQUE' : 'TRANSPARENT'); // OPAQUE (busy) or TRANSPARENT (not busy)
2610 $event['category'] = $obj->type_label;
2611 $event['email'] = $obj->email;
2612
2613 // Public URL of event
2614 if ($eventorganization != '') {
2615 $link_subscription = $dolibarr_main_url_root.'/public/eventorganization/attendee_new.php?id='.((int) $obj->id).'&type=global&noregistration=1';
2616 $encodedsecurekey = dol_hash(getDolGlobalString('EVENTORGANIZATION_SECUREKEY').'conferenceorbooth'.((int) $obj->id), 'md5');
2617 $link_subscription .= '&securekey='.urlencode($encodedsecurekey);
2618
2619 $event['url'] = $link_subscription;
2620 } else {
2621 $event['url'] = $dolibarr_main_url_root.'/comm/action/card.php?id='.$obj->id;
2622 }
2623
2624 $event['created'] = (int) $this->db->jdate($obj->datec) - (getDolGlobalInt('AGENDA_EXPORT_FIX_TZ') * 3600);
2625 $event['modified'] = (int) $this->db->jdate($obj->datem) - (getDolGlobalInt('AGENDA_EXPORT_FIX_TZ') * 3600);
2626 $event['num_vote'] = $this->num_vote;
2627 $event['event_paid'] = $this->event_paid;
2628 $event['status'] = $this->status;
2629
2630 // TODO: find a way to call "$this->fetch_userassigned();" without override "$this" properties
2631 $this->id = $obj->id;
2632 $this->fetch_userassigned(false);
2633
2634 $assignedUserArray = array();
2635
2636 foreach ($this->userassigned as $key => $value) {
2637 $assignedUser = new User($this->db);
2638 $assignedUser->fetch($value['id']);
2639
2640 $assignedUserArray[$key] = $assignedUser;
2641 }
2642
2643 if (empty($filters['module']) || $filters['module'] != 'project@eventorganization') {
2644 $event['assignedUsers'] = $assignedUserArray;
2645 }
2646
2647 if ($qualified && $datestart) {
2648 $eventarray[] = $event;
2649 }
2650 $diff++;
2651 }
2652
2653 $parameters = array('filters' => $filters, 'eventarray' => &$eventarray);
2654 $reshook = $hookmanager->executeHooks('addMoreEventsExport', $parameters); // Note that $action and $object may have been modified by hook
2655 if ($reshook > 0) {
2656 $eventarray = $hookmanager->resArray;
2657 }
2658 } else {
2659 $this->error = $this->db->lasterror();
2660 return -1;
2661 }
2662
2663 if ($exportholiday == 1) {
2664 $langs->load("holiday");
2665 $title = $langs->transnoentities("Holidays");
2666
2667 $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";
2668 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as x, ".MAIN_DB_PREFIX."user as u";
2669 $sql .= " WHERE u.rowid = x.fk_user";
2670 $sql .= " AND u.statut = '1'"; // Show only active users (0 = inactive user, 1 = active user)
2671 $sql .= " AND (x.statut = '2' OR x.statut = '3')"; // Show only public leaves (2 = leave wait for approval, 3 = leave approved)
2672
2673 $resql = $this->db->query($sql);
2674 if ($resql) {
2675 $num = $this->db->num_rows($resql);
2676 $i = 0;
2677
2678 while ($i < $num) {
2679 $obj = $this->db->fetch_object($resql);
2680 $event = array();
2681
2682 if ($obj->halfday == 1) {
2683 $event['fulldayevent'] = false;
2684
2685 $timestampStart = dol_stringtotime($obj->date_start." 00:00:00", 0);
2686 $timestampEnd = dol_stringtotime($obj->date_end." 12:00:00", 0);
2687 } elseif ($obj->halfday == -1) {
2688 $event['fulldayevent'] = false;
2689
2690 $timestampStart = dol_stringtotime($obj->date_start." 12:00:00", 0);
2691 $timestampEnd = dol_stringtotime($obj->date_end." 23:59:59", 0);
2692 } else {
2693 $event['fulldayevent'] = true;
2694
2695 $timestampStart = dol_stringtotime($obj->date_start." 00:00:00", 0);
2696 $timestampEnd = dol_stringtotime($obj->date_end." 23:59:59", 0);
2697 }
2698
2699 if (getDolGlobalString('AGENDA_EXPORT_FIX_TZ')) {
2700 $timestampStart -= (getDolGlobalInt('AGENDA_EXPORT_FIX_TZ') * 3600);
2701 $timestampEnd -= (getDolGlobalInt('AGENDA_EXPORT_FIX_TZ') * 3600);
2702 }
2703
2704 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2705 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
2706 $url = $urlwithroot.'/holiday/card.php?id='.$obj->rowid;
2707
2708 $event['uid'] = 'dolibarrholiday-'.$obj->rowid."@".dol_getprefix('email');
2709 $event['author'] = dolGetFirstLastname($obj->firstname, $obj->lastname);
2710 $event['type'] = 'event';
2711 $event['category'] = "Holiday";
2712 $event['transparency'] = 'OPAQUE';
2713 $event['email'] = $obj->email;
2714 $event['created'] = $timestampStart;
2715 $event['modified'] = $timestampStart;
2716 $event['startdate'] = $timestampStart;
2717 $event['enddate'] = $timestampEnd;
2718 $event['duration'] = $timestampEnd - $timestampStart;
2719 $event['url'] = $url;
2720
2721 if ($obj->status == 2) {
2722 // 2 = leave wait for approval
2723 $event['summary'] = $title." - ".$obj->lastname." (wait for approval)";
2724 } else {
2725 // 3 = leave approved
2726 $event['summary'] = $title." - ".$obj->lastname;
2727 }
2728
2729 $eventarray[] = $event;
2730
2731 $i++;
2732 }
2733 }
2734 }
2735
2736 $langs->load("agenda");
2737
2738 // Define title and desc
2739 $title = '';
2740 $more = '';
2741 if ($login) {
2742 $more = $langs->transnoentities("User").' '.$login;
2743 }
2744 if ($logina) {
2745 $more = $langs->transnoentities("ActionsAskedBy").' '.$logina;
2746 }
2747 if ($logint) {
2748 $more = $langs->transnoentities("ActionsToDoBy").' '.$logint;
2749 }
2750 if ($eventorganization) {
2751 $langs->load("eventorganization");
2752 $title = $langs->transnoentities("OrganizedEvent").(empty($eventarray[0]['label']) ? '' : ' '.$eventarray[0]['label']);
2753 $more = 'ICS file - '.$langs->transnoentities("OrganizedEvent").(empty($eventarray[0]['label']) ? '' : ' '.$eventarray[0]['label']);
2754 }
2755 if ($more) {
2756 if (empty($title)) {
2757 $title = 'Dolibarr actions '.$mysoc->name.' - '.$more;
2758 }
2759 $desc = $more;
2760 $desc .= ' ('.$mysoc->name.' - built by Dolibarr)';
2761 } else {
2762 if (empty($title)) {
2763 $title = $langs->transnoentities("Events").' '.$mysoc->name;
2764 }
2765 $desc = $langs->transnoentities('ListOfActions');
2766 $desc .= ' ('.$mysoc->name.' - built by Dolibarr)';
2767 }
2768
2769 // Create temp file
2770 $outputfiletmp = tempnam($conf->agenda->dir_temp, 'tmp'); // Temporary file (allow call of function by different threads
2771 dolChmod($outputfiletmp);
2772
2773 // Write file
2774 if ($format == 'vcal') {
2775 $result = build_calfile($format, $title, $desc, $eventarray, $outputfiletmp);
2776 } elseif ($format == 'ical') {
2777 $result = build_calfile($format, $title, $desc, $eventarray, $outputfiletmp);
2778 } elseif ($format == 'rss') {
2779 $result = build_rssfile($format, $title, $desc, $eventarray, $outputfiletmp);
2780 }
2781
2782 if ($result >= 0) {
2783 if (dol_move($outputfiletmp, $outputfile, '0', 1, 0, 0)) {
2784 $result = 1;
2785 } else {
2786 $this->error = 'Failed to rename '.$outputfiletmp.' into '.$outputfile;
2787 dol_syslog(get_class($this)."::build_exportfile ".$this->error, LOG_ERR);
2788 dol_delete_file($outputfiletmp, 0, 1);
2789 $result = -1;
2790 }
2791 } else {
2792 dol_syslog(get_class($this)."::build_exportfile build_xxxfile function fails to for format=".$format." outputfiletmp=".$outputfile, LOG_ERR);
2793 dol_delete_file($outputfiletmp, 0, 1);
2794 $langs->load("errors");
2795 $this->error = $langs->trans("ErrorFailToCreateFile", $outputfile);
2796 }
2797 }
2798
2799 return $result;
2800 }
2801
2809 public function initAsSpecimen()
2810 {
2811 global $user;
2812
2813 $now = dol_now();
2814
2815 // Initialise parameters
2816 $this->id = 0;
2817 $this->specimen = 1;
2818
2819 $this->type_code = 'AC_OTH';
2820 $this->code = 'AC_SPECIMEN_CODE';
2821 $this->label = 'Label of event Specimen';
2822 $this->datec = $now;
2823 $this->datem = $now;
2824 $this->datep = $now;
2825 $this->datef = $now;
2826 $this->fulldayevent = 0;
2827 $this->percentage = 0;
2828 $this->status = 0;
2829 $this->location = 'Location';
2830 $this->transparency = 1; // 1 means opaque
2831 $this->priority = 1;
2832 //$this->note_public = "This is a 'public' note.";
2833 $this->note_private = "This is a 'private' note.";
2834
2835 $this->userownerid = $user->id;
2836 $this->userassigned[$user->id] = array('id' => $user->id, 'transparency' => 1);
2837 return 1;
2838 }
2839
2848 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2849 {
2850 $tables = array(
2851 'actioncomm'
2852 );
2853
2854 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
2855 }
2856
2867 public static function replaceContact(DoliDB $dbs, $origin_id, $dest_id)
2868 {
2869 // llx_actioncomm_resources: UNIQUE(fk_actioncomm, element_type, fk_element)
2870 $sql = 'DELETE FROM '.$dbs->prefix().'actioncomm_resources WHERE rowid IN (';
2871 $sql .= ' SELECT x.rowid FROM (';
2872 $sql .= ' SELECT origin.rowid FROM '.$dbs->prefix().'actioncomm_resources as origin';
2873 $sql .= ' INNER JOIN '.$dbs->prefix().'actioncomm_resources as dest';
2874 $sql .= ' ON dest.fk_actioncomm = origin.fk_actioncomm AND dest.element_type = origin.element_type';
2875 $sql .= " WHERE origin.element_type = 'socpeople'";
2876 $sql .= ' AND origin.fk_element = '.((int) $origin_id).' AND dest.fk_element = '.((int) $dest_id);
2877 $sql .= ' ) as x)';
2878 if (!$dbs->query($sql)) {
2879 return false;
2880 }
2881
2882 $sql = 'UPDATE '.$dbs->prefix().'actioncomm_resources SET fk_element = '.((int) $dest_id);
2883 $sql .= " WHERE element_type = 'socpeople' AND fk_element = ".((int) $origin_id);
2884 if (!$dbs->query($sql)) {
2885 return false;
2886 }
2887
2888 // llx_actioncomm_reminder: UNIQUE(fk_actioncomm, fk_user, fk_soc, fk_contact, typeremind, offsetvalue, offsetunit)
2889 $sql = 'DELETE FROM '.$dbs->prefix().'actioncomm_reminder WHERE rowid IN (';
2890 $sql .= ' SELECT x.rowid FROM (';
2891 $sql .= ' SELECT origin.rowid FROM '.$dbs->prefix().'actioncomm_reminder as origin';
2892 $sql .= ' INNER JOIN '.$dbs->prefix().'actioncomm_reminder as dest';
2893 $sql .= ' ON dest.fk_actioncomm = origin.fk_actioncomm AND dest.typeremind = origin.typeremind';
2894 $sql .= ' AND dest.offsetvalue = origin.offsetvalue AND dest.offsetunit = origin.offsetunit';
2895 // fk_user and fk_soc are part of the unique key and are nullable, hence the NULL safe
2896 // comparisons: the MySQL <=> operator is not portable to PostgreSQL
2897 $sql .= ' AND (dest.fk_user = origin.fk_user OR (dest.fk_user IS NULL AND origin.fk_user IS NULL))';
2898 $sql .= ' AND (dest.fk_soc = origin.fk_soc OR (dest.fk_soc IS NULL AND origin.fk_soc IS NULL))';
2899 $sql .= ' WHERE origin.fk_contact = '.((int) $origin_id).' AND dest.fk_contact = '.((int) $dest_id);
2900 $sql .= ' ) as x)';
2901 if (!$dbs->query($sql)) {
2902 return false;
2903 }
2904
2905 $tables = array(
2906 'actioncomm', 'actioncomm_reminder'
2907 );
2908
2909 return CommonObject::commonReplaceContact($dbs, $origin_id, $dest_id, $tables, 'fk_contact');
2910 }
2911
2920 public static function replaceProduct(DoliDB $dbs, $origin_id, $dest_id)
2921 {
2922 $sql = 'UPDATE ' . MAIN_DB_PREFIX . 'actioncomm SET fk_element = ' . ((int) $dest_id) . " WHERE elementtype = 'product' AND fk_element = ".((int) $origin_id);
2923 // using $dbs, not $this->db because function is static
2924 if (!$dbs->query($sql)) {
2925 //$this->errors = $dbs->lasterror();
2926 return false;
2927 }
2928
2929 return true;
2930 }
2931
2937 public function hasDelay()
2938 {
2939 global $conf;
2940
2941 $now = dol_now();
2942
2943 return $this->datep && ($this->datep < ($now - $conf->agenda->warning_delay));
2944 }
2945
2946
2955 public function loadReminders($type = '', $fk_user = 0, $onlypast = true)
2956 {
2957 $error = 0;
2958
2959 $this->reminders = array();
2960
2961 //Select all action comm reminders for event
2962 $sql = "SELECT rowid as id, typeremind, dateremind, status, offsetvalue, offsetunit, fk_user, fk_email_template, lasterror";
2963 $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
2964 $sql .= " WHERE fk_actioncomm = ".((int) $this->id);
2965 if ($onlypast) {
2966 $sql .= " AND dateremind <= '".$this->db->idate(dol_now())."'";
2967 }
2968 if ($type) {
2969 $sql .= " AND typeremind = '".$this->db->escape($type)."'";
2970 }
2971 if ($fk_user > 0) {
2972 $sql .= " AND fk_user = ".((int) $fk_user);
2973 }
2974 if (!getDolGlobalString('AGENDA_REMINDER_EMAIL')) {
2975 $sql .= " AND typeremind <> 'email'";
2976 }
2977 if (!getDolGlobalString('AGENDA_REMINDER_BROWSER')) {
2978 $sql .= " AND typeremind <> 'browser'";
2979 }
2980
2981 $sql .= $this->db->order("dateremind", "ASC");
2982 $resql = $this->db->query($sql);
2983
2984 if ($resql) {
2985 while ($obj = $this->db->fetch_object($resql)) {
2986 $tmpactioncommreminder = new ActionCommReminder($this->db);
2987 $tmpactioncommreminder->id = $obj->id;
2988 $tmpactioncommreminder->typeremind = $obj->typeremind;
2989 $tmpactioncommreminder->dateremind = $this->db->jdate($obj->dateremind);
2990 $tmpactioncommreminder->offsetvalue = $obj->offsetvalue;
2991 $tmpactioncommreminder->offsetunit = $obj->offsetunit;
2992 $tmpactioncommreminder->status = $obj->status;
2993 $tmpactioncommreminder->fk_user = $obj->fk_user;
2994 $tmpactioncommreminder->fk_email_template = $obj->fk_email_template;
2995 $tmpactioncommreminder->lasterror = $obj->lasterror;
2996 $tmpactioncommreminder->fk_actioncomm = $this->id;
2997
2998 $this->reminders[$obj->id] = $tmpactioncommreminder;
2999 }
3000 } else {
3001 $this->error = $this->db->lasterror();
3002 $error++;
3003 }
3004
3005 return count($this->reminders);
3006 }
3007
3008
3015 public function sendEmailsReminder()
3016 {
3017 global $langs, $user;
3018
3019 $error = 0;
3020 $this->output = '';
3021 $this->error = '';
3022 $nbMailSend = 0;
3023 $errorsMsg = array();
3024
3025 if (!isModEnabled('agenda')) { // Should not happen. If module disabled, cron job should not be visible.
3026 $langs->load("agenda");
3027 $this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Agenda"));
3028 return 0;
3029 }
3030 if (!getDolGlobalString('AGENDA_REMINDER_EMAIL')) {
3031 $langs->load("agenda");
3032 $this->output = $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Agenda"));
3033 return 0;
3034 }
3035
3036 $now = dol_now();
3037 $actionCommReminder = new ActionCommReminder($this->db);
3038
3039 dol_syslog(__METHOD__." start", LOG_INFO);
3040
3041 $this->db->begin();
3042
3043 //Select all action comm reminders
3044 $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
3045 $sql .= " WHERE typeremind = 'email'";
3046 $sql .= " AND status = 0"; // 0=No yet sent, -1=Error. TODO Include reminder in error once we can count number of error, so we can try 5 times and not more on errors.
3047 $sql .= " AND dateremind <= '".$this->db->idate($now)."'";
3048 $sql .= " AND entity IN (".getEntity('actioncomm').")";
3049 $sql .= $this->db->order("dateremind", "ASC");
3050 $resql = $this->db->query($sql);
3051
3052 if ($resql) {
3053 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
3054 $formmail = new FormMail($this->db);
3055 $to = null; // Ensure 'to' is defined for static analysis
3056
3057 while ($obj = $this->db->fetch_object($resql)) {
3058 // Error status for the reminder being processed in this iteration. $error (the cumulative counter for
3059 // the whole run) must not be used to gate this per-reminder processing: once any single reminder fails
3060 // (ex: a user with no email on file), it would otherwise stay non-zero for the rest of the loop and
3061 // silently defer every other due reminder to the next cron run.
3062 $errorforreminder = 0;
3063
3064 $res = $actionCommReminder->fetch($obj->id);
3065 if ($res < 0) {
3066 $error++;
3067 $errorforreminder++;
3068 $errorsMsg[] = "Failed to load invoice ActionComm Reminder";
3069 }
3070
3071 if (!$errorforreminder) {
3072 //Select email template
3073 $arraymessage = $formmail->getEMailTemplate($this->db, 'actioncomm_send', $user, $langs, (!empty($actionCommReminder->fk_email_template)) ? $actionCommReminder->fk_email_template : -1, 1);
3074
3075 // Load event
3076 $res = $this->fetch($actionCommReminder->fk_actioncomm);
3077 if ($res > 0) {
3078 // PREPARE EMAIL
3079 $errormesg = '';
3080 $this->fetch_thirdparty();
3081
3082 // Make substitution in email content
3083 $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $this);
3084
3085 complete_substitutions_array($substitutionarray, $langs, $this);
3086
3087 // Content
3088 $sendContent = make_substitutions($langs->trans($arraymessage->content), $substitutionarray);
3089
3090 // Topic
3091 $sendTopic = (!empty($arraymessage->topic)) ? $arraymessage->topic : $langs->transnoentitiesnoconv('EventReminder');
3092 $sendTopic = make_substitutions($sendTopic, $substitutionarray);
3093
3094 // Recipient
3095 $recipient = new User($this->db);
3096 $res = $recipient->fetch($actionCommReminder->fk_user);
3097 if ($res > 0) {
3098 if (!empty($recipient->email)) {
3099 $to = $recipient->email;
3100 } else {
3101 $errormesg = "Failed to send remind to user id=" . $actionCommReminder->fk_user . ". No email defined for user.";
3102 $error++;
3103 $errorforreminder++;
3104 }
3105 } else {
3106 $errormesg = "Failed to load recipient with user id=" . $actionCommReminder->fk_user;
3107 $error++;
3108 $errorforreminder++;
3109 }
3110
3111 // Sender
3112 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
3113 if (empty($from)) {
3114 $errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
3115 $error++;
3116 $errorforreminder++;
3117 }
3118
3119 if (!$errorforreminder) {
3120 // Errors Recipient
3121 $errors_to = getDolGlobalString('MAIN_MAIL_ERRORS_TO');
3122
3123 // Mail Creation
3124 $cMailFile = new CMailFile($sendTopic, (string) $to, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', '', '', '', '');
3125
3126 // Sending Mail
3127 if ($cMailFile->sendfile()) {
3128 $nbMailSend++;
3129 } else {
3130 $errormesg = 'Failed to send email to: ' . $to . ' ' . $cMailFile->error . implode(',', $cMailFile->errors);
3131 $error++;
3132 $errorforreminder++;
3133 }
3134 }
3135
3136 if (!$errorforreminder) {
3137 $actionCommReminder->status = $actionCommReminder::STATUS_DONE;
3138
3139 $res = $actionCommReminder->update($user);
3140 if ($res < 0) {
3141 $errorsMsg[] = "Failed to update status to done of ActionComm Reminder";
3142 $error++;
3143 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.
3144 }
3145 } else {
3146 $actionCommReminder->status = $actionCommReminder::STATUS_ERROR;
3147 $actionCommReminder->lasterror = dol_trunc($errormesg, 128, 'right', 'UTF-8', 1);
3148
3149 $res = $actionCommReminder->update($user);
3150 if ($res < 0) {
3151 $errorsMsg[] = "Failed to update status to error of ActionComm Reminder";
3152 $error++;
3153 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.
3154 } else {
3155 $errorsMsg[] = $errormesg;
3156 }
3157 }
3158 } else {
3159 $errorsMsg[] = 'Failed to fetch record actioncomm with ID = '.$actionCommReminder->fk_actioncomm;
3160 $error++;
3161 $errorforreminder++;
3162 }
3163 }
3164 }
3165 } else {
3166 $error++;
3167 }
3168
3169 if (!$error) {
3170 // Delete also very old past events (we do not keep more than 1 month record in past)
3171 $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
3172 $sql .= " WHERE dateremind < '".$this->db->idate($now - (3600 * 24 * 32))."'";
3173 $sql .= " AND status = ".((int) $actionCommReminder::STATUS_DONE);
3174 $resql = $this->db->query($sql);
3175
3176 if (!$resql) {
3177 $errorsMsg[] = 'Failed to delete old reminders';
3178 //$error++; // If this fails, we must not rollback other SQL requests already done. Never mind.
3179 }
3180 }
3181
3182 if (!$error) {
3183 $this->output = 'Nb of emails sent : '.$nbMailSend;
3184 $this->db->commit();
3185
3186 dol_syslog(__METHOD__." end - ".$this->output, LOG_INFO);
3187
3188 return 0;
3189 } else {
3190 $this->db->commit(); // We commit also on error, to have the error message recorded.
3191 $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg) ? implode(', ', $errorsMsg) : $error);
3192
3193 dol_syslog(__METHOD__." end - ".$this->error, LOG_INFO);
3194
3195 return $error;
3196 }
3197 }
3198
3205 public function sendSmsReminder()
3206 {
3207 global $langs, $user;
3208
3209 $error = 0;
3210 $this->output = '';
3211 $this->error = '';
3212 $nbSmsSent = 0;
3213 $errorsMsg = array();
3214
3215 if (!isModEnabled('agenda')) { // Should not happen. If module disabled, cron job should not be visible.
3216 $langs->load("agenda");
3217 $this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Agenda"));
3218 return 0;
3219 }
3220 if (!getDolGlobalString('AGENDA_REMINDER_SMS')) {
3221 $langs->load("agenda");
3222 $this->output = $langs->trans('EventRemindersBySmsNotEnabled', $langs->transnoentitiesnoconv("Agenda"));
3223 return 0;
3224 }
3225
3226 $now = dol_now();
3227 $actionCommReminder = new ActionCommReminder($this->db);
3228
3229 dol_syslog(__METHOD__." start", LOG_INFO);
3230
3231 $this->db->begin();
3232
3233 //Select all action comm reminders
3234 $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
3235 $sql .= " WHERE typeremind = 'sms'";
3236 $sql .= " AND status = 0"; // 0=No yet sent, -1=Error. TODO Include reminder in error once we can count number of error, so we can try 5 times and not more on errors.
3237 $sql .= " AND dateremind <= '".$this->db->idate($now)."'";
3238 $sql .= " AND entity IN (".getEntity('actioncomm').")";
3239 $sql .= $this->db->order("dateremind", "ASC");
3240 $resql = $this->db->query($sql);
3241
3242 if ($resql) {
3243 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
3244 $formmail = new FormMail($this->db);
3245 $to = null; // Ensure 'to' is defined for static analysis
3246
3247 while ($obj = $this->db->fetch_object($resql)) {
3248 $res = $actionCommReminder->fetch($obj->id);
3249 if ($res < 0) {
3250 $error++;
3251 $errorsMsg[] = "Failed to load invoice ActionComm Reminder";
3252 }
3253
3254 if (!$error) {
3255 //Select email template
3256 $arraymessage = $formmail->getEMailTemplate($this->db, 'actioncomm_send', $user, $langs, (!empty($actionCommReminder->fk_email_template)) ? $actionCommReminder->fk_email_template : -1, 1);
3257
3258 // Load event
3259 $res = $this->fetch($actionCommReminder->fk_actioncomm);
3260 if ($res > 0) {
3261 // PREPARE SMS
3262 $errormesg = '';
3263 $this->fetch_thirdparty();
3264
3265 // Make substitution in email content
3266 $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $this);
3267
3268 complete_substitutions_array($substitutionarray, $langs, $this);
3269
3270 // Content
3271 $sendContent = dol_string_nohtmltag(make_substitutions($langs->trans($arraymessage->content), $substitutionarray));
3272
3273 // Topic
3274 // $sendTopic = (!empty($arraymessage->topic)) ? $arraymessage->topic : html_entity_decode($langs->transnoentities('EventReminder'));
3275
3276 // Recipient
3277 $recipient = new User($this->db);
3278 $res = $recipient->fetch($actionCommReminder->fk_user);
3279 if ($res > 0) {
3280 if (!empty($recipient->user_mobile)) {
3281 $to = $recipient->user_mobile;
3282 } else {
3283 $errormesg = "Failed to send remind to user id=" . $actionCommReminder->fk_user . ". No email defined for user.";
3284 $error++;
3285 }
3286 } else {
3287 $errormesg = "Failed to load recipient with user id=" . $actionCommReminder->fk_user;
3288 $error++;
3289 }
3290
3291 // Sender
3292 $from = getDolGlobalString('MAIN_SMS_FROM');
3293 if (empty($from)) {
3294 $errormesg = "Failed to get sender into global setup MAIN_SMS_FROM";
3295 $error++;
3296 }
3297
3298 if (!$error) {
3299 // Errors Recipient
3300 // $errors_to = getDolGlobalString('MAIN_MAIL_ERRORS_TO');
3301
3302 // Sms Creation
3303 $CSMSFile = new CSMSFile((string) $to, $from, $sendContent, 0, 0, 3, 1);
3304
3305 // Sending Mail
3306 if ($CSMSFile->sendfile()) {
3307 $nbSmsSent++;
3308 } else {
3309 $errormesg = 'Failed to send email to: ' . $to . ' ' . $CSMSFile->error . implode(',', $CSMSFile->errors);
3310 $error++;
3311 }
3312 }
3313
3314 if (!$error) {
3315 $actionCommReminder->status = $actionCommReminder::STATUS_DONE;
3316
3317 $res = $actionCommReminder->update($user);
3318 if ($res < 0) {
3319 $errorsMsg[] = "Failed to update status to done of ActionComm Reminder";
3320 $error++;
3321 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.
3322 }
3323 } else {
3324 $actionCommReminder->status = $actionCommReminder::STATUS_ERROR;
3325 $actionCommReminder->lasterror = dol_trunc($errormesg, 128, 'right', 'UTF-8', 1);
3326
3327 $res = $actionCommReminder->update($user);
3328 if ($res < 0) {
3329 $errorsMsg[] = "Failed to update status to error of ActionComm Reminder";
3330 $error++;
3331 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.
3332 } else {
3333 $errorsMsg[] = $errormesg;
3334 }
3335 }
3336 } else {
3337 $errorsMsg[] = 'Failed to fetch record actioncomm with ID = '.$actionCommReminder->fk_actioncomm;
3338 $error++;
3339 }
3340 }
3341 }
3342 } else {
3343 $error++;
3344 }
3345
3346 if (!$error) {
3347 // Delete also very old past events (we do not keep more than 1 month record in past)
3348 $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
3349 $sql .= " WHERE dateremind < '".$this->db->idate($now - (3600 * 24 * 32))."'";
3350 $sql .= " AND status = ".((int) $actionCommReminder::STATUS_DONE);
3351 $resql = $this->db->query($sql);
3352
3353 if (!$resql) {
3354 $errorsMsg[] = 'Failed to delete old reminders';
3355 //$error++; // If this fails, we must not rollback other SQL requests already done. Never mind.
3356 }
3357 }
3358
3359 if (!$error) {
3360 $this->output = 'Nb of SMS sent : '.$nbSmsSent;
3361 $this->db->commit();
3362 dol_syslog(__METHOD__." end - ".$this->output, LOG_INFO);
3363
3364 return 0;
3365 } else {
3366 $this->db->commit(); // We commit also on error, to have the error message recorded.
3367 $this->error = 'Nb of SMS sent : '.$nbSmsSent.', '.(!empty($errorsMsg) ? implode(', ', $errorsMsg) : $error);
3368 dol_syslog(__METHOD__." end - ".$this->error, LOG_INFO);
3369
3370 return $error;
3371 }
3372 }
3373
3382 public function updatePercent($id, $percent, $usermodid = 0)
3383 {
3384 $this->db->begin();
3385
3386 $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm ";
3387 $sql .= " SET percent = ".(int) $percent;
3388 if ($usermodid > 0) {
3389 $sql .= ", fk_user_mod = ".((int) $usermodid);
3390 }
3391 $sql .= " WHERE id = ".((int) $id);
3392
3393 if ($this->db->query($sql)) {
3394 $this->db->commit();
3395 return 1;
3396 } else {
3397 $this->db->rollback();
3398 $this->error = $this->db->lasterror();
3399 return -1;
3400 }
3401 }
3402}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
global $dolibarr_main_url_root
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
$c
Definition line.php:353
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage agenda events (actions)
const EVENT_FINISHED
Typical value for a event that is in a finished state.
hasDelay()
Is the action delayed?
build_exportfile($format, $type, $cachedelay, $filename, $filters, $exportholiday=0)
Export events from database into a cal file.
getTooltipContentArray($params)
getTooltipContentArray
update(User $user, $notrigger=0)
Update action into database If percentage = 100, on met a jour date 100%.
sendSmsReminder()
Send reminders by sms CAN BE A CRON TASK.
fetch_userassigned($override=true)
Initialize this->userassigned array with list of id of user assigned to event.
info($id)
Charge les information d'ordre info dans l'objet facture.
static generateUid()
Build a new random UUID (v4, RFC 4122) for $this->uid.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
const EVENT_IN_PROGRESS
Typical value for a event that is in a progress state.
sendEmailsReminder()
Send reminders by emails CAN BE A CRON TASK.
create(User $user, $notrigger=0)
Add an action/event into database.
const EVENT_TODO
Typical value for a event that is in a todo state.
setCategories($categories)
Sets object to supplied categories.
createFromClone(User $fuser, $socid)
Load an object from its id and create a new one in database.
formatResourceConflicts($conflicts, $langs)
Format an array of resource conflicts (as returned by checkResourceConflicts()) into a translated,...
backfillUid()
Backfill $this->uid for an event created before the uid column existed (left NULL by the migration).
static replaceContact(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a contact id with another one when merging two contacts.
getNomUrl($withpicto=0, $maxlength=0, $morecss='', $option='', $overwritepicto=0, $notooltip=0, $save_lastsearch_value=-1)
Return URL of event This uses $this->id, $this->type_code, $this->label and $this->type_label.
LibStatut($percent, $mode, $hidenastatus=0, $datestart='')
Return label of action status.
load_board($user, $load_state_board=0)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
fetch($id, $ref='', $ref_ext='', $email_msgid='', $loadresources=1)
Load object from database.
updatePercent($id, $percent, $usermodid=0)
Update the percent value of a event with the given id.
getActions($socid=0, $fk_element=0, $elementtype='', $sqlfilter='', $sortfield='a.datep', $sortorder='DESC', $limit=0)
Load all objects with filters.
getTypeLabel($mode=0)
Return label of type of event.
loadReminders($type='', $fk_user=0, $onlypast=true)
Load event reminder of events.
fetchResources()
Initialize $this->userassigned & this->socpeopleassigned array with list of id of user and contact as...
getTranslatedLabel()
Return the label translated with current user language when the event was created from a known automa...
static replaceProduct(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a product id with another one.
getTypePicto($morecss='pictofixedwidth paddingright valignmiddle', $titlealt='')
Return Picto of type of event.
__construct(DoliDB $db)
Constructor.
initAsSpecimen()
Initialise an instance with random values.
$fields
Array with all fields and their property.
getLibStatut($mode, $hidenastatus=0)
Return the label of the status.
getIdsOfRecurringSerie()
Return the ids of all the events of the recurring series the current event belongs to.
checkResourceConflicts($newdatep, $newdatef)
Check if any resource attached to this event would become double-booked if the event's dates were cha...
Class for ActionCommReminder.
Class to manage different types of events.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Class to send SMS Usage: $smsfile = new CSMSFile($subject,$sendto,$replyto,$message,...
Class to manage categories.
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
setErrorsFromObject($object)
setErrorsFromObject
deleteExtraFields()
Delete all extra fields values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
static commonReplaceContact(DoliDB $dbs, $origin_id, $dest_id, array $tables, $fieldname='fk_socpeople', $ignoreerrors=0)
Function used to replace a contact id with another one.
cloneCategories($fromId, $toId, $type='')
Copy related categories to another object.
Class to manage Dolibarr database access.
Class to manage generation of HTML components Only common components must be here.
Class to manage a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
Class to manage hooks.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
global $mysoc
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:626
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:645
dol_stringtotime($string, $gm=1, $processnotimeasnoon=0)
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:452
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=null)
Move a file into another name.
dol_filemtime($pathoffile)
Return time of a file.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_now($mode='gmt')
Return date for now.
dolGetFirstLineOfText($text, $nboflines=1, $charset='UTF-8')
Return first line of text.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dolChmod($filepath, $newmask='')
Change mod of a file.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dol_htmlcleanlastbr($stringtodecode)
This function remove all ending and br at end.
dol_htmlentities($string, $flags=ENT_QUOTES|ENT_SUBSTITUTE, $encoding='UTF-8', $double_encode=false)
Replace htmlentities functions.
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 "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
dol_textishtml($msg, $option=0)
Return if a text is a html content.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
dolGetRandomBytes($length)
Return a string of random bytes (hexa string) with length = $length for cryptographic purposes.
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.
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->charset_outp...
Definition xcal.lib.php:36
build_rssfile($format, $title, $desc, $events_array, $outputfile, $filter='', $url='', $langcode='', $useurlforguid=false)
Build a file from an array of events.
Definition xcal.lib.php:337