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
248 public $socpeopleassigned = array();
249
253 public $otherassigned = array();
254
258 public $reminders = array();
259
263 public $socid;
264
268 public $contact_id;
269
273 public $fk_task;
274
280 public $societe;
281
287 public $contact;
288
289 // Properties for links to other objects
294 public $fk_element; // Id of record
295
299 public $elementid;
300
304 public $elementtype;
305
309 public $fk_bookcal_calendar;
310
314 public $icalname;
315
319 public $icalcolor;
320
324 public $extraparams;
325
329 public $actions = array();
330
334 public $email_msgid;
335
339 public $email_from;
340
344 public $email_reply_to;
345
349 public $email_sender;
350
354 public $email_to;
355
359 public $email_tocc;
363 public $email_tobcc;
364
368 public $email_subject;
369
373 public $errors_to;
374
378 public $num_vote;
379
383 public $event_paid;
384
388 public $status;
389
393 public $ip;
394
395 /*
396 * Properties to manage the recurring events
397 */
399 public $recurid;
401 public $recurrule;
403 public $recurdateend;
404
406 public $calling_duration;
407
408
412 const EVENT_TODO = 0;
413
418
422 const EVENT_FINISHED = 100;
423
424
425 // BEGIN MODULEBUILDER PROPERTIES
430 public $fields = array(
431 "id" => array("type" => "integer", "label" => "Ref", "enabled" => "1", 'position' => 10, 'notnull' => 1, "visible" => "1",),
432 "ref" => array("type" => "varchar(30)", "label" => "Ref", "enabled" => "1", 'position' => 15, 'notnull' => 1, "visible" => "0", "csslist" => "tdoverflowmax150", "showoncombobox" => "1",),
433 "ref_ext" => array("type" => "varchar(255)", "label" => "Refext", "enabled" => "1", 'position' => 20, 'notnull' => 0, "visible" => "0",),
434 "datep" => array("type" => "datetime", "label" => "DateStart", "enabled" => "1", 'position' => 25, 'notnull' => 0, "visible" => "1",),
435 "datep2" => array("type" => "datetime", "label" => "DateEnd", "enabled" => "1", 'position' => 26, 'notnull' => 0, "visible" => "-1",),
436 "fk_action" => array("type" => "integer", "label" => "Fkaction", "enabled" => "1", 'position' => 40, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
437 "code" => array("type" => "varchar(50)", "label" => "Code", "enabled" => "1", 'position' => 45, 'notnull' => 0, "visible" => "0", "showoncombobox" => "1",),
438 "label" => array("type" => "varchar(255)", "label" => "Title", "enabled" => "1", 'position' => 50, 'notnull' => 1, "visible" => "1", "alwayseditable" => "1", "css" => "minwidth300", "cssview" => "wordbreak", "csslist" => "tdoverflowmax150",),
439 "note" => array("type" => "mediumtext", "label" => "Description", "enabled" => "1", 'position' => 51, 'notnull' => 0, "visible" => "-1",),
440 "fk_project" => array("type" => "integer", "label" => "Project", "picto" => "project", "enabled" => "1", 'position' => 75, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
441 "fk_soc" => array("type" => "integer", "label" => "ThirdParty", "picto" => "company", "enabled" => "1", 'position' => 80, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
442 "fk_contact" => array("type" => "integer", "label" => "Contact", "picto" => "contact", "enabled" => "1", 'position' => 85, 'notnull' => 0, "visible" => "-1", "css" => "maxwidth500 widthcentpercentminusxx",),
443 "fk_parent" => array("type" => "integer", "label" => "Parent", "enabled" => "1", 'position' => 90, 'notnull' => 1, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
444 "fk_user_action" => array("type" => "integer", "label" => "Fkuseraction", "picto" => "user", "enabled" => "1", 'position' => 95, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
445 "transparency" => array("type" => "integer", "label" => "Transparency", "enabled" => "1", 'position' => 100, 'notnull' => 0, "visible" => "0",),
446 "fk_user_done" => array("type" => "integer", "label" => "Fkuserdone", "picto" => "user", "enabled" => "1", 'position' => 105, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
447 "priority" => array("type" => "smallint(6)", "label" => "Priority", "enabled" => "1", 'position' => 110, 'notnull' => 0, "visible" => "0",),
448 "fulldayevent" => array("type" => "smallint(6)", "label" => "Fulldayevent", "enabled" => "1", 'position' => 115, 'notnull' => 1, "visible" => "0",),
449 "location" => array("type" => "varchar(128)", "label" => "Location", "enabled" => "1", 'position' => 125, 'notnull' => 0, "visible" => "0",),
450 "max_participants" => array("type" => "integer", "label" => "MaxNbOfAttendees", "enabled" => "1", 'position' => 126, 'notnull' => 0, "visible" => "0",),
451 "durationp" => array("type" => "double", "label" => "Durationp", "enabled" => "1", 'position' => 130, 'notnull' => 0, "visible" => "0",),
452 "durationa" => array("type" => "double", "label" => "Durationa", "enabled" => "1", 'position' => 135, 'notnull' => 0, "visible" => "0",),
453 "fk_element" => array("type" => "integer", "label" => "LinkedObject", "enabled" => "getDolGlobalString('AGENDA_SHOW_LINKED_OBJECT')", 'position' => 145, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
454 "elementtype" => array("type" => "varchar(255)", "label" => "Elementtype", "enabled" => "1", 'position' => 150, 'notnull' => 0, "visible" => "0",),
455 "email_msgid" => array("type" => "varchar(256)", "label" => "Emailmsgid", "enabled" => "1", 'position' => 155, 'notnull' => 0, "visible" => "0",),
456 "email_subject" => array("type" => "varchar(256)", "label" => "Emailsubject", "enabled" => "1", 'position' => 160, 'notnull' => 0, "visible" => "0",),
457 "email_from" => array("type" => "varchar(256)", "label" => "Emailfrom", "enabled" => "1", 'position' => 165, 'notnull' => 0, "visible" => "0",),
458 "email_sender" => array("type" => "varchar(256)", "label" => "Emailsender", "enabled" => "1", 'position' => 170, 'notnull' => 0, "visible" => "0",),
459 "email_to" => array("type" => "varchar(256)", "label" => "Emailto", "enabled" => "1", 'position' => 175, 'notnull' => 0, "visible" => "0",),
460 "email_tocc" => array("type" => "varchar(256)", "label" => "Emailtocc", "enabled" => "1", 'position' => 180, 'notnull' => 0, "visible" => "0",),
461 "email_tobcc" => array("type" => "varchar(256)", "label" => "Emailtobcc", "enabled" => "1", 'position' => 185, 'notnull' => 0, "visible" => "0",),
462 "errors_to" => array("type" => "varchar(256)", "label" => "Errorsto", "enabled" => "1", 'position' => 190, 'notnull' => 0, "visible" => "0",),
463 "recurid" => array("type" => "varchar(128)", "label" => "Recurid", "enabled" => "1", 'position' => 195, 'notnull' => 0, "visible" => "0",),
464 "recurrule" => array("type" => "varchar(128)", "label" => "Recurrule", "enabled" => "1", 'position' => 200, 'notnull' => 0, "visible" => "0",),
465 "recurdateend" => array("type" => "datetime", "label" => "Recurdateend", "enabled" => "1", 'position' => 205, 'notnull' => 0, "visible" => "0",),
466 "import_key" => array("type" => "varchar(14)", "label" => "ImportId", "enabled" => "1", 'position' => 900, 'notnull' => 0, "visible" => "-1",),
467 "extraparams" => array("type" => "varchar(255)", "label" => "Extraparams", "enabled" => "1", 'position' => 215, 'notnull' => 0, "visible" => "0",),
468 "calling_duration" => array("type" => "integer", "label" => "Callingduration", "enabled" => "1", 'position' => 220, 'notnull' => 0, "visible" => "0",),
469 "visibility" => array("type" => "varchar(12)", "label" => "Visibility", "enabled" => "1", 'position' => 225, 'notnull' => 0, "visible" => "0",),
470 "reply_to" => array("type" => "varchar(255)", "label" => "Replyto", "enabled" => "1", 'position' => 230, 'notnull' => 0, "visible" => "0",),
471 "num_vote" => array("type" => "integer", "label" => "Numvote", "enabled" => "1", 'position' => 235, 'notnull' => 0, "visible" => "0",),
472 "event_paid" => array("type" => "smallint(6)", "label" => "Eventpaid", "enabled" => "1", 'position' => 240, 'notnull' => 1, "visible" => "0",),
473 "status" => array("type" => "smallint(6)", "label" => "Status", "enabled" => "1", 'position' => 500, 'notnull' => 1, "visible" => "0",),
474 "ip" => array("type" => "varchar(250)", "label" => "Ip", "enabled" => "1", 'position' => 250, 'notnull' => 0, "visible" => "0",),
475 "fk_bookcal_calendar" => array("type" => "integer", "label" => "Fkbookcalcalendar", "enabled" => "1", 'position' => 255, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
476 "fk_task" => array("type" => "integer", "label" => "Task", "picto" => "task", "enabled" => "1", 'position' => 260, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
477 "fk_user_author" => array("type" => "integer", "label" => "UserCreation", "picto" => "user", "enabled" => "1", 'position' => 505, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
478 "fk_user_mod" => array("type" => "integer", "label" => "UserModification", "picto" => "user", "enabled" => "1", 'position' => 506, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
479 "datec" => array("type" => "datetime", "label" => "DateCreation", "enabled" => "1", 'position' => 510, 'notnull' => 0, "visible" => "-1",),
480 "tms" => array("type" => "timestamp", "label" => "DateModification", "enabled" => "1", 'position' => 520, 'notnull' => 1, "visible" => "-1",),
481 "percent" => array("type" => "smallint(6)", "label" => "Status", "enabled" => "1", 'position' => 1000, 'notnull' => 1, "visible" => "1",), // status
482 );
483 // END MODULEBUILDER PROPERTIES
484
485
491 public function __construct(DoliDB $db)
492 {
493 $this->db = $db;
494
495 $this->ismultientitymanaged = 1;
496 }
497
506 public function create(User $user, $notrigger = 0)
507 {
508 global $langs, $conf;
509
510 $error = 0;
511 $now = dol_now();
512
513 // Check parameters
514 if (!isset($this->userownerid) || (string) $this->userownerid === '') { // $this->userownerid may be 0 (anonymous event) or > 0
515 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);
516 $this->errors[] = 'ErrorActionCommPropertyUserowneridNotDefined';
517 return -1;
518 }
519
520 // Clean parameters
521 $this->label = dol_trunc(trim($this->label), 128);
522 $this->location = (!empty($this->location) ? dol_trunc(trim($this->location), 128) : "");
523 $this->note_private = dol_htmlcleanlastbr(trim(empty($this->note_private) ? $this->note : $this->note_private));
524 if (empty($this->percentage)) {
525 $this->percentage = 0;
526 }
527 if (empty($this->priority) || !is_numeric($this->priority)) {
528 $this->priority = 0;
529 }
530 if (empty($this->fulldayevent)) {
531 $this->fulldayevent = 0;
532 }
533 if (empty($this->transparency)) {
534 $this->transparency = 0;
535 }
536 if ($this->percentage > 100) {
537 $this->percentage = 100;
538 }
539 if (empty($this->datep) && $this->datep != '0') { // We should not insert event in calendar without a start date
540 $this->datep = $now;
541 }
542 if (!empty($this->datep) && !empty($this->datef)) {
543 $this->durationp = ($this->datef - $this->datep); // deprecated
544 }
545 if (!empty($this->datep) && !empty($this->datef) && $this->datep > $this->datef) {
546 $this->datef = $this->datep;
547 }
548 if (!isset($this->fk_project) || $this->fk_project < 0) {
549 $this->fk_project = 0;
550 }
551 if (!isset($this->fk_task) || $this->fk_task < 0) {
552 $this->fk_task = 0;
553 }
554 // For backward compatibility
555 if ($this->elementtype == 'facture') {
556 $this->elementtype = 'invoice';
557 }
558 if ($this->elementtype == 'commande') {
559 $this->elementtype = 'order';
560 }
561 if ($this->elementtype == 'contrat') {
562 $this->elementtype = 'contract';
563 }
564 if (empty($this->fk_element) && !empty($this->elementid)) {
565 $this->fk_element = $this->elementid;
566 }
567 if (empty($this->elementid) && !empty($this->fk_element)) {
568 $this->elementid = $this->fk_element;
569 }
570
571 if (!is_array($this->userassigned) && !empty($this->userassigned)) { // For backward compatibility when userassigned was an int instead of an array
572 $tmpid = (int) $this->userassigned;
573 $this->userassigned = array();
574 $this->userassigned[$tmpid] = array('id' => $tmpid, 'transparency' => $this->transparency);
575 }
576
577 $userownerid = $this->userownerid;
578
579 // Be sure assigned user is defined as an array of array('id'=>,'mandatory'=>,...).
580 if (empty($this->userassigned) || count($this->userassigned) == 0 || !is_array($this->userassigned)) {
581 $this->userassigned = array($userownerid => array('id' => $userownerid, 'transparency' => $this->transparency));
582 }
583
584 if (!$this->type_id || !$this->type_code) {
585 $key = empty($this->type_id) ? $this->type_code : $this->type_id;
586
587 // Get id from code
588 $cactioncomm = new CActionComm($this->db);
589 $result = $cactioncomm->fetch($key);
590
591 if ($result > 0) {
592 $this->type_id = $cactioncomm->id;
593 $this->type_code = $cactioncomm->code;
594 } elseif ($result == 0) {
595 $this->error = $langs->trans('ErrorActionCommBadType', $this->type_id, $this->type_code);
596 return -1;
597 } else {
598 $this->error = $cactioncomm->error;
599 return -1;
600 }
601 }
602 $code = empty($this->code) ? $this->type_code : $this->code;
603
604 // Check parameters
605 if (!$this->type_id) {
606 $this->error = "ErrorWrongParameters";
607 return -1;
608 }
609
610 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
611 $extraparams = dol_trunc($extraparams, 250);
612
613 $this->db->begin();
614
615 $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm";
616 $sql .= "(ref,";
617 $sql .= "datec,";
618 $sql .= "datep,";
619 $sql .= "datep2,";
620 $sql .= "durationp,"; // deprecated
621 $sql .= "fk_action,";
622 $sql .= "code,";
623 $sql .= "ref_ext,";
624 $sql .= "fk_soc,";
625 $sql .= "fk_project,";
626 $sql .= "note,";
627 $sql .= "fk_contact,";
628 $sql .= "fk_user_author,";
629 $sql .= "fk_user_action,";
630 $sql .= "fk_task,";
631 $sql .= "label,percent,priority,fulldayevent,location,max_participants,";
632 $sql .= "transparency,";
633 $sql .= "fk_element,";
634 $sql .= "elementtype,";
635 $sql .= "fk_bookcal_calendar,";
636 $sql .= "entity,";
637 $sql .= "extraparams,";
638 // Fields emails
639 $sql .= "email_msgid,";
640 $sql .= "email_from,";
641 $sql .= "email_sender,";
642 $sql .= "email_to,";
643 $sql .= "email_tocc,";
644 $sql .= "email_tobcc,";
645 $sql .= "email_subject,";
646 $sql .= "errors_to,";
647 $sql .= "recurid,";
648 $sql .= "recurrule,";
649 $sql .= "recurdateend,";
650 $sql .= "num_vote,";
651 $sql .= "event_paid,";
652 $sql .= "status,";
653 $sql .= "ip";
654 $sql .= ") VALUES (";
655 $sql .= "'(PROV)', ";
656 $sql .= "'".$this->db->idate($now)."', "; // date creation
657 $sql .= "'".$this->db->idate($this->datep)."', "; // date start event
658 $sql .= (strval($this->datef) != '' ? "'".$this->db->idate($this->datef)."'" : "null").", ";
659 $sql .= ((isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '') ? "'".$this->db->escape((string) $this->durationp)."'" : "null").", "; // deprecated
660 $sql .= (isset($this->type_id) ? ((int) $this->type_id) : "null").",";
661 $sql .= ($code ? ("'".$this->db->escape($code)."'") : "null").", ";
662 $sql .= (!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").", ";
663 $sql .= ((isset($this->socid) && $this->socid > 0) ? ((int) $this->socid) : "null").", ";
664 $sql .= ((isset($this->fk_project) && $this->fk_project > 0) ? ((int) $this->fk_project) : "null").", ";
665 $sql .= " '".$this->db->escape($this->note_private)."', ";
666 $sql .= ((isset($this->contact_id) && $this->contact_id > 0) ? ((int) $this->contact_id) : "null").", "; // deprecated, use ->socpeopleassigned
667 $sql .= (isset($user->id) && $user->id > 0 ? ((int) $user->id) : "null").", ";
668 $sql .= ($userownerid > 0 ? ((int) $userownerid) : "null").", ";
669 $sql .= (!empty($this->fk_task) ? ((int) $this->fk_task) : "null").", ";
670 $sql .= "'".$this->db->escape($this->label)."', ";
671 $sql .= "'".$this->db->escape((string) $this->percentage)."', ";
672 $sql .= "'".$this->db->escape((string) $this->priority)."', ";
673 $sql .= "'".$this->db->escape((string) $this->fulldayevent)."', ";
674 $sql .= "'".$this->db->escape($this->location)."', ";
675 $sql .= (isset($this->max_participants) && $this->max_participants > 0 ? ((int) $this->max_participants) : "null").", ";
676 $sql .= "'".$this->db->escape((string) $this->transparency)."', ";
677 $sql .= (!empty($this->elementid) ? ((int) $this->elementid) : "null").", ";
678 $sql .= (!empty($this->elementtype) ? "'".$this->db->escape($this->elementtype)."'" : "null").", ";
679 $sql .= (!empty($this->fk_bookcal_calendar) ? "'".$this->db->escape((string) $this->fk_bookcal_calendar)."'" : "null").", ";
680 $sql .= ((int) $conf->entity).",";
681 $sql .= (!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null").", ";
682 // Fields emails
683 $sql .= (!empty($this->email_msgid) ? "'".$this->db->escape($this->email_msgid)."'" : "null").", ";
684 $sql .= (!empty($this->email_from) ? "'".$this->db->escape($this->email_from)."'" : "null").", ";
685 $sql .= (!empty($this->email_sender) ? "'".$this->db->escape($this->email_sender)."'" : "null").", ";
686 $sql .= (!empty($this->email_to) ? "'".$this->db->escape($this->email_to)."'" : "null").", ";
687 $sql .= (!empty($this->email_tocc) ? "'".$this->db->escape($this->email_tocc)."'" : "null").", ";
688 $sql .= (!empty($this->email_tobcc) ? "'".$this->db->escape($this->email_tobcc)."'" : "null").", ";
689 $sql .= (!empty($this->email_subject) ? "'".$this->db->escape($this->email_subject)."'" : "null").", ";
690 $sql .= (!empty($this->errors_to) ? "'".$this->db->escape($this->errors_to)."'" : "null").", ";
691 $sql .= (!empty($this->recurid) ? "'".$this->db->escape($this->recurid)."'" : "null").", ";
692 $sql .= (!empty($this->recurrule) ? "'".$this->db->escape($this->recurrule)."'" : "null").", ";
693 $sql .= (!empty($this->recurdateend) ? "'".$this->db->idate($this->recurdateend)."'" : "null").", ";
694 $sql .= (!empty($this->num_vote) ? (int) $this->num_vote : "null").", ";
695 $sql .= (!empty($this->event_paid) ? (int) $this->event_paid : 0).", ";
696 $sql .= (!empty($this->status) ? (int) $this->status : "0").", ";
697 $sql .= (!empty($this->ip) ? "'".$this->db->escape($this->ip)."'" : "null");
698 $sql .= ")";
699
700 dol_syslog(get_class($this)."::add", LOG_DEBUG);
701 $resql = $this->db->query($sql);
702 if ($resql) {
703 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."actioncomm", "id");
704 $this->ref = (string) $this->id;
705 $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm SET ref='".$this->db->escape($this->ref)."' WHERE id=".((int) $this->id);
706 $resql = $this->db->query($sql);
707 if (!$resql) {
708 $error++;
709 dol_syslog('Error to process ref: '.$this->db->lasterror(), LOG_ERR);
710 $this->errors[] = $this->db->lasterror();
711 }
712 // Now insert assigned users
713 if (!$error) {
714 //dol_syslog(var_export($this->userassigned, true));
715 $already_inserted = array();
716 foreach ($this->userassigned as $key => $val) {
717 // Common value with new behavior is to have $val = array('id'=>iduser, 'transparency'=>0|1) and $this->userassigned is an array of iduser => $val.
718 if (!is_array($val)) { // For backward compatibility when $val='id'.
719 $val = array('id' => $val);
720 }
721
722 if ($val['id'] > 0) {
723 if (!empty($already_inserted[$val['id']])) {
724 continue;
725 }
726
727 $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
728 $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'])).")";
729
730 $resql = $this->db->query($sql);
731 if (!$resql) {
732 $error++;
733 dol_syslog('Error to process userassigned: ' . $this->db->lasterror(), LOG_ERR);
734 $this->errors[] = $this->db->lasterror();
735 } else {
736 $already_inserted[$val['id']] = true;
737 }
738 //var_dump($sql);exit;
739 }
740 }
741 }
742
743 if (!$error) {
744 if (!empty($this->socpeopleassigned)) {
745 $already_inserted = array();
746 foreach ($this->socpeopleassigned as $id => $val) {
747 // Common value with new behavior is to have $this->socpeopleassigned an array of idcontact => dummyvalue
748 if (!empty($already_inserted[$id])) {
749 continue;
750 }
751
752 $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
753 $sql .= " VALUES(".((int) $this->id).", 'socpeople', ".((int) $id).", 0, 0, 0)";
754
755 $resql = $this->db->query($sql);
756 if (!$resql) {
757 $error++;
758 dol_syslog('Error to process socpeopleassigned: ' . $this->db->lasterror(), LOG_ERR);
759 $this->errors[] = $this->db->lasterror();
760 } else {
761 $already_inserted[$id] = true;
762 }
763 }
764 }
765 }
766
767 if (!$error) {
768 // Actions on extra fields
769 $result = $this->insertExtraFields();
770 if ($result < 0) {
771 $error++;
772 }
773 }
774
775 if (!$error && !$notrigger) {
776 // Call trigger
777 $result = $this->call_trigger('ACTION_CREATE', $user);
778 if ($result < 0) {
779 $error++;
780 }
781 // End call triggers
782 }
783
784 if (!$error) {
785 $this->db->commit();
786 return $this->id;
787 } else {
788 $this->db->rollback();
789 return -1;
790 }
791 } else {
792 $this->db->rollback();
793 $this->error = $this->db->lasterror();
794 return -1;
795 }
796 }
797
805 public function createFromClone(User $fuser, $socid)
806 {
807 global $hookmanager;
808
809 $error = 0;
810
811 $this->db->begin();
812
813 // Load source object
814 $objFrom = clone $this;
815
816 // Retrieve all extrafield
817 // fetch optionals attributes and labels
818 $this->fetch_optionals();
819
820 //$this->fetch_userassigned();
821 $this->fetchResources();
822
823 $this->id = 0;
824 $this->recurid = '';
825 $this->recurrule = '';
826 $this->recurdateend = '';
827
828 // Create clone
829 $this->context['createfromclone'] = 'createfromclone';
830 $result = $this->create($fuser);
831 if ($result < 0) {
832 $error++;
833 } else {
834 $resultcat = $this->cloneCategories($objFrom->id, $this->id);
835 if ($resultcat < 0) {
836 $error++;
837 }
838 }
839
840 if (!$error) {
841 // Hook of thirdparty module
842 if (is_object($hookmanager)) {
843 $parameters = array('objFrom' => $objFrom);
844 $action = '';
845 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
846 if ($reshook < 0) {
847 $this->setErrorsFromObject($hookmanager);
848 $error++;
849 }
850 }
851
852 // Call trigger
853 $result = $this->call_trigger('ACTION_CLONE', $fuser);
854 if ($result < 0) {
855 $error++;
856 }
857 // End call triggers
858 }
859
860 unset($this->context['createfromclone']);
861
862 // End
863 if (!$error) {
864 $this->db->commit();
865 return $this->id;
866 } else {
867 $this->db->rollback();
868 return -1;
869 }
870 }
871
882 public function fetch($id, $ref = '', $ref_ext = '', $email_msgid = '', $loadresources = 1)
883 {
884 if (empty($id) && empty($ref) && empty($ref_ext) && empty($email_msgid)) {
885 dol_syslog(get_class($this)."::fetch Bad parameters", LOG_WARNING);
886 return -1;
887 }
888
889 $sql = "SELECT a.id,";
890 $sql .= " a.ref as ref,";
891 $sql .= " a.entity,";
892 $sql .= " a.ref_ext,";
893 $sql .= " a.datep,";
894 $sql .= " a.datep2,";
895 $sql .= " a.durationp,"; // deprecated
896 $sql .= " a.datec,";
897 $sql .= " a.tms as datem,";
898 $sql .= " a.code, a.label, a.note as note_private,";
899 $sql .= " a.fk_soc,";
900 $sql .= " a.fk_project,";
901 $sql .= " a.fk_user_author, a.fk_user_mod,";
902 $sql .= " a.fk_user_action,";
903 $sql .= " a.fk_task,";
904 $sql .= " a.fk_contact, a.percent as percentage,";
905 $sql .= " a.fk_element as elementid, a.elementtype,";
906 $sql .= " a.priority, a.fulldayevent, a.location, a.max_participants, a.transparency,";
907 $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,";
908 $sql .= " a.recurid, a.recurrule, a.recurdateend,";
909 $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,";
910 $sql .= " s.nom as socname,";
911 $sql .= " u.firstname, u.lastname as lastname,";
912 $sql .= " num_vote, event_paid, a.status";
913 $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a ";
914 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action=c.id ";
915 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author";
916 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc";
917 $sql .= " WHERE ";
918 if ($ref) {
919 $sql .= " a.ref = '".$this->db->escape($ref)."'";
920 } elseif ($ref_ext) {
921 $sql .= " a.ref_ext = '".$this->db->escape($ref_ext)."'";
922 } elseif ($email_msgid) {
923 $sql .= " a.email_msgid = '".$this->db->escape($email_msgid)."'";
924 } else {
925 $sql .= " a.id = ".((int) $id);
926 }
927
928 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
929 $resql = $this->db->query($sql);
930 if ($resql) {
931 $num = $this->db->num_rows($resql);
932 if ($num) {
933 $obj = $this->db->fetch_object($resql);
934
935 $this->id = $obj->id;
936 $this->entity = $obj->entity;
937 $this->ref = $obj->ref;
938 $this->ref_ext = $obj->ref_ext;
939
940 // Properties of parent table llx_c_actioncomm
941 $this->type_id = $obj->type_id;
942 $this->type_code = $obj->type_code;
943 $this->type_color = $obj->type_color;
944 $this->type_picto = $obj->type_picto;
945 $this->type = $obj->type_type;
946 $this->type_label = $obj->type_label;
947
948 $this->code = $obj->code;
949 $this->label = $obj->label;
950 $this->datep = $this->db->jdate($obj->datep);
951 $this->datef = $this->db->jdate($obj->datep2);
952
953 $this->datec = $this->db->jdate($obj->datec);
954 $this->datem = $this->db->jdate($obj->datem);
955
956 $this->note = $obj->note_private; // deprecated
957 $this->note_private = $obj->note_private;
958 $this->percentage = $obj->percentage;
959
960 $this->authorid = $obj->fk_user_author;
961 $this->usermodid = $obj->fk_user_mod;
962
963 if (!is_object($this->author)) {
964 $this->author = new User($this->db); // To avoid warning
965 }
966 $this->author->id = $obj->fk_user_author; // deprecated
967 $this->author->firstname = $obj->firstname; // deprecated
968 $this->author->lastname = $obj->lastname; // deprecated
969 if (!is_object($this->usermod)) {
970 $this->usermod = new User($this->db); // To avoid warning
971 }
972 $this->usermod->id = $obj->fk_user_mod; // deprecated
973
974 $this->userownerid = $obj->fk_user_action;
975 $this->fk_task = $obj->fk_task;
976 $this->priority = $obj->priority;
977 $this->fulldayevent = $obj->fulldayevent;
978 $this->location = $obj->location;
979 $this->max_participants = $obj->max_participants;
980 $this->transparency = $obj->transparency;
981
982 $this->socid = $obj->fk_soc; // To have fetch_thirdparty method working
983 if (!empty($obj->socname)) {
984 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
985 $this->thirdparty = new Societe($this->db);
986 $this->thirdparty->id = $obj->fk_soc;
987 $this->thirdparty->name = $obj->socname;
988 }
989 $this->contact_id = $obj->fk_contact; // To have fetch_contact method working
990 $this->fk_project = $obj->fk_project; // To have fetch_projet method working
991
992 //$this->societe->id = $obj->fk_soc; // deprecated
993 //$this->contact->id = $obj->fk_contact; // deprecated
994
995 $this->fk_element = $obj->elementid;
996 $this->elementid = $obj->elementid;
997 $this->elementtype = $obj->elementtype;
998
999 $this->recurid = $obj->recurid;
1000 $this->recurrule = $obj->recurrule;
1001 $this->recurdateend = $this->db->jdate($obj->recurdateend);
1002
1003 $this->num_vote = $obj->num_vote;
1004 $this->event_paid = $obj->event_paid;
1005 $this->status = $obj->status;
1006
1007 //email information
1008 $this->email_msgid = $obj->email_msgid;
1009 $this->email_from = $obj->email_from;
1010 $this->email_sender = $obj->email_sender;
1011 $this->email_to = $obj->email_to;
1012 $this->email_tocc = $obj->email_tocc;
1013 $this->email_tobcc = $obj->email_tobcc;
1014 $this->email_subject = $obj->email_subject;
1015 $this->errors_to = $obj->errors_to;
1016
1017 $this->fetch_optionals();
1018
1019 if ($loadresources) {
1020 $this->fetchResources();
1021 }
1022 }
1023
1024 $this->db->free($resql);
1025 } else {
1026 $this->error = $this->db->lasterror();
1027 return -1;
1028 }
1029
1030 return $num;
1031 }
1032
1038 public function fetchResources()
1039 {
1040 $this->userassigned = array();
1041 $this->socpeopleassigned = array();
1042
1043 $sql = 'SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency';
1044 $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm_resources';
1045 $sql .= ' WHERE fk_actioncomm = '.((int) $this->id);
1046 $sql .= " AND element_type IN ('user', 'socpeople')";
1047 $resql = $this->db->query($sql);
1048 if ($resql) {
1049 // If owner is known, we must but id first into list
1050 if ($this->userownerid > 0) {
1051 $this->userassigned[$this->userownerid] = array('id' => $this->userownerid); // Set first so will be first into list.
1052 }
1053
1054 while ($obj = $this->db->fetch_object($resql)) {
1055 if ($obj->fk_element > 0) {
1056 switch ($obj->element_type) {
1057 case 'user':
1058 $this->userassigned[$obj->fk_element] = array('id' => $obj->fk_element, 'mandatory' => $obj->mandatory, 'answer_status' => $obj->answer_status, 'transparency' => $obj->transparency);
1059 if (empty($this->userownerid)) {
1060 $this->userownerid = $obj->fk_element; // If not defined (should not happened, we fix this)
1061 }
1062 break;
1063 case 'socpeople':
1064 $this->socpeopleassigned[$obj->fk_element] = array('id' => $obj->fk_element, 'mandatory' => $obj->mandatory, 'answer_status' => $obj->answer_status, 'transparency' => $obj->transparency);
1065 break;
1066 }
1067 }
1068 }
1069
1070 return 1;
1071 } else {
1072 dol_print_error($this->db);
1073 return -1;
1074 }
1075 }
1076
1077 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1084 public function fetch_userassigned($override = true)
1085 {
1086 // phpcs:enable
1087 $sql = "SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency";
1088 $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm_resources";
1089 $sql .= " WHERE element_type = 'user' AND fk_actioncomm = ".((int) $this->id);
1090
1091 $resql2 = $this->db->query($sql);
1092 if ($resql2) {
1093 $this->userassigned = array();
1094
1095 // If owner is known, we must but id first into list
1096 if ($this->userownerid > 0) {
1097 // Set first so will be first into list.
1098 $this->userassigned[$this->userownerid] = array('id' => $this->userownerid);
1099 }
1100
1101 while ($obj = $this->db->fetch_object($resql2)) {
1102 if ($obj->fk_element > 0) {
1103 $this->userassigned[$obj->fk_element] = array('id' => $obj->fk_element,
1104 'mandatory' => $obj->mandatory,
1105 'answer_status' => $obj->answer_status,
1106 'transparency' => $obj->transparency);
1107 }
1108
1109 if ($override === true) {
1110 // If not defined (should not happened, we fix this)
1111 if (empty($this->userownerid)) {
1112 $this->userownerid = $obj->fk_element;
1113 }
1114 }
1115 }
1116
1117 return 1;
1118 } else {
1119 dol_print_error($this->db);
1120 return -1;
1121 }
1122 }
1123
1131 public function delete($user, $notrigger = 0)
1132 {
1133 $error = 0;
1134
1135 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1136
1137 $this->db->begin();
1138
1139 // remove categorie association
1140 if (!$error) {
1141 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_actioncomm";
1142 $sql .= " WHERE fk_actioncomm=".((int) $this->id);
1143
1144 $res = $this->db->query($sql);
1145 if (!$res) {
1146 $this->error = $this->db->lasterror();
1147 $error++;
1148 }
1149 }
1150
1151 // remove actioncomm_resources
1152 if (!$error) {
1153 $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources";
1154 $sql .= " WHERE fk_actioncomm=".((int) $this->id);
1155
1156 $res = $this->db->query($sql);
1157 if (!$res) {
1158 $this->error = $this->db->lasterror();
1159 $error++;
1160 }
1161 }
1162
1163 if (!$error) {
1164 $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
1165 $sql .= " WHERE fk_actioncomm = ".((int) $this->id);
1166
1167 $res = $this->db->query($sql);
1168 if (!$res) {
1169 $this->error = $this->db->lasterror();
1170 $error++;
1171 }
1172 }
1173
1174 // Removed extrafields
1175 if (!$error) {
1176 $result = $this->deleteExtraFields();
1177 if ($result < 0) {
1178 $error++;
1179 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1180 }
1181 }
1182
1183 // remove actioncomm
1184 if (!$error) {
1185 $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm";
1186 $sql .= " WHERE id=".((int) $this->id);
1187
1188 $res = $this->db->query($sql);
1189 if (!$res) {
1190 $this->error = $this->db->lasterror();
1191 $error++;
1192 }
1193 }
1194
1195 if (!$error) {
1196 if (!$notrigger) {
1197 // Call trigger
1198 $result = $this->call_trigger('ACTION_DELETE', $user);
1199 if ($result < 0) {
1200 $error++;
1201 }
1202 // End call triggers
1203 }
1204
1205 if (!$error) {
1206 $this->db->commit();
1207 return 1;
1208 } else {
1209 $this->db->rollback();
1210 return -2;
1211 }
1212 } else {
1213 $this->db->rollback();
1214 $this->error = $this->db->lasterror();
1215 return -1;
1216 }
1217 }
1218
1227 public function update(User $user, $notrigger = 0)
1228 {
1229 $error = 0;
1230
1231 // Clean parameters
1232 $this->label = trim($this->label);
1233 $this->note_private = dol_htmlcleanlastbr(trim(!isset($this->note_private) ? $this->note : $this->note_private));
1234 if (empty($this->percentage)) {
1235 $this->percentage = 0;
1236 }
1237 if (empty($this->priority) || !is_numeric($this->priority)) {
1238 $this->priority = 0;
1239 }
1240 if (empty($this->transparency)) {
1241 $this->transparency = 0;
1242 }
1243 if (empty($this->fulldayevent)) {
1244 $this->fulldayevent = 0;
1245 }
1246 if ($this->percentage > 100) {
1247 $this->percentage = 100;
1248 }
1249 //if ($this->percentage == 100 && ! $this->dateend) $this->dateend = $this->date;
1250 if ($this->datep && $this->datef) {
1251 $this->durationp = ($this->datef - $this->datep); // deprecated
1252 }
1253 //if ($this->date && $this->dateend) $this->durationa=($this->dateend - $this->date);
1254 if ($this->datep && $this->datef && $this->datep > $this->datef) {
1255 $this->datef = $this->datep;
1256 }
1257 //if ($this->date && $this->dateend && $this->date > $this->dateend) $this->dateend=$this->date;
1258 if ($this->fk_project < 0) {
1259 $this->fk_project = 0;
1260 }
1261
1262 $socid = (($this->socid > 0) ? $this->socid : 0);
1263 $contactid = (($this->contact_id > 0) ? $this->contact_id : 0);
1264 $userownerid = ($this->userownerid ? $this->userownerid : 0);
1265
1266 // If a type_id is set, we must also have the type_code set
1267 if ($this->type_id > 0) {
1268 if (empty($this->type_code)) {
1269 $cactioncomm = new CActionComm($this->db);
1270 $result = $cactioncomm->fetch($this->type_id);
1271 if ($result >= 0 && !empty($cactioncomm->code)) {
1272 $this->type_code = $cactioncomm->code;
1273 }
1274 }
1275 }
1276
1277 $code = $this->code;
1278 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
1279 $code = $this->type_code;
1280 }
1281
1282 $this->db->begin();
1283
1284 $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm";
1285 $sql .= " SET percent = '".$this->db->escape((string) $this->percentage)."'";
1286 $sql .= ", fk_action = ".(int) $this->type_id;
1287 $sql .= ", code = " . ($code ? "'".$this->db->escape($code)."'" : "null");
1288 $sql .= ", label = ".($this->label ? "'".$this->db->escape($this->label)."'" : "null");
1289 $sql .= ", datep = ".(strval($this->datep) != '' ? "'".$this->db->idate($this->datep)."'" : 'null');
1290 $sql .= ", datep2 = ".(strval($this->datef) != '' ? "'".$this->db->idate($this->datef)."'" : 'null');
1291 $sql .= ", durationp = ".(isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '' ? "'".$this->db->escape((string) $this->durationp)."'" : "null"); // deprecated
1292 $sql .= ", note = '".$this->db->escape($this->note_private)."'";
1293 $sql .= ", fk_project =".($this->fk_project > 0 ? ((int) $this->fk_project) : "null");
1294 $sql .= ", fk_soc =".($socid > 0 ? ((int) $socid) : "null");
1295 $sql .= ", fk_contact =".($contactid > 0 ? ((int) $contactid) : "null");
1296 $sql .= ", priority = '".$this->db->escape((string) $this->priority)."'";
1297 $sql .= ", fulldayevent = '".$this->db->escape((string) $this->fulldayevent)."'";
1298 $sql .= ", location = ".($this->location ? "'".$this->db->escape($this->location)."'" : "null");
1299 $sql .= ", max_participants = ".(isset($this->max_participants) && $this->max_participants > 0 ? ((int) $this->max_participants) : "null");
1300 $sql .= ", transparency = '".$this->db->escape((string) $this->transparency)."'";
1301 $sql .= ", fk_user_mod = ".((int) $user->id);
1302 $sql .= ", fk_user_action = ".($userownerid > 0 ? ((int) $userownerid) : "null");
1303 $sql .= ", fk_task = ".(!empty($this->fk_task) ? ((int) $this->fk_task) : "null");
1304 if (!empty($this->fk_element)) {
1305 $sql .= ", fk_element=".($this->fk_element ? ((int) $this->fk_element) : "null");
1306 }
1307 if (!empty($this->elementtype)) {
1308 $sql .= ", elementtype=".($this->elementtype ? "'".$this->db->escape($this->elementtype)."'" : "null");
1309 }
1310 if (!empty($this->num_vote)) {
1311 $sql .= ", num_vote=".($this->num_vote ? (int) $this->num_vote : null);
1312 }
1313 if (!empty($this->event_paid)) {
1314 $sql .= ", event_paid=".($this->event_paid ? (int) $this->event_paid : 0);
1315 }
1316 if (!empty($this->status)) {
1317 $sql .= ", status=".($this->status ? (int) $this->status : 0);
1318 }
1319 $sql .= " WHERE id=".((int) $this->id);
1320
1321 dol_syslog(get_class($this)."::update", LOG_DEBUG);
1322 if ($this->db->query($sql)) {
1323 $action = 'update';
1324
1325 // Actions on extra fields
1326 if (!$error) {
1327 $result = $this->insertExtraFields();
1328 if ($result < 0) {
1329 $error++;
1330 }
1331 }
1332
1333 // Now insert assignedusers
1334 if (!$error) {
1335 $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources where fk_actioncomm = ".((int) $this->id)." AND element_type = 'user'";
1336 $resql = $this->db->query($sql);
1337
1338 $already_inserted = array();
1339 foreach ($this->userassigned as $key => $val) {
1340 if (!is_array($val)) { // For backward compatibility when val=id
1341 $val = array('id' => $val);
1342 }
1343 if (!isset($val['id']) || !is_scalar($val['id'])) {
1344 continue;
1345 }
1346 if (!empty($already_inserted[$val['id']])) {
1347 continue;
1348 }
1349
1350 $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
1351 $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'])).")";
1352
1353 $resql = $this->db->query($sql);
1354 if (!$resql) {
1355 $error++;
1356 $this->errors[] = $this->db->lasterror();
1357 } else {
1358 $already_inserted[$val['id']] = true;
1359 }
1360 //var_dump($sql);exit;
1361 }
1362 }
1363
1364 if (!$error) {
1365 $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources where fk_actioncomm = ".((int) $this->id)." AND element_type = 'socpeople'";
1366 $resql = $this->db->query($sql);
1367
1368 if (!empty($this->socpeopleassigned)) {
1369 $already_inserted = array();
1370 foreach ($this->socpeopleassigned as $val) {
1371 if (!is_array($val)) { // For backward compatibility when val=id
1372 $val = array('id' => $val);
1373 }
1374 if (!empty($already_inserted[$val['id']])) {
1375 continue;
1376 }
1377
1378 $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)";
1379 $sql .= " VALUES(".((int) $this->id).", 'socpeople', ".((int) $val['id']).", 0, 0, 0)";
1380
1381 $resql = $this->db->query($sql);
1382 if (!$resql) {
1383 $error++;
1384 $this->errors[] = $this->db->lasterror();
1385 } else {
1386 $already_inserted[$val['id']] = true;
1387 }
1388 }
1389 }
1390 }
1391
1392 if (!$error && !$notrigger) {
1393 // Call trigger
1394 $result = $this->call_trigger('ACTION_MODIFY', $user);
1395 if ($result < 0) {
1396 $error++;
1397 }
1398 // End call triggers
1399 }
1400
1401 if (!$error) {
1402 $this->db->commit();
1403 return 1;
1404 } else {
1405 $this->db->rollback();
1406 dol_syslog(get_class($this)."::update ".implode(',', $this->errors), LOG_ERR);
1407 return -2;
1408 }
1409 } else {
1410 $this->db->rollback();
1411 $this->error = $this->db->lasterror();
1412 return -1;
1413 }
1414 }
1415
1426 public function checkResourceConflicts($newdatep, $newdatef)
1427 {
1428 if (!getDolGlobalString('RESOURCE_USED_IN_EVENT_CHECK') || $this->element != 'action') {
1429 return array();
1430 }
1431
1432 $sql = "SELECT er.rowid, r.ref as r_ref, ac.id as ac_id, ac.label as ac_label";
1433 $sql .= " FROM ".MAIN_DB_PREFIX."element_resources as er";
1434 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."resource as r ON r.rowid = er.resource_id AND er.resource_type = 'dolresource'";
1435 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm as ac ON ac.id = er.element_id AND er.element_type = '".$this->db->escape($this->element)."'";
1436 $sql .= " WHERE ac.id <> ".((int) $this->id);
1437 $sql .= " AND er.resource_id IN (";
1438 $sql .= " SELECT resource_id FROM ".MAIN_DB_PREFIX."element_resources";
1439 $sql .= " WHERE element_id = ".((int) $this->id);
1440 $sql .= " AND element_type = '".$this->db->escape($this->element)."'";
1441 $sql .= " AND busy = 1";
1442 $sql .= ")";
1443 $sql .= " AND er.busy = 1";
1444 $sql .= " AND (";
1445 $sql .= " (ac.datep <= '".$this->db->idate($newdatep)."' AND (ac.datep2 IS NULL OR ac.datep2 >= '".$this->db->idate($newdatep)."'))";
1446 if (!empty($newdatef)) {
1447 $sql .= " OR (ac.datep <= '".$this->db->idate($newdatef)."' AND (ac.datep2 >= '".$this->db->idate($newdatef)."'))";
1448 }
1449 $sql .= " OR (";
1450 $sql .= "ac.datep >= '".$this->db->idate($newdatep)."'";
1451 if (!empty($newdatef)) {
1452 $sql .= " AND (ac.datep2 IS NOT NULL AND ac.datep2 <= '".$this->db->idate($newdatef)."')";
1453 }
1454 $sql .= ")";
1455 $sql .= ")";
1456
1457 $resql = $this->db->query($sql);
1458 if (!$resql) {
1459 $this->error = $this->db->lasterror();
1460 return -1;
1461 }
1462
1463 $conflicts = array();
1464 while ($obj = $this->db->fetch_object($resql)) {
1465 $conflicts[] = array('r_ref' => $obj->r_ref, 'ac_id' => (int) $obj->ac_id, 'ac_label' => $obj->ac_label);
1466 }
1467 $this->db->free($resql);
1468
1469 return $conflicts;
1470 }
1471
1480 public function formatResourceConflicts($conflicts, $langs)
1481 {
1482 $message = $langs->trans('ErrorResourcesAlreadyInUse').' : ';
1483 foreach ($conflicts as $conflict) {
1484 $message .= '<br> - '.$langs->trans('ErrorResourceUseInEvent', $conflict['r_ref'], $conflict['ac_label'].' ['.$conflict['ac_id'].']');
1485 }
1486 return $message;
1487 }
1488
1503 public function getActions($socid = 0, $fk_element = 0, $elementtype = '', $sqlfilter = '', $sortfield = 'a.datep', $sortorder = 'DESC', $limit = 0)
1504 {
1505 global $hookmanager;
1506
1507 $resarray = array();
1508
1509 dol_syslog(get_class($this)."::getActions", LOG_DEBUG);
1510
1511 // Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
1512 if (!is_object($hookmanager)) {
1513 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
1514 $hookmanager = new HookManager($this->db);
1515 }
1516 $hookmanager->initHooks(array('agendadao'));
1517
1518 $sql = "SELECT a.id";
1519 if ($elementtype == 'user') {
1520 $sql .= ",a.datep";
1521 }
1522 $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
1523 // Fields from hook
1524 $parameters = array('sql' => &$sql, 'socid' => $socid, 'fk_element' => $fk_element, 'elementtype' => $elementtype);
1525 $reshook = $hookmanager->executeHooks('getActionsListFrom', $parameters); // Note that $action and $object may have been modified by hook
1526 if (!empty($hookmanager->resPrint)) {
1527 $sql .= $hookmanager->resPrint;
1528 }
1529 $sql .= " WHERE a.entity IN (".getEntity('agenda').")";
1530 if (!empty($socid)) {
1531 $sql .= " AND a.fk_soc = ".((int) $socid);
1532 }
1533 if (!empty($elementtype)) {
1534 if ($elementtype == 'project') {
1535 $sql .= ' AND a.fk_project = '.((int) $fk_element);
1536 } elseif ($elementtype == 'contact') {
1537 $sql .= ' AND EXISTS';
1538 $sql .= " (SELECT r.rowid FROM ".MAIN_DB_PREFIX."actioncomm_resources as r WHERE";
1539 $sql .= " r.element_type = 'socpeople' AND r.fk_element = ".((int) $fk_element).' AND r.fk_actioncomm = a.id)';
1540 } elseif ($elementtype == 'user') {
1541 $sql1 = $sql;
1542 $sql .= " AND a.fk_user_action = ".((int) $fk_element);
1543 $sql = "SELECT a.id FROM ((" . $sql . ") UNION (" . $sql1;
1544 $sql .= " AND EXISTS (SELECT r.rowid FROM ".MAIN_DB_PREFIX."actioncomm_resources as r WHERE";
1545 $sql .= " r.element_type = 'user' AND r.fk_element = ".((int) $fk_element).' AND r.fk_actioncomm = a.id)';
1546 $sql .= " AND a.fk_user_action <> ".((int) $fk_element);
1547 $sql .= ")) as a";
1548 } else {
1549 $sql .= " AND a.fk_element = ".((int) $fk_element)." AND a.elementtype = '".$this->db->escape($elementtype)."'";
1550 }
1551 }
1552 if (!empty($sqlfilter)) {
1553 $sql .= $sqlfilter;
1554 }
1555 // Fields where hook
1556 $parameters = array('sql' => &$sql, 'socid' => $socid, 'fk_element' => $fk_element, 'elementtype' => $elementtype);
1557 $reshook = $hookmanager->executeHooks('getActionsListWhere', $parameters); // Note that $action and $object may have been modified by hook
1558 if (!empty($hookmanager->resPrint)) {
1559 $sql .= $hookmanager->resPrint;
1560 }
1561 if ($sortorder && $sortfield) {
1562 $sql .= $this->db->order($sortfield, $sortorder);
1563 }
1564 $sql .= $this->db->plimit($limit, 0);
1565
1566 $resql = $this->db->query($sql);
1567 if ($resql) {
1568 $num = $this->db->num_rows($resql);
1569
1570 if ($num) {
1571 for ($i = 0; $i < $num; $i++) {
1572 $obj = $this->db->fetch_object($resql);
1573 $actioncommstatic = new ActionComm($this->db);
1574 $actioncommstatic->fetch($obj->id);
1575 $resarray[$i] = $actioncommstatic;
1576 }
1577 }
1578 $this->db->free($resql);
1579 return $resarray;
1580 } else {
1581 return $this->db->lasterror();
1582 }
1583 }
1584
1585 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1593 public function load_board($user, $load_state_board = 0)
1594 {
1595 // phpcs:enable
1596 global $conf, $langs;
1597
1598 if (empty($load_state_board)) {
1599 // The count and the number of late events are computed by the database instead of reading every event to do. An event
1600 // is late when it has a date and that date is before now minus the warning delay (the rule of hasDelay()).
1601 $sql = "SELECT COUNT(a.id) as nb,";
1602 $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";
1603 } else {
1604 $this->nb = array();
1605 $sql = "SELECT count(a.id) as nb";
1606 }
1607 $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
1608 if (!$user->hasRight('agenda', 'allactions', 'read')) {
1609 $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);
1610 }
1611 $sql .= " WHERE 1 = 1";
1612 if (empty($load_state_board)) {
1613 $sql .= " AND a.percent >= 0 AND a.percent < 100";
1614 }
1615 $sql .= " AND a.entity IN (".getEntity('agenda').")";
1616 if (!$user->hasRight('agenda', 'allactions', 'read')) {
1617 $sql .= " AND (a.fk_user_author = ".((int) $user->id)." OR a.fk_user_action = ".((int) $user->id);
1618 $sql .= " OR ar.fk_element = ".((int) $user->id);
1619 $sql .= ")";
1620 }
1621 // If the internal user must only see his customers, force searching by him
1622 $search_sale = 0;
1623 if (!$user->hasRight('societe', 'client', 'voir')) {
1624 $search_sale = $user->id;
1625 }
1626 // Search on sale representative
1627 if ($search_sale && $search_sale != '-1') {
1628 if ($search_sale == -2) {
1629 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = a.fk_soc)";
1630 } elseif ($search_sale > 0) {
1631 $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)."))";
1632 }
1633 }
1634
1635 $resql = $this->db->query($sql);
1636 if ($resql) {
1637 $response = null; // Ensure the variable is defined
1638 if (empty($load_state_board)) {
1639 $response = new WorkboardResponse();
1640 $response->warning_delay = $conf->agenda->warning_delay / 60 / 60 / 24;
1641 $response->label = $langs->trans("ActionsToDo");
1642 $response->labelShort = $langs->trans("ActionsToDoShort");
1643 $response->url = DOL_URL_ROOT.'/comm/action/list.php?mode=show_list&actioncode=0&status=todo&mainmenu=agenda';
1644 if ($user->hasRight("agenda", "allactions", "read")) {
1645 $response->url .= '&filtert=-1';
1646 }
1647 $response->img = img_object('', "action", 'class="inline-block valigntextmiddle"');
1648
1649 $obj = $this->db->fetch_object($resql);
1650 if ($obj) {
1651 $response->nbtodo = (int) $obj->nb;
1652 $response->nbtodolate = (int) $obj->nblate;
1653 }
1654 } else {
1655 $obj = $this->db->fetch_object($resql);
1656 if ($obj) {
1657 $this->nb["actionscomm"] = $obj->nb;
1658 }
1659 }
1660
1661 $this->db->free($resql);
1662 if (empty($load_state_board) && $response instanceof WorkboardResponse) {
1663 return $response;
1664 } else {
1665 return 1;
1666 }
1667 } else {
1668 dol_print_error($this->db);
1669 $this->error = $this->db->error();
1670 return -1;
1671 }
1672 }
1673
1674
1681 public function info($id)
1682 {
1683 $sql = 'SELECT ';
1684 $sql .= ' a.id,';
1685 $sql .= ' datec,';
1686 $sql .= ' tms as datem,';
1687 $sql .= ' fk_user_author,';
1688 $sql .= ' fk_user_mod';
1689 $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm as a';
1690 $sql .= ' WHERE a.id = '.((int) $id);
1691
1692 dol_syslog(get_class($this)."::info", LOG_DEBUG);
1693 $result = $this->db->query($sql);
1694 if ($result) {
1695 if ($this->db->num_rows($result)) {
1696 $obj = $this->db->fetch_object($result);
1697
1698 $this->id = $obj->id;
1699
1700 $this->user_creation_id = $obj->fk_user_author;
1701 $this->user_modification_id = $obj->fk_user_mod;
1702 $this->date_creation = $this->db->jdate($obj->datec);
1703 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
1704 }
1705 $this->db->free($result);
1706 } else {
1707 dol_print_error($this->db);
1708 }
1709 }
1710
1711
1719 public function getLibStatut($mode, $hidenastatus = 0)
1720 {
1721 return $this->LibStatut($this->percentage, $mode, $hidenastatus, $this->datep);
1722 }
1723
1724 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1734 public function LibStatut($percent, $mode, $hidenastatus = 0, $datestart = '')
1735 {
1736 // phpcs:enable
1737 global $langs;
1738
1739 $labelStatus = $langs->transnoentitiesnoconv('StatusNotApplicable');
1740 if ($percent == -1 && !$hidenastatus) {
1741 $labelStatus = $langs->transnoentitiesnoconv('StatusNotApplicable');
1742 } elseif ($percent == 0) {
1743 $labelStatus = $langs->transnoentitiesnoconv('StatusActionToDo').' (0%)';
1744 } elseif ($percent > 0 && $percent < 100) {
1745 $labelStatus = $langs->transnoentitiesnoconv('StatusActionInProcess').' ('.$percent.'%)';
1746 } elseif ($percent >= 100) {
1747 $labelStatus = $langs->transnoentitiesnoconv('StatusActionDone').' (100%)';
1748 }
1749
1750 $labelStatusShort = $langs->transnoentitiesnoconv('StatusNotApplicable');
1751 if ($percent == -1 && !$hidenastatus) {
1752 $labelStatusShort = $langs->trans('NA');
1753 } elseif ($percent == 0) {
1754 $labelStatusShort = '0%';
1755 } elseif ($percent > 0 && $percent < 100) {
1756 $labelStatusShort = $percent.'%';
1757 } elseif ($percent >= 100) {
1758 $labelStatusShort = '100%';
1759 }
1760
1761 $statusType = 'status9';
1762 if ($percent == -1 && !$hidenastatus) {
1763 $statusType = 'status9';
1764 }
1765 if ($percent == 0) {
1766 $statusType = 'status1';
1767 }
1768 if ($percent > 0 && $percent < 100) {
1769 $statusType = 'status3';
1770 }
1771 if ($percent >= 100) {
1772 $statusType = 'status6';
1773 }
1774
1775 $params = array('badgeParams' => array('attr' => array('title' => '<b>'.$langs->trans("Progression").'</b> : '.$labelStatus)));
1776
1777 return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode, '', $params);
1778 }
1779
1786 public function getTooltipContentArray($params)
1787 {
1788 global $langs, $form;
1789
1790 $langs->load('agenda');
1791
1792 $datas = array();
1793 $nofetch = !empty($params['nofetch']);
1794
1795 // Set label of type
1796 $labeltype = '';
1797 if ($this->type_code) {
1798 $langs->load("commercial");
1799 $labeltype = ($langs->transnoentities("Action".$this->type_code) != "Action".$this->type_code) ? $langs->transnoentities("Action".$this->type_code) : $this->type_label;
1800 }
1801 if (!getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
1802 if ($this->type_code != 'AC_OTH_AUTO') {
1803 $labeltype = $langs->trans('ActionAC_MANUAL');
1804 }
1805 }
1806 $datas['picto'] = img_picto('', $this->picto).' <u>'.$langs->trans('Action').'</u>';
1807 if (!empty($this->ref)) {
1808 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.dol_escape_htmltag($this->ref);
1809 }
1810 $translatedlabel = $this->getTranslatedLabel();
1811 if (!empty($translatedlabel)) {
1812 $datas['title'] = '<br><b>'.$langs->trans('Title').':</b> '.dol_escape_htmltag($translatedlabel);
1813 }
1814 if (!empty($labeltype)) {
1815 $datas['labeltype'] = '<br><b>'.$langs->trans('Type').':</b> '.dol_escape_htmltag($labeltype);
1816 }
1817 if (!empty($this->location)) {
1818 $datas['location'] = '<br><b>'.$langs->trans('Location').':</b> '.dol_escape_htmltag($this->location);
1819 }
1820 if (isset($this->transparency) && $this->datef && $this->datep != $this->datef && isset($this->transparency)) {
1821 $datas['transparency'] = '<br><b>'.$langs->trans('Busy').':</b> '.yn($this->transparency);
1822 }
1823
1824 $datas['date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->datep, 'dayhourreduceformat', 'tzuserrel');
1825 if ($this->datef) {
1826 $tmpa = dol_getdate($this->datep);
1827 $tmpb = dol_getdate($this->datef);
1828 if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) {
1829 if ($tmpa['hours'] != $tmpb['hours'] || $tmpa['minutes'] != $tmpb['minutes']) {
1830 $datas['date'] .= '-'.dol_print_date($this->datef, 'hour', 'tzuserrel');
1831 }
1832 } else {
1833 $datas['date'] .= '-'.dol_print_date($this->datef, 'dayhourreduceformat', 'tzuserrel');
1834 }
1835 }
1836
1837 if (!empty($this->recurid)) {
1838 $datas['recurring'] = '<br><b>'.$langs->trans("RecurringEvent").':</b> ';
1839 $datas['recurring'] .= img_picto($langs->trans("EventPartOfARecurringSerie", $this->recurid), 'recurring', 'class="pictofixedwidth"');
1840 $reg = array();
1841 if (preg_match('/FREQ=MONTHLY_BYMONTHDAY(\d+)/', $this->recurrule, $reg)) {
1842 $datas['recurring'] .= $langs->trans("EveryMonth").' <span class="opacitymedium small">('.$langs->trans("DayOfMonth").' '.$reg[1].' - '.$langs->trans("Until").' '.dol_print_date($this->recurdateend, 'day').')</span>';
1843 }
1844 }
1845
1846 if (!empty($this->email_msgid)) {
1847 $langs->load("mails");
1848 $datas['space'] = '<br>';
1849 // $datas['email'] = '<br><b>'.img_picto('', 'email').' '.$langs->trans("Email").'</b>';
1850 $datas['mailtopic'] = '<br><b>'.$langs->trans('MailTopic').':</b> '.dol_escape_htmltag($this->email_subject);
1851 $datas['mailfrom'] = '<br><b>'.$langs->trans('MailFrom').':</b> '.dol_htmlentities($this->email_from);
1852 $datas['mailto'] = '<br><b>'.$langs->trans('MailTo').':</b> '.dol_htmlentities($this->email_to);
1853 if (!empty($this->email_tocc)) {
1854 $datas['mailcc'] = '<br><b>'.$langs->trans('MailCC').':</b> '.dol_htmlentities($this->email_tocc);
1855 }
1856 /* Disabled because bcc must remain by definition not visible
1857 if (!empty($this->email_tobcc)) {
1858 $datas['mailccc'] = '<br><b>'.$langs->trans('MailCCC').':</b> '.$this->email_tobcc;
1859 } */
1860 }
1861 if (!empty($this->note_private)) {
1862 $datas['description'] = '<br><hr>';
1863 // Try to limit length of content
1864 $texttoshow = dolGetFirstLineOfText($this->note_private, 10);
1865 // Restrict height of content into the tooltip
1866 $datas['note'] = '<div class="tenlinesmax">';
1867 $datas['note'] .= (dol_textishtml($texttoshow) ? str_replace(array("\r", "\n"), "", $texttoshow) : str_replace(array("\r", "\n"), '<br>', $texttoshow));
1868 $datas['note'] .= '</div>';
1869 }
1870
1871 // show categories for this record only in ajax to not overload lists
1872 if (isModEnabled('category') && !$nofetch) {
1873 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
1874 if (empty($form)) {
1875 include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
1876 $form = new Form($this->db);
1877 }
1878 $tmpcategstring = $form->showCategories($this->id, Categorie::TYPE_ACTIONCOMM, 1);
1879 if ($tmpcategstring) {
1880 $datas['categories'] = '<br>'.$tmpcategstring;
1881 }
1882 }
1883
1884 return $datas;
1885 }
1886
1900 public function getNomUrl($withpicto = 0, $maxlength = 0, $morecss = '', $option = '', $overwritepicto = 0, $notooltip = 0, $save_lastsearch_value = -1)
1901 {
1902 global $conf, $langs, $user, $hookmanager, $action;
1903
1904 if (!empty($conf->dol_no_mouse_hover)) {
1905 $notooltip = 1; // Force disable tooltips
1906 }
1907
1908 $canread = 0;
1909 if ($user->hasRight('agenda', 'myactions', 'read') && ($this->authorid == $user->id || $this->userownerid == $user->id)) {
1910 $canread = 1; // Can read my event
1911 }
1912 if ($user->hasRight('agenda', 'myactions', 'read') && array_key_exists($user->id, $this->userassigned)) {
1913 $canread = 1; // Can read my event i am assigned
1914 }
1915 if ($user->hasRight('agenda', 'allactions', 'read')) {
1916 $canread = 1; // Can read all event of other
1917 }
1918 if (!$canread) {
1919 $option = 'nolink';
1920 }
1921
1922 $label = $this->getTranslatedLabel();
1923
1924 $result = '';
1925
1926 // Set label of type
1927 $labeltype = $this->getTypeLabel(1);
1928
1929 $linkclose = '';
1930
1931 $params = [
1932 'id' => (string) $this->id,
1933 'objecttype' => $this->element.($this->module ? '@'.$this->module : ''),
1934 'option' => $option,
1935 'nofetch' => 1,
1936 ];
1937 $classfortooltip = 'classfortooltip';
1938 $dataparams = '';
1939 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1940 $classfortooltip = 'classforajaxtooltip';
1941 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1942 //$label = ''; // $label is used as ref when $maxlength is not negative, so we must not empty it.
1943 } else {
1944 $label = implode($this->getTooltipContentArray($params));
1945 }
1946
1947 if (empty($notooltip)) {
1948 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1949 $label = $langs->trans("ShowAction");
1950 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1951 }
1952 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
1953 $linkclose .= $dataparams.' class="'.$morecss.' '.$classfortooltip.'"';
1954 } else {
1955 $linkclose .= ' class="'.$morecss.'"';
1956 }
1957
1958 $query = ['id' => $this->id];
1959 if ($option == 'birthday') {
1960 $baseurl = DOL_URL_ROOT.'/contact/perso.php';
1961 } elseif ($option == 'holiday') {
1962 $baseurl = DOL_URL_ROOT.'/holiday/card.php';
1963 } else {
1964 $baseurl = DOL_URL_ROOT.'/comm/action/card.php';
1965 }
1966
1967 if ($option !== 'nolink') {
1968 // Add param to save lastsearch_values or not
1969 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1970 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1971 $add_save_lastsearch_values = 1;
1972 }
1973 if ($add_save_lastsearch_values) {
1974 $query += ['save_lastsearch_values' => 1];
1975 }
1976 }
1977 $url = dolBuildUrl($baseurl, $query);
1978
1979 $linkstart = '<a href="'.$url.'"';
1980 $linkstart .= $linkclose.'>';
1981 $linkend = '</a>';
1982
1983 if ($option == 'nolink') {
1984 $linkstart = '';
1985 $linkend = '';
1986 }
1987
1988 if ($withpicto == 2) {
1989 if (getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
1990 $label = $labeltype;
1991 }
1992 $labelshort = '';
1993 } else {
1994 if (getDolGlobalString('AGENDA_USE_EVENT_TYPE') && empty($label)) {
1995 if (empty($this->label)) {
1996 $label = $labeltype;
1997 } else {
1998 $label = $this->getTranslatedLabel();
1999 }
2000 }
2001 if ($maxlength < 0) {
2002 $labelshort = $this->ref;
2003 } else {
2004 $labelshort = dol_trunc(empty($label) ? $labeltype : $label, $maxlength);
2005 }
2006 }
2007
2008 if ($withpicto) {
2009 if (getDolGlobalString('AGENDA_USE_EVENT_TYPE')) { // Add code into ()
2010 if ($labeltype) {
2011 $label .= (preg_match('/'.preg_quote($labeltype, '/').'/', $label) ? '' : ' ('.$langs->transnoentities("Action".$this->type_code).')');
2012 }
2013 }
2014 }
2015
2016 $result .= $linkstart;
2017 if ($withpicto) {
2018 $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);
2019 }
2020 $result .= dol_escape_htmltag($labelshort);
2021 $result .= $linkend;
2022
2023 global $action;
2024 $hookmanager->initHooks(array('actiondao'));
2025 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
2026 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2027 if ($reshook > 0) {
2028 $result = $hookmanager->resPrint;
2029 } else {
2030 $result .= $hookmanager->resPrint;
2031 }
2032
2033 return $result;
2034 }
2035
2041 public function getTranslatedLabel()
2042 {
2043 global $langs;
2044
2045 if ($this->code == 'AC_COMPANY_CREATE' && !empty($this->thirdparty->name)) {
2046 return $langs->transnoentitiesnoconv('NewCompanyToDolibarr', $this->thirdparty->name);
2047 }
2048
2049 return $this->label;
2050 }
2051
2060 public function getTypePicto($morecss = 'pictofixedwidth paddingright valignmiddle', $titlealt = '')
2061 {
2062 $imgpicto = '';
2063 if (getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
2064 $color = '';
2065 if ($this->type_color) {
2066 $color = 'style="color: #'.$this->type_color.' !important;"';
2067 }
2068 if ($this->type_picto) {
2069 $imgpicto = img_picto($titlealt, $this->type_picto, '', 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2070 } else {
2071 if ($this->type_code === 'AC_RDV') {
2072 $imgpicto = img_picto($titlealt, 'meeting', $color, 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2073 } elseif ($this->type_code === 'AC_TEL') {
2074 $imgpicto = img_picto($titlealt, 'object_phoning', $color, 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2075 } elseif ($this->type_code === 'AC_FAX') {
2076 $imgpicto = img_picto($titlealt, 'object_phoning_fax', $color, 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2077 } 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))) {
2078 $imgpicto = img_picto($titlealt, 'object_email', $color, 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2079 } elseif ($this->type_code === 'AC_INT') {
2080 $imgpicto = img_picto($titlealt, 'object_intervention', $color, 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2081 } elseif (!empty($this->code) && preg_match('/^TICKET_MSG/', $this->code)) {
2082 $imgpicto = img_picto($titlealt, 'object_conversation', $color, 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2083 } elseif ((string) $this->type != 'systemauto') {
2084 $imgpicto = img_picto($titlealt, 'user-cog', $color, 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2085 } else {
2086 $imgpicto = img_picto($titlealt, 'cog', $color, 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2087 }
2088 }
2089 } else {
2090 // 2 picto: 1 for auto, 1 for manual
2091 if ($this->type != 'systemauto') {
2092 $imgpicto = img_picto($titlealt, 'user-cog', '', 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2093 } else {
2094 $imgpicto = img_picto($titlealt, 'cog', '', 0, 0, 0, '', ($morecss ? ' '.$morecss : ''));
2095 }
2096 }
2097
2098 return $imgpicto;
2099 }
2100
2101
2108 public function getTypeLabel($mode = 0)
2109 {
2110 global $conf, $langs;
2111
2112 // If cache for array of types unknown, we load it
2113 if (!empty($conf->cache['actioncommgetypelabel'])) {
2114 $arraylist = $conf->cache['actioncommgetypelabel'];
2115 } else {
2116 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php';
2117 $caction = new CActionComm($this->db);
2118 $arraylist = $caction->liste_array(1, 'code', '', (getDolGlobalString('AGENDA_USE_EVENT_TYPE') ? 0 : 1), '', 1);
2119 $conf->cache['actioncommgetypelabel'] = $arraylist;
2120 }
2121
2122 $labeltype = $this->type_code;
2123 if (!getDolGlobalString('AGENDA_USE_EVENT_TYPE') && empty($arraylist[$labeltype])) {
2124 $labeltype = 'AC_OTH';
2125 }
2126 if (!empty($this->code) && preg_match('/^TICKET_MSG/', $this->code)) {
2127 $labeltype = $langs->trans("Message");
2128 } else {
2129 if (!empty($arraylist[$labeltype])) {
2130 $labeltype = $arraylist[$labeltype];
2131 }
2132 if ($this->type_code == 'AC_OTH_AUTO' && ($this->type_code != $this->code) && $labeltype && !empty($arraylist[$this->code])) {
2133 $labeltype .= ' - '.$arraylist[$this->code]; // Use code in priority over type_code
2134 }
2135 }
2136
2137 if ($this->type == 'systemauto' && $mode == 1) {
2138 $labeltype .= ' ('.$langs->trans("auto").')';
2139 }
2140 if ($this->type == 'systemauto' && $mode == 2) {
2141 $labeltype = $langs->trans("AutoActions").($this->type_code == 'AC_OTH_AUTO' ? '' : ': '.$labeltype);
2142 } elseif ($this->type != 'systemauto' && $mode == 2) {
2143 $labeltype = $langs->trans("ManualActions").($this->type_code == 'AC_OTH' ? '' : ': '.$labeltype);
2144 }
2145
2146
2147 return $labeltype;
2148 }
2149
2160 public function setCategories($categories)
2161 {
2162 // Handle single category
2163 if (!is_array($categories)) {
2164 $categories = array($categories);
2165 }
2166
2167 // Get current categories
2168 include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2169 $c = new Categorie($this->db);
2170 $existing = $c->containing($this->id, Categorie::TYPE_ACTIONCOMM, 'id');
2171
2172 // Diff
2173 if (is_array($existing)) {
2174 $to_del = array_diff($existing, $categories);
2175 $to_add = array_diff($categories, $existing);
2176 } else {
2177 $to_del = array(); // Nothing to delete
2178 $to_add = $categories;
2179 }
2180
2181 // Process
2182 foreach ($to_del as $del) {
2183 if ($c->fetch($del) > 0) {
2184 $c->del_type($this, Categorie::TYPE_ACTIONCOMM);
2185 }
2186 }
2187 foreach ($to_add as $add) {
2188 if ($c->fetch($add) > 0) {
2189 $c->add_type($this, Categorie::TYPE_ACTIONCOMM);
2190 }
2191 }
2192 return 1;
2193 }
2194
2195 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2207 public function build_exportfile($format, $type, $cachedelay, $filename, $filters, $exportholiday = 0)
2208 {
2209 global $hookmanager;
2210
2211 // phpcs:enable
2212 global $conf, $langs, $dolibarr_main_url_root, $mysoc;
2213
2214 require_once DOL_DOCUMENT_ROOT."/core/lib/xcal.lib.php";
2215 require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php";
2216 require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php";
2217
2218 dol_syslog(get_class($this)."::build_exportfile Build export file format=".$format.", type=".$type.", cachedelay=".$cachedelay.", filename=".$filename.", filters size=".count($filters), LOG_DEBUG);
2219
2220 // Check parameters
2221 if (empty($format)) {
2222 return -1;
2223 }
2224
2225 // Clean parameters
2226 if (!$filename) {
2227 $extension = 'vcs';
2228 if ($format == 'ical') {
2229 $extension = 'ics';
2230 }
2231 $filename = $format.'.'.$extension;
2232 }
2233
2234 // Create dir and define output file (definitive and temporary)
2235 $result = dol_mkdir($conf->agenda->dir_temp);
2236 $outputfile = $conf->agenda->dir_temp.'/'.$filename;
2237
2238 $result = 0;
2239
2240 $buildfile = true;
2241 $login = '';
2242 $logina = '';
2243 $logint = '';
2244 $eventorganization = '';
2245
2246 $now = dol_now();
2247
2248 if ($cachedelay) {
2249 $nowgmt = dol_now();
2250 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2251 if (dol_filemtime($outputfile) > ($nowgmt - $cachedelay)) {
2252 dol_syslog(get_class($this)."::build_exportfile file ".$outputfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay."). Build is canceled");
2253 $buildfile = false;
2254 }
2255 }
2256
2257 if ($buildfile) {
2258 // Build event array
2259 $eventarray = array();
2260
2261 if (!empty($filters['module']) && $filters['module'] == 'project@eventorganization') {
2262 $sql = "SELECT p.rowid as id,";
2263 $sql .= " p.date_start_event as datep,"; // Start
2264 $sql .= " p.date_end_event as datep2,"; // End
2265 $sql .= " p.datec, p.tms as datem,";
2266 $sql .= " p.title as label, '' as code, p.note_public, p.note_private, 0 as type_id,";
2267 $sql .= " p.fk_soc,";
2268 $sql .= " p.fk_user_creat as fk_user_author, p.fk_user_modif as fk_user_mod,";
2269 $sql .= " 0 as fk_user_action,";
2270 $sql .= " 0 as fk_contact, 100 as percentage,";
2271 $sql .= " 0 as fk_element, '' as elementtype,";
2272 $sql .= " 1 as priority, 0 as fulldayevent, p.location, 0 as transparency,";
2273 $sql .= " u.firstname, u.lastname, '".$this->db->escape(getDolGlobalString("MAIN_INFO_SOCIETE_MAIL"))."' as email,";
2274 $sql .= " s.nom as socname,";
2275 $sql .= " 0 as type_id, '' as type_code, '' as type_label";
2276 $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
2277 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = p.fk_user_creat"; // Link to get author of event for export
2278 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = p.fk_soc";
2279
2280 $parameters = array('filters' => $filters);
2281 $reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters); // Note that $action and $object may have been modified by hook
2282 $sql .= $hookmanager->resPrint;
2283
2284 $sql .= " WHERE p.entity IN (".getEntity('project').")";
2285
2286 foreach ($filters as $key => $value) {
2287 if ($key == 'notolderthan' && $value != '') {
2288 $sql .= " AND p.date_start_event >= '".$this->db->idate($now - ($value * 24 * 60 * 60))."'";
2289 }
2290 if ($key == 'year') {
2291 $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))."'";
2292 }
2293 if ($key == 'id') {
2294 $sql .= " AND p.id = ".(is_numeric($value) ? $value : 0);
2295 }
2296 if ($key == 'idfrom') {
2297 $sql .= " AND p.id >= ".(is_numeric($value) ? $value : 0);
2298 }
2299 if ($key == 'idto') {
2300 $sql .= " AND p.id <= ".(is_numeric($value) ? $value : 0);
2301 }
2302 if ($key == 'project') {
2303 $sql .= " AND p.rowid = ".(is_numeric($value) ? $value : 0);
2304 }
2305 if ($key == 'status') {
2306 $sql .= " AND p.fk_statut = ".((int) $value);
2307 }
2308 // TODO Add filters on event code of meetings/talks only
2309 }
2310
2311 $sql .= " ORDER by date_start_event";
2312
2313 $eventorganization = 'project';
2314 } else {
2315 $sql = "SELECT a.id,";
2316 $sql .= " a.datep,"; // Start
2317 $sql .= " a.datep2,"; // End
2318 $sql .= " a.datec, a.tms as datem,";
2319 $sql .= " a.label, a.code, '' as note_public, a.note as note_private, a.fk_action as type_id,";
2320 $sql .= " a.fk_soc,";
2321 $sql .= " a.fk_user_author, a.fk_user_mod,";
2322 $sql .= " a.fk_user_action,";
2323 $sql .= " a.fk_contact, a.percent as percentage,";
2324 $sql .= " a.fk_element, a.elementtype,";
2325 $sql .= " a.priority, a.fulldayevent, a.location, a.transparency,";
2326 $sql .= " u.firstname, u.lastname, u.email,";
2327 $sql .= " s.nom as socname,";
2328 $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label,";
2329 $sql .= " num_vote, event_paid, a.status";
2330 $sql .= " FROM (".MAIN_DB_PREFIX."c_actioncomm as c, ".MAIN_DB_PREFIX."actioncomm as a)";
2331 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author"; // Link to get author of event for export
2332 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc";
2333
2334 $parameters = array('filters' => $filters);
2335 $reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters); // Note that $action and $object may have been modified by hook
2336 $sql .= $hookmanager->resPrint;
2337
2338 // We must filter on assignment table
2339 if (!empty($filters['logint']) && $filters['logint']) {
2340 $sql .= ", ".MAIN_DB_PREFIX."actioncomm_resources as ar";
2341 }
2342 $sql .= " WHERE a.fk_action = c.id";
2343 $sql .= " AND a.entity IN (".getEntity('agenda').")";
2344
2345 foreach ($filters as $key => $value) {
2346 if ($key == 'notolderthan' && $value != '') {
2347 $sql .= " AND a.datep >= '".$this->db->idate($now - ($value * 24 * 60 * 60))."'";
2348 }
2349 if ($key == 'year') {
2350 $sql .= " AND a.datep BETWEEN '".$this->db->idate(dol_get_first_day($value, 1))."' AND '".$this->db->idate(dol_get_last_day($value, 12))."'";
2351 }
2352 if ($key == 'id') {
2353 $sql .= " AND a.id = ".(is_numeric($value) ? $value : 0);
2354 }
2355 if ($key == 'idfrom') {
2356 $sql .= " AND a.id >= ".(is_numeric($value) ? $value : 0);
2357 }
2358 if ($key == 'idto') {
2359 $sql .= " AND a.id <= ".(is_numeric($value) ? $value : 0);
2360 }
2361 if ($key == 'project') {
2362 $sql .= " AND a.fk_project = ".(is_numeric($value) ? $value : 0);
2363 }
2364 if ($key == 'notactiontype') { // deprecated
2365 $sql .= " AND c.type <> '".$this->db->escape($value)."'";
2366 }
2367 if ($key == 'actiontype') { // 'system', 'systemauto', 'module', ...
2368 $newvalue = $value;
2369 $usenotin = 0;
2370 if (preg_match('/^!/', $newvalue)) {
2371 $newvalue = preg_replace('/^!/', '', $value);
2372 $usenotin = 1;
2373 }
2374 $arraynewvalue = explode(',', $newvalue);
2375 $newvalue = "";
2376 foreach ($arraynewvalue as $tmpval) {
2377 $newvalue .= ($newvalue ? "," : "")."'".$tmpval."'";
2378 }
2379 if ($usenotin) {
2380 $sql .= " AND c.type NOT IN (".$this->db->sanitize($newvalue, 1).")";
2381 } else {
2382 $sql .= " AND c.type IN (".$this->db->sanitize($newvalue, 1).")";
2383 }
2384 }
2385 if ($key == 'actioncode') { // 'AC_COMPANY_CREATE', 'AC_COMPANY_MODIFY', ...
2386 $newvalue = $value;
2387 $usenotin = 0;
2388 if (preg_match('/^!/', $newvalue)) {
2389 $newvalue = preg_replace('/^!/', '', $value);
2390 $usenotin = 1;
2391 }
2392 $arraynewvalue = explode(',', $newvalue);
2393 $newvalue = "";
2394 foreach ($arraynewvalue as $tmpval) {
2395 $newvalue .= ($newvalue ? "," : "")."'".$tmpval."'";
2396 }
2397 if ($usenotin) {
2398 $sql .= " AND a.code NOT IN (".$this->db->sanitize($newvalue, 1).")";
2399 } else {
2400 $sql .= " AND a.code IN (".$this->db->sanitize($newvalue, 1).")";
2401 }
2402 }
2403
2404 // We must filter on assignment table
2405 if ($key == 'logint') {
2406 $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'";
2407 }
2408 if ($key == 'logina') {
2409 $logina = $value;
2410 $sanitizedcondition = '=';
2411 if (preg_match('/^!/', $logina)) {
2412 $logina = preg_replace('/^!/', '', $logina);
2413 $sanitizedcondition = '<>';
2414 }
2415 $userforfilter = new User($this->db);
2416 $result = $userforfilter->fetch(0, $logina);
2417 if ($result > 0) {
2418 $sql .= " AND a.fk_user_author ".$sanitizedcondition." ".((int) $userforfilter->id);
2419 } elseif ($result < 0 || $sanitizedcondition == '=') {
2420 $sql .= " AND a.fk_user_author = 0";
2421 }
2422 }
2423 if ($key == 'logint') {
2424 $logint = $value;
2425 $sanitizedcondition = '=';
2426 if (preg_match('/^!/', $logint)) {
2427 $logint = preg_replace('/^!/', '', $logint);
2428 $sanitizedcondition = '<>';
2429 }
2430 $userforfilter = new User($this->db);
2431 $result = $userforfilter->fetch(0, $logint);
2432 if ($result > 0) {
2433 $sql .= " AND ar.fk_element = ".((int) $userforfilter->id);
2434 } elseif ($result < 0 || $sanitizedcondition == '=') {
2435 $sql .= " AND ar.fk_element = 0";
2436 }
2437 }
2438 if ($key == 'module') {
2439 if ($value == 'conforbooth@eventorganization') {
2440 $value = '@eventorganization';
2441 }
2442 $sql .= " AND c.module LIKE '%".$this->db->escape($value)."'";
2443 }
2444 if ($key == 'status') {
2445 $sql .= " AND a.status = ".((int) $value);
2446 }
2447 }
2448
2449 $sql .= " AND a.datep IS NOT NULL"; // To exclude corrupted events and avoid errors in lightning/sunbird import
2450
2451 $parameters = array('filters' => $filters);
2452 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
2453 $sql .= $hookmanager->resPrint;
2454
2455 $sql .= " ORDER by datep";
2456 }
2457
2458 if (!empty($filters['limit'])) {
2459 $sql .= $this->db->plimit((int) $filters['limit']);
2460 }
2461
2462 //print $sql;exit;
2463
2464 dol_syslog(get_class($this)."::build_exportfile select event(s)", LOG_DEBUG);
2465
2466 $resql = $this->db->query($sql);
2467 if ($resql) {
2468 $diff = 0;
2469 while ($obj = $this->db->fetch_object($resql)) {
2470 $qualified = true;
2471
2472 // 'eid','startdate','duration','enddate','title','summary','category','email','url','desc','author'
2473 $event = array();
2474 $event['uid'] = 'dolibarragenda-'.$obj->id."@".dol_getprefix('email');
2475 $event['type'] = $type;
2476
2477 $datestart = (int) $this->db->jdate($obj->datep) - (getDolGlobalInt('AGENDA_EXPORT_FIX_TZ') * 3600);
2478
2479 // fix for -> Warning: A non-numeric value encountered
2480 if (is_numeric($this->db->jdate($obj->datep2))) {
2481 $dateend = (int) $this->db->jdate($obj->datep2) - (getDolGlobalInt('AGENDA_EXPORT_FIX_TZ') * 3600);
2482 } else {
2483 // use start date as fall-back to avoid pb with empty end date on ICS readers
2484 $dateend = $datestart;
2485 }
2486
2487 $duration = ($datestart && $dateend) ? ($dateend - $datestart) : 0;
2488 $event['summary'] = $obj->label.($obj->socname ? " (".$obj->socname.")" : "");
2489
2490 if (!empty($filters['module']) && $filters['module'] == 'project@eventorganization') {
2491 $event['desc'] = $obj->note_public;
2492 } else {
2493 $event['desc'] = $obj->note_private;
2494 }
2495 $event['startdate'] = $datestart;
2496 $event['enddate'] = $dateend; // Not required with type 'journal'
2497 $event['duration'] = $duration; // Not required with type 'journal'
2498 $event['author'] = dolGetFirstLastname($obj->firstname, $obj->lastname);
2499 $event['priority'] = $obj->priority;
2500 $event['fulldayevent'] = $obj->fulldayevent;
2501 $event['location'] = $obj->location;
2502 $event['transparency'] = (($obj->transparency > 0) ? 'OPAQUE' : 'TRANSPARENT'); // OPAQUE (busy) or TRANSPARENT (not busy)
2503 $event['category'] = $obj->type_label;
2504 $event['email'] = $obj->email;
2505
2506 // Public URL of event
2507 if ($eventorganization != '') {
2508 $link_subscription = $dolibarr_main_url_root.'/public/eventorganization/attendee_new.php?id='.((int) $obj->id).'&type=global&noregistration=1';
2509 $encodedsecurekey = dol_hash(getDolGlobalString('EVENTORGANIZATION_SECUREKEY').'conferenceorbooth'.((int) $obj->id), 'md5');
2510 $link_subscription .= '&securekey='.urlencode($encodedsecurekey);
2511
2512 $event['url'] = $link_subscription;
2513 } else {
2514 $event['url'] = $dolibarr_main_url_root.'/comm/action/card.php?id='.$obj->id;
2515 }
2516
2517 $event['created'] = (int) $this->db->jdate($obj->datec) - (getDolGlobalInt('AGENDA_EXPORT_FIX_TZ') * 3600);
2518 $event['modified'] = (int) $this->db->jdate($obj->datem) - (getDolGlobalInt('AGENDA_EXPORT_FIX_TZ') * 3600);
2519 $event['num_vote'] = $this->num_vote;
2520 $event['event_paid'] = $this->event_paid;
2521 $event['status'] = $this->status;
2522
2523 // TODO: find a way to call "$this->fetch_userassigned();" without override "$this" properties
2524 $this->id = $obj->id;
2525 $this->fetch_userassigned(false);
2526
2527 $assignedUserArray = array();
2528
2529 foreach ($this->userassigned as $key => $value) {
2530 $assignedUser = new User($this->db);
2531 $assignedUser->fetch($value['id']);
2532
2533 $assignedUserArray[$key] = $assignedUser;
2534 }
2535
2536 if (empty($filters['module']) || $filters['module'] != 'project@eventorganization') {
2537 $event['assignedUsers'] = $assignedUserArray;
2538 }
2539
2540 if ($qualified && $datestart) {
2541 $eventarray[] = $event;
2542 }
2543 $diff++;
2544 }
2545
2546 $parameters = array('filters' => $filters, 'eventarray' => &$eventarray);
2547 $reshook = $hookmanager->executeHooks('addMoreEventsExport', $parameters); // Note that $action and $object may have been modified by hook
2548 if ($reshook > 0) {
2549 $eventarray = $hookmanager->resArray;
2550 }
2551 } else {
2552 $this->error = $this->db->lasterror();
2553 return -1;
2554 }
2555
2556 if ($exportholiday == 1) {
2557 $langs->load("holiday");
2558 $title = $langs->transnoentities("Holidays");
2559
2560 $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";
2561 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as x, ".MAIN_DB_PREFIX."user as u";
2562 $sql .= " WHERE u.rowid = x.fk_user";
2563 $sql .= " AND u.statut = '1'"; // Show only active users (0 = inactive user, 1 = active user)
2564 $sql .= " AND (x.statut = '2' OR x.statut = '3')"; // Show only public leaves (2 = leave wait for approval, 3 = leave approved)
2565
2566 $resql = $this->db->query($sql);
2567 if ($resql) {
2568 $num = $this->db->num_rows($resql);
2569 $i = 0;
2570
2571 while ($i < $num) {
2572 $obj = $this->db->fetch_object($resql);
2573 $event = array();
2574
2575 if ($obj->halfday == 1) {
2576 $event['fulldayevent'] = false;
2577
2578 $timestampStart = dol_stringtotime($obj->date_start." 00:00:00", 0);
2579 $timestampEnd = dol_stringtotime($obj->date_end." 12:00:00", 0);
2580 } elseif ($obj->halfday == -1) {
2581 $event['fulldayevent'] = false;
2582
2583 $timestampStart = dol_stringtotime($obj->date_start." 12:00:00", 0);
2584 $timestampEnd = dol_stringtotime($obj->date_end." 23:59:59", 0);
2585 } else {
2586 $event['fulldayevent'] = true;
2587
2588 $timestampStart = dol_stringtotime($obj->date_start." 00:00:00", 0);
2589 $timestampEnd = dol_stringtotime($obj->date_end." 23:59:59", 0);
2590 }
2591
2592 if (getDolGlobalString('AGENDA_EXPORT_FIX_TZ')) {
2593 $timestampStart -= (getDolGlobalInt('AGENDA_EXPORT_FIX_TZ') * 3600);
2594 $timestampEnd -= (getDolGlobalInt('AGENDA_EXPORT_FIX_TZ') * 3600);
2595 }
2596
2597 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2598 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
2599 $url = $urlwithroot.'/holiday/card.php?id='.$obj->rowid;
2600
2601 $event['uid'] = 'dolibarrholiday-'.$obj->rowid."@".dol_getprefix('email');
2602 $event['author'] = dolGetFirstLastname($obj->firstname, $obj->lastname);
2603 $event['type'] = 'event';
2604 $event['category'] = "Holiday";
2605 $event['transparency'] = 'OPAQUE';
2606 $event['email'] = $obj->email;
2607 $event['created'] = $timestampStart;
2608 $event['modified'] = $timestampStart;
2609 $event['startdate'] = $timestampStart;
2610 $event['enddate'] = $timestampEnd;
2611 $event['duration'] = $timestampEnd - $timestampStart;
2612 $event['url'] = $url;
2613
2614 if ($obj->status == 2) {
2615 // 2 = leave wait for approval
2616 $event['summary'] = $title." - ".$obj->lastname." (wait for approval)";
2617 } else {
2618 // 3 = leave approved
2619 $event['summary'] = $title." - ".$obj->lastname;
2620 }
2621
2622 $eventarray[] = $event;
2623
2624 $i++;
2625 }
2626 }
2627 }
2628
2629 $langs->load("agenda");
2630
2631 // Define title and desc
2632 $title = '';
2633 $more = '';
2634 if ($login) {
2635 $more = $langs->transnoentities("User").' '.$login;
2636 }
2637 if ($logina) {
2638 $more = $langs->transnoentities("ActionsAskedBy").' '.$logina;
2639 }
2640 if ($logint) {
2641 $more = $langs->transnoentities("ActionsToDoBy").' '.$logint;
2642 }
2643 if ($eventorganization) {
2644 $langs->load("eventorganization");
2645 $title = $langs->transnoentities("OrganizedEvent").(empty($eventarray[0]['label']) ? '' : ' '.$eventarray[0]['label']);
2646 $more = 'ICS file - '.$langs->transnoentities("OrganizedEvent").(empty($eventarray[0]['label']) ? '' : ' '.$eventarray[0]['label']);
2647 }
2648 if ($more) {
2649 if (empty($title)) {
2650 $title = 'Dolibarr actions '.$mysoc->name.' - '.$more;
2651 }
2652 $desc = $more;
2653 $desc .= ' ('.$mysoc->name.' - built by Dolibarr)';
2654 } else {
2655 if (empty($title)) {
2656 $title = $langs->transnoentities("Events").' '.$mysoc->name;
2657 }
2658 $desc = $langs->transnoentities('ListOfActions');
2659 $desc .= ' ('.$mysoc->name.' - built by Dolibarr)';
2660 }
2661
2662 // Create temp file
2663 $outputfiletmp = tempnam($conf->agenda->dir_temp, 'tmp'); // Temporary file (allow call of function by different threads
2664 dolChmod($outputfiletmp);
2665
2666 // Write file
2667 if ($format == 'vcal') {
2668 $result = build_calfile($format, $title, $desc, $eventarray, $outputfiletmp);
2669 } elseif ($format == 'ical') {
2670 $result = build_calfile($format, $title, $desc, $eventarray, $outputfiletmp);
2671 } elseif ($format == 'rss') {
2672 $result = build_rssfile($format, $title, $desc, $eventarray, $outputfiletmp);
2673 }
2674
2675 if ($result >= 0) {
2676 if (dol_move($outputfiletmp, $outputfile, '0', 1, 0, 0)) {
2677 $result = 1;
2678 } else {
2679 $this->error = 'Failed to rename '.$outputfiletmp.' into '.$outputfile;
2680 dol_syslog(get_class($this)."::build_exportfile ".$this->error, LOG_ERR);
2681 dol_delete_file($outputfiletmp, 0, 1);
2682 $result = -1;
2683 }
2684 } else {
2685 dol_syslog(get_class($this)."::build_exportfile build_xxxfile function fails to for format=".$format." outputfiletmp=".$outputfile, LOG_ERR);
2686 dol_delete_file($outputfiletmp, 0, 1);
2687 $langs->load("errors");
2688 $this->error = $langs->trans("ErrorFailToCreateFile", $outputfile);
2689 }
2690 }
2691
2692 return $result;
2693 }
2694
2702 public function initAsSpecimen()
2703 {
2704 global $user;
2705
2706 $now = dol_now();
2707
2708 // Initialise parameters
2709 $this->id = 0;
2710 $this->specimen = 1;
2711
2712 $this->type_code = 'AC_OTH';
2713 $this->code = 'AC_SPECIMEN_CODE';
2714 $this->label = 'Label of event Specimen';
2715 $this->datec = $now;
2716 $this->datem = $now;
2717 $this->datep = $now;
2718 $this->datef = $now;
2719 $this->fulldayevent = 0;
2720 $this->percentage = 0;
2721 $this->status = 0;
2722 $this->location = 'Location';
2723 $this->transparency = 1; // 1 means opaque
2724 $this->priority = 1;
2725 //$this->note_public = "This is a 'public' note.";
2726 $this->note_private = "This is a 'private' note.";
2727
2728 $this->userownerid = $user->id;
2729 $this->userassigned[$user->id] = array('id' => $user->id, 'transparency' => 1);
2730 return 1;
2731 }
2732
2741 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2742 {
2743 $tables = array(
2744 'actioncomm'
2745 );
2746
2747 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
2748 }
2749
2760 public static function replaceContact(DoliDB $dbs, $origin_id, $dest_id)
2761 {
2762 // llx_actioncomm_resources: UNIQUE(fk_actioncomm, element_type, fk_element)
2763 $sql = 'DELETE FROM '.$dbs->prefix().'actioncomm_resources WHERE rowid IN (';
2764 $sql .= ' SELECT x.rowid FROM (';
2765 $sql .= ' SELECT origin.rowid FROM '.$dbs->prefix().'actioncomm_resources as origin';
2766 $sql .= ' INNER JOIN '.$dbs->prefix().'actioncomm_resources as dest';
2767 $sql .= ' ON dest.fk_actioncomm = origin.fk_actioncomm AND dest.element_type = origin.element_type';
2768 $sql .= " WHERE origin.element_type = 'socpeople'";
2769 $sql .= ' AND origin.fk_element = '.((int) $origin_id).' AND dest.fk_element = '.((int) $dest_id);
2770 $sql .= ' ) as x)';
2771 if (!$dbs->query($sql)) {
2772 return false;
2773 }
2774
2775 $sql = 'UPDATE '.$dbs->prefix().'actioncomm_resources SET fk_element = '.((int) $dest_id);
2776 $sql .= " WHERE element_type = 'socpeople' AND fk_element = ".((int) $origin_id);
2777 if (!$dbs->query($sql)) {
2778 return false;
2779 }
2780
2781 // llx_actioncomm_reminder: UNIQUE(fk_actioncomm, fk_user, fk_soc, fk_contact, typeremind, offsetvalue, offsetunit)
2782 $sql = 'DELETE FROM '.$dbs->prefix().'actioncomm_reminder WHERE rowid IN (';
2783 $sql .= ' SELECT x.rowid FROM (';
2784 $sql .= ' SELECT origin.rowid FROM '.$dbs->prefix().'actioncomm_reminder as origin';
2785 $sql .= ' INNER JOIN '.$dbs->prefix().'actioncomm_reminder as dest';
2786 $sql .= ' ON dest.fk_actioncomm = origin.fk_actioncomm AND dest.typeremind = origin.typeremind';
2787 $sql .= ' AND dest.offsetvalue = origin.offsetvalue AND dest.offsetunit = origin.offsetunit';
2788 // fk_user and fk_soc are part of the unique key and are nullable, hence the NULL safe
2789 // comparisons: the MySQL <=> operator is not portable to PostgreSQL
2790 $sql .= ' AND (dest.fk_user = origin.fk_user OR (dest.fk_user IS NULL AND origin.fk_user IS NULL))';
2791 $sql .= ' AND (dest.fk_soc = origin.fk_soc OR (dest.fk_soc IS NULL AND origin.fk_soc IS NULL))';
2792 $sql .= ' WHERE origin.fk_contact = '.((int) $origin_id).' AND dest.fk_contact = '.((int) $dest_id);
2793 $sql .= ' ) as x)';
2794 if (!$dbs->query($sql)) {
2795 return false;
2796 }
2797
2798 $tables = array(
2799 'actioncomm', 'actioncomm_reminder'
2800 );
2801
2802 return CommonObject::commonReplaceContact($dbs, $origin_id, $dest_id, $tables, 'fk_contact');
2803 }
2804
2813 public static function replaceProduct(DoliDB $dbs, $origin_id, $dest_id)
2814 {
2815 $sql = 'UPDATE ' . MAIN_DB_PREFIX . 'actioncomm SET fk_element = ' . ((int) $dest_id) . ' WHERE elementtype="product" AND fk_element = '.((int) $origin_id);
2816 // using $dbs, not $this->db because function is static
2817 if (!$dbs->query($sql)) {
2818 //$this->errors = $dbs->lasterror();
2819 return false;
2820 }
2821
2822 return true;
2823 }
2824
2830 public function hasDelay()
2831 {
2832 global $conf;
2833
2834 $now = dol_now();
2835
2836 return $this->datep && ($this->datep < ($now - $conf->agenda->warning_delay));
2837 }
2838
2839
2848 public function loadReminders($type = '', $fk_user = 0, $onlypast = true)
2849 {
2850 $error = 0;
2851
2852 $this->reminders = array();
2853
2854 //Select all action comm reminders for event
2855 $sql = "SELECT rowid as id, typeremind, dateremind, status, offsetvalue, offsetunit, fk_user, fk_email_template, lasterror";
2856 $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
2857 $sql .= " WHERE fk_actioncomm = ".((int) $this->id);
2858 if ($onlypast) {
2859 $sql .= " AND dateremind <= '".$this->db->idate(dol_now())."'";
2860 }
2861 if ($type) {
2862 $sql .= " AND typeremind = '".$this->db->escape($type)."'";
2863 }
2864 if ($fk_user > 0) {
2865 $sql .= " AND fk_user = ".((int) $fk_user);
2866 }
2867 if (!getDolGlobalString('AGENDA_REMINDER_EMAIL')) {
2868 $sql .= " AND typeremind <> 'email'";
2869 }
2870 if (!getDolGlobalString('AGENDA_REMINDER_BROWSER')) {
2871 $sql .= " AND typeremind <> 'browser'";
2872 }
2873
2874 $sql .= $this->db->order("dateremind", "ASC");
2875 $resql = $this->db->query($sql);
2876
2877 if ($resql) {
2878 while ($obj = $this->db->fetch_object($resql)) {
2879 $tmpactioncommreminder = new ActionCommReminder($this->db);
2880 $tmpactioncommreminder->id = $obj->id;
2881 $tmpactioncommreminder->typeremind = $obj->typeremind;
2882 $tmpactioncommreminder->dateremind = $this->db->jdate($obj->dateremind);
2883 $tmpactioncommreminder->offsetvalue = $obj->offsetvalue;
2884 $tmpactioncommreminder->offsetunit = $obj->offsetunit;
2885 $tmpactioncommreminder->status = $obj->status;
2886 $tmpactioncommreminder->fk_user = $obj->fk_user;
2887 $tmpactioncommreminder->fk_email_template = $obj->fk_email_template;
2888 $tmpactioncommreminder->lasterror = $obj->lasterror;
2889 $tmpactioncommreminder->fk_actioncomm = $this->id;
2890
2891 $this->reminders[$obj->id] = $tmpactioncommreminder;
2892 }
2893 } else {
2894 $this->error = $this->db->lasterror();
2895 $error++;
2896 }
2897
2898 return count($this->reminders);
2899 }
2900
2901
2908 public function sendEmailsReminder()
2909 {
2910 global $langs, $user;
2911
2912 $error = 0;
2913 $this->output = '';
2914 $this->error = '';
2915 $nbMailSend = 0;
2916 $errorsMsg = array();
2917
2918 if (!isModEnabled('agenda')) { // Should not happen. If module disabled, cron job should not be visible.
2919 $langs->load("agenda");
2920 $this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Agenda"));
2921 return 0;
2922 }
2923 if (!getDolGlobalString('AGENDA_REMINDER_EMAIL')) {
2924 $langs->load("agenda");
2925 $this->output = $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Agenda"));
2926 return 0;
2927 }
2928
2929 $now = dol_now();
2930 $actionCommReminder = new ActionCommReminder($this->db);
2931
2932 dol_syslog(__METHOD__." start", LOG_INFO);
2933
2934 $this->db->begin();
2935
2936 //Select all action comm reminders
2937 $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
2938 $sql .= " WHERE typeremind = 'email'";
2939 $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.
2940 $sql .= " AND dateremind <= '".$this->db->idate($now)."'";
2941 $sql .= " AND entity IN (".getEntity('actioncomm').")";
2942 $sql .= $this->db->order("dateremind", "ASC");
2943 $resql = $this->db->query($sql);
2944
2945 if ($resql) {
2946 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
2947 $formmail = new FormMail($this->db);
2948 $to = null; // Ensure 'to' is defined for static analysis
2949
2950 while ($obj = $this->db->fetch_object($resql)) {
2951 $res = $actionCommReminder->fetch($obj->id);
2952 if ($res < 0) {
2953 $error++;
2954 $errorsMsg[] = "Failed to load invoice ActionComm Reminder";
2955 }
2956
2957 if (!$error) {
2958 //Select email template
2959 $arraymessage = $formmail->getEMailTemplate($this->db, 'actioncomm_send', $user, $langs, (!empty($actionCommReminder->fk_email_template)) ? $actionCommReminder->fk_email_template : -1, 1);
2960
2961 // Load event
2962 $res = $this->fetch($actionCommReminder->fk_actioncomm);
2963 if ($res > 0) {
2964 // PREPARE EMAIL
2965 $errormesg = '';
2966 $this->fetch_thirdparty();
2967
2968 // Make substitution in email content
2969 $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $this);
2970
2971 complete_substitutions_array($substitutionarray, $langs, $this);
2972
2973 // Content
2974 $sendContent = make_substitutions($langs->trans($arraymessage->content), $substitutionarray);
2975
2976 // Topic
2977 $sendTopic = (!empty($arraymessage->topic)) ? $arraymessage->topic : $langs->transnoentitiesnoconv('EventReminder');
2978 $sendTopic = make_substitutions($sendTopic, $substitutionarray);
2979
2980 // Recipient
2981 $recipient = new User($this->db);
2982 $res = $recipient->fetch($actionCommReminder->fk_user);
2983 if ($res > 0) {
2984 if (!empty($recipient->email)) {
2985 $to = $recipient->email;
2986 } else {
2987 $errormesg = "Failed to send remind to user id=" . $actionCommReminder->fk_user . ". No email defined for user.";
2988 $error++;
2989 }
2990 } else {
2991 $errormesg = "Failed to load recipient with user id=" . $actionCommReminder->fk_user;
2992 $error++;
2993 }
2994
2995 // Sender
2996 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
2997 if (empty($from)) {
2998 $errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
2999 $error++;
3000 }
3001
3002 if (!$error) {
3003 // Errors Recipient
3004 $errors_to = getDolGlobalString('MAIN_MAIL_ERRORS_TO');
3005
3006 // Mail Creation
3007 $cMailFile = new CMailFile($sendTopic, (string) $to, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', '', '', '', '');
3008
3009 // Sending Mail
3010 if ($cMailFile->sendfile()) {
3011 $nbMailSend++;
3012 } else {
3013 $errormesg = 'Failed to send email to: ' . $to . ' ' . $cMailFile->error . implode(',', $cMailFile->errors);
3014 $error++;
3015 }
3016 }
3017
3018 if (!$error) {
3019 $actionCommReminder->status = $actionCommReminder::STATUS_DONE;
3020
3021 $res = $actionCommReminder->update($user);
3022 if ($res < 0) {
3023 $errorsMsg[] = "Failed to update status to done of ActionComm Reminder";
3024 $error++;
3025 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.
3026 }
3027 } else {
3028 $actionCommReminder->status = $actionCommReminder::STATUS_ERROR;
3029 $actionCommReminder->lasterror = dol_trunc($errormesg, 128, 'right', 'UTF-8', 1);
3030
3031 $res = $actionCommReminder->update($user);
3032 if ($res < 0) {
3033 $errorsMsg[] = "Failed to update status to error of ActionComm Reminder";
3034 $error++;
3035 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.
3036 } else {
3037 $errorsMsg[] = $errormesg;
3038 }
3039 }
3040 } else {
3041 $errorsMsg[] = 'Failed to fetch record actioncomm with ID = '.$actionCommReminder->fk_actioncomm;
3042 $error++;
3043 }
3044 }
3045 }
3046 } else {
3047 $error++;
3048 }
3049
3050 if (!$error) {
3051 // Delete also very old past events (we do not keep more than 1 month record in past)
3052 $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
3053 $sql .= " WHERE dateremind < '".$this->db->idate($now - (3600 * 24 * 32))."'";
3054 $sql .= " AND status = ".((int) $actionCommReminder::STATUS_DONE);
3055 $resql = $this->db->query($sql);
3056
3057 if (!$resql) {
3058 $errorsMsg[] = 'Failed to delete old reminders';
3059 //$error++; // If this fails, we must not rollback other SQL requests already done. Never mind.
3060 }
3061 }
3062
3063 if (!$error) {
3064 $this->output = 'Nb of emails sent : '.$nbMailSend;
3065 $this->db->commit();
3066
3067 dol_syslog(__METHOD__." end - ".$this->output, LOG_INFO);
3068
3069 return 0;
3070 } else {
3071 $this->db->commit(); // We commit also on error, to have the error message recorded.
3072 $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg) ? implode(', ', $errorsMsg) : $error);
3073
3074 dol_syslog(__METHOD__." end - ".$this->error, LOG_INFO);
3075
3076 return $error;
3077 }
3078 }
3079
3086 public function sendSmsReminder()
3087 {
3088 global $langs, $user;
3089
3090 $error = 0;
3091 $this->output = '';
3092 $this->error = '';
3093 $nbSmsSent = 0;
3094 $errorsMsg = array();
3095
3096 if (!isModEnabled('agenda')) { // Should not happen. If module disabled, cron job should not be visible.
3097 $langs->load("agenda");
3098 $this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Agenda"));
3099 return 0;
3100 }
3101 if (!getDolGlobalString('AGENDA_REMINDER_SMS')) {
3102 $langs->load("agenda");
3103 $this->output = $langs->trans('EventRemindersBySmsNotEnabled', $langs->transnoentitiesnoconv("Agenda"));
3104 return 0;
3105 }
3106
3107 $now = dol_now();
3108 $actionCommReminder = new ActionCommReminder($this->db);
3109
3110 dol_syslog(__METHOD__." start", LOG_INFO);
3111
3112 $this->db->begin();
3113
3114 //Select all action comm reminders
3115 $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
3116 $sql .= " WHERE typeremind = 'sms'";
3117 $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.
3118 $sql .= " AND dateremind <= '".$this->db->idate($now)."'";
3119 $sql .= " AND entity IN (".getEntity('actioncomm').")";
3120 $sql .= $this->db->order("dateremind", "ASC");
3121 $resql = $this->db->query($sql);
3122
3123 if ($resql) {
3124 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
3125 $formmail = new FormMail($this->db);
3126 $to = null; // Ensure 'to' is defined for static analysis
3127
3128 while ($obj = $this->db->fetch_object($resql)) {
3129 $res = $actionCommReminder->fetch($obj->id);
3130 if ($res < 0) {
3131 $error++;
3132 $errorsMsg[] = "Failed to load invoice ActionComm Reminder";
3133 }
3134
3135 if (!$error) {
3136 //Select email template
3137 $arraymessage = $formmail->getEMailTemplate($this->db, 'actioncomm_send', $user, $langs, (!empty($actionCommReminder->fk_email_template)) ? $actionCommReminder->fk_email_template : -1, 1);
3138
3139 // Load event
3140 $res = $this->fetch($actionCommReminder->fk_actioncomm);
3141 if ($res > 0) {
3142 // PREPARE SMS
3143 $errormesg = '';
3144 $this->fetch_thirdparty();
3145
3146 // Make substitution in email content
3147 $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $this);
3148
3149 complete_substitutions_array($substitutionarray, $langs, $this);
3150
3151 // Content
3152 $sendContent = dol_string_nohtmltag(make_substitutions($langs->trans($arraymessage->content), $substitutionarray));
3153
3154 // Topic
3155 // $sendTopic = (!empty($arraymessage->topic)) ? $arraymessage->topic : html_entity_decode($langs->transnoentities('EventReminder'));
3156
3157 // Recipient
3158 $recipient = new User($this->db);
3159 $res = $recipient->fetch($actionCommReminder->fk_user);
3160 if ($res > 0) {
3161 if (!empty($recipient->user_mobile)) {
3162 $to = $recipient->user_mobile;
3163 } else {
3164 $errormesg = "Failed to send remind to user id=" . $actionCommReminder->fk_user . ". No email defined for user.";
3165 $error++;
3166 }
3167 } else {
3168 $errormesg = "Failed to load recipient with user id=" . $actionCommReminder->fk_user;
3169 $error++;
3170 }
3171
3172 // Sender
3173 $from = getDolGlobalString('MAIN_SMS_FROM');
3174 if (empty($from)) {
3175 $errormesg = "Failed to get sender into global setup MAIN_SMS_FROM";
3176 $error++;
3177 }
3178
3179 if (!$error) {
3180 // Errors Recipient
3181 // $errors_to = getDolGlobalString('MAIN_MAIL_ERRORS_TO');
3182
3183 // Sms Creation
3184 $CSMSFile = new CSMSFile((string) $to, $from, $sendContent, 0, 0, 3, 1);
3185
3186 // Sending Mail
3187 if ($CSMSFile->sendfile()) {
3188 $nbSmsSent++;
3189 } else {
3190 $errormesg = 'Failed to send email to: ' . $to . ' ' . $CSMSFile->error . implode(',', $CSMSFile->errors);
3191 $error++;
3192 }
3193 }
3194
3195 if (!$error) {
3196 $actionCommReminder->status = $actionCommReminder::STATUS_DONE;
3197
3198 $res = $actionCommReminder->update($user);
3199 if ($res < 0) {
3200 $errorsMsg[] = "Failed to update status to done of ActionComm Reminder";
3201 $error++;
3202 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.
3203 }
3204 } else {
3205 $actionCommReminder->status = $actionCommReminder::STATUS_ERROR;
3206 $actionCommReminder->lasterror = dol_trunc($errormesg, 128, 'right', 'UTF-8', 1);
3207
3208 $res = $actionCommReminder->update($user);
3209 if ($res < 0) {
3210 $errorsMsg[] = "Failed to update status to error of ActionComm Reminder";
3211 $error++;
3212 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.
3213 } else {
3214 $errorsMsg[] = $errormesg;
3215 }
3216 }
3217 } else {
3218 $errorsMsg[] = 'Failed to fetch record actioncomm with ID = '.$actionCommReminder->fk_actioncomm;
3219 $error++;
3220 }
3221 }
3222 }
3223 } else {
3224 $error++;
3225 }
3226
3227 if (!$error) {
3228 // Delete also very old past events (we do not keep more than 1 month record in past)
3229 $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
3230 $sql .= " WHERE dateremind < '".$this->db->idate($now - (3600 * 24 * 32))."'";
3231 $sql .= " AND status = ".((int) $actionCommReminder::STATUS_DONE);
3232 $resql = $this->db->query($sql);
3233
3234 if (!$resql) {
3235 $errorsMsg[] = 'Failed to delete old reminders';
3236 //$error++; // If this fails, we must not rollback other SQL requests already done. Never mind.
3237 }
3238 }
3239
3240 if (!$error) {
3241 $this->output = 'Nb of SMS sent : '.$nbSmsSent;
3242 $this->db->commit();
3243 dol_syslog(__METHOD__." end - ".$this->output, LOG_INFO);
3244
3245 return 0;
3246 } else {
3247 $this->db->commit(); // We commit also on error, to have the error message recorded.
3248 $this->error = 'Nb of SMS sent : '.$nbSmsSent.', '.(!empty($errorsMsg) ? implode(', ', $errorsMsg) : $error);
3249 dol_syslog(__METHOD__." end - ".$this->error, LOG_INFO);
3250
3251 return $error;
3252 }
3253 }
3254
3263 public function updatePercent($id, $percent, $usermodid = 0)
3264 {
3265 $this->db->begin();
3266
3267 $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm ";
3268 $sql .= " SET percent = ".(int) $percent;
3269 if ($usermodid > 0) {
3270 $sql .= ", fk_user_mod = ".((int) $usermodid);
3271 }
3272 $sql .= " WHERE id = ".((int) $id);
3273
3274 if ($this->db->query($sql)) {
3275 $this->db->commit();
3276 return 1;
3277 } else {
3278 $this->db->rollback();
3279 $this->error = $this->db->lasterror();
3280 return -1;
3281 }
3282 }
3283}
$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:280
$c
Definition line.php:346
$object ref
Definition info.php:90
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 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,...
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.
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:616
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:635
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:442
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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.
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:181
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
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:325