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