dolibarr 25.0.0-alpha
ticket.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2013-2018 Jean-François Ferry <hello@librethic.io>
3 * Copyright (C) 2016 Christophe Battarel <christophe@altairis.fr>
4 * Copyright (C) 2019-2026 Frédéric France <frederic.france@free.fr>
5 * Copyright (C) 2020 Laurent Destailleur <eldy@users.sourceforge.net>
6 * Copyright (C) 2023-2025 Charlene Benke <charlene@patas-monkey.com>
7 * Copyright (C) 2023-2024 Benjamin Falière <benjamin.faliere@altairis.fr>
8 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
9 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
10 * Copyright (C) 2026 Jon Bendtsen <jon.bendtsen.github@jonb.dk>
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
32// Put here all includes required by your class file
33require_once DOL_DOCUMENT_ROOT."/core/class/commonobject.class.php";
34require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
35require_once DOL_DOCUMENT_ROOT.'/core/lib/ticket.lib.php';
36
37
41class Ticket extends CommonObject
42{
46 public $db;
47
51 public $element = 'ticket';
52
56 public $table_element = 'ticket';
57
61 public $fk_element = 'fk_ticket';
62
66 public $picto = 'ticket';
67
71 public $track_id;
72
76 public $fk_soc;
77
81 public $socid;
82
86 public $fk_contract;
87
91 public $origin_email;
92
96 public $fk_user_create;
97
101 public $fk_user_assign;
102
106 public $subject;
107
111 public $message;
112
116 public $private;
117
123 public $fk_statut;
124
128 public $status;
129
133 public $resolution;
134
138 public $progress;
139
143 public $timing;
144
148 public $type_code;
149
153 public $category_code;
154
158 public $severity_code;
159
163 public $type_label;
164
168 public $category_label;
169
173 public $severity_label;
174
178 public $email_from;
179
183 public $origin_replyto;
184
188 public $origin_references;
189
193 public $datec;
194
198 public $date_read;
199
203 public $date_last_msg_sent;
204
208 public $date_close;
209
213 public $cache_types_tickets;
214
218 public $cache_msgs_ticket;
219
223 public $notify_tiers_at_create;
224
228 public $email_msgid;
229
233 public $email_date;
234
238 public $ip;
239
243 public $lines;
244
248 public $regeximgext = '\.gif|\.jpg|\.jpeg|\.png|\.bmp|\.webp|\.xpm|\.xbm'; // See also into images.lib.php
249
253 const STATUS_NOT_READ = 0; // Draft. Not take into account yet.
254 const STATUS_READ = 1; // Ticket was read.
255 const STATUS_ASSIGNED = 2; // Ticket was just assigned to someone. Not in progress yet.
256 const STATUS_IN_PROGRESS = 3; // In progress
257 const STATUS_NEED_MORE_INFO = 5; // Waiting requester feedback
258 const STATUS_WAITING = 7; // On hold
259 const STATUS_CLOSED = 8; // Closed - Solved
260 const STATUS_CANCELED = 9; // Closed - Not solved
261
262
289 // BEGIN MODULEBUILDER PROPERTIES
290 public $fields = array(
291 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'visible' => -2, 'enabled' => 1, 'position' => 1, 'notnull' => 1, 'index' => 1, 'comment' => "Id"),
292 'entity' => array('type' => 'integer', 'label' => 'Entity', 'visible' => 0, 'enabled' => 1, 'position' => 5, 'notnull' => 1, 'index' => 1),
293 'ref' => array('type' => 'varchar(128)', 'label' => 'Ref', 'visible' => 1, 'enabled' => 1, 'position' => 10, 'notnull' => 1, 'index' => 1, 'searchall' => 1, 'comment' => "Reference of object", 'css' => '', 'showoncombobox' => 1),
294 'track_id' => array('type' => 'varchar(255)', 'label' => 'TicketTrackId', 'visible' => -2, 'enabled' => 1, 'position' => 11, 'notnull' => -1, 'searchall' => 1, 'help' => "Help text"),
295 'fk_user_create' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'Author', 'visible' => 1, 'enabled' => 1, 'position' => 15, 'notnull' => 1, 'csslist' => 'tdoverflowmax100 maxwidth150onsmartphone'),
296 'origin_email' => array('type' => 'mail', 'label' => 'OriginEmail', 'visible' => -2, 'enabled' => 1, 'position' => 16, 'notnull' => 1, 'index' => 1, 'searchall' => 1, 'comment' => "Reference of object", 'csslist' => 'tdoverflowmax150'),
297 'origin_replyto' => array('type' => 'mail', 'label' => 'EmailReplyto', 'visible' => -2, 'enabled' => 1, 'position' => 17, 'notnull' => 1, 'index' => 1, 'searchall' => 1, 'comment' => "Email to reply to", 'csslist' => 'tdoverflowmax150'),
298 'origin_references' => array('type' => 'text', 'label' => 'EmailReferences', 'visible' => -2, 'enabled' => 1, 'position' => 18, 'notnull' => 1, 'index' => 1, 'searchall' => 1, 'comment' => "References from origin email", 'csslist' => 'tdoverflowmax150'),
299 'subject' => array('type' => 'varchar(255)', 'label' => 'Subject', 'visible' => 1, 'enabled' => 1, 'position' => 19, 'notnull' => -1, 'searchall' => 1, 'help' => "", 'css' => 'maxwidth200 tdoverflowmax200', 'csslist' => 'tdoverflowmax250', 'autofocusoncreate' => 1),
300 'type_code' => array('type' => 'varchar(32)', 'label' => 'Type', 'visible' => 1, 'enabled' => 1, 'position' => 20, 'notnull' => -1, 'help' => "", 'csslist' => 'tdoverflowmax100'),
301 'category_code' => array('type' => 'varchar(32)', 'label' => 'TicketCategory', 'visible' => -1, 'enabled' => 1, 'position' => 21, 'notnull' => -1, 'help' => "", 'css' => 'maxwidth100 tdoverflowmax200'),
302 'severity_code' => array('type' => 'varchar(32)', 'label' => 'Severity', 'visible' => 1, 'enabled' => 1, 'position' => 22, 'notnull' => -1, 'help' => "", 'css' => 'maxwidth100 tdoverflowmax100'),
303 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'visible' => 1, 'enabled' => 'isModEnabled("societe")', 'position' => 50, 'notnull' => -1, 'index' => 1, 'searchall' => 1, 'help' => "OrganizationEventLinkToThirdParty", 'css' => 'tdoverflowmax150 maxwidth150onsmartphone'),
304 'notify_tiers_at_create' => array('type' => 'integer', 'label' => 'NotifyThirdparty', 'visible' => -1, 'enabled' => 0, 'position' => 51, 'notnull' => 1, 'index' => 1),
305 'fk_project' => array('type' => 'integer:Project:projet/class/project.class.php', 'label' => 'Project', 'visible' => -1, 'enabled' => 'isModEnabled("project")', 'position' => 52, 'notnull' => -1, 'index' => 1, 'help' => "LinkToProject"),
306 'fk_contract' => array('type' => 'integer:Contrat:contrat/class/contrat.class.php', 'label' => 'Contract', 'visible' => -1, 'enabled' => 'isModEnabled("contract")', 'position' => 53, 'notnull' => -1, 'index' => 1, 'help' => "LinkToContract"),
307 //'timing' => array('type'=>'varchar(20)', 'label'=>'Timing', 'visible'=>-1, 'enabled'=>1, 'position'=>42, 'notnull'=>-1, 'help'=>""), // what is this ?
308 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'visible' => 1, 'enabled' => 1, 'position' => 500, 'notnull' => 1, 'csslist' => 'nowraponall'),
309 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'visible' => -1, 'enabled' => 1, 'position' => 501, 'notnull' => 1),
310 'date_read' => array('type' => 'datetime', 'label' => 'DateReading', 'visible' => -1, 'enabled' => 1, 'position' => 505, 'notnull' => 1, 'csslist' => 'nowraponall'),
311 'date_last_msg_sent' => array('type' => 'datetime', 'label' => 'TicketLastMessageDate', 'visible' => 0, 'enabled' => 1, 'position' => 506, 'notnull' => -1),
312 'fk_user_assign' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'AssignedTo', 'visible' => 1, 'enabled' => 1, 'position' => 507, 'notnull' => 1, 'csslist' => 'tdoverflowmax100 maxwidth150onsmartphone'),
313 'date_close' => array('type' => 'datetime', 'label' => 'TicketCloseOn', 'visible' => -1, 'enabled' => 1, 'position' => 510, 'notnull' => 1),
314 'message' => array('type' => 'html', 'label' => 'Message', 'visible' => -2, 'enabled' => 1, 'position' => 540, 'notnull' => -1,),
315 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 110),
316 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 115),
317 'email_msgid' => array('type' => 'varchar(255)', 'label' => 'EmailMsgID', 'visible' => -2, 'enabled' => 1, 'position' => 540, 'notnull' => -1, 'help' => 'EmailMsgIDDesc', 'csslist' => 'tdoverflowmax100'),
318 'email_date' => array('type' => 'datetime', 'label' => 'EmailDate', 'visible' => -2, 'enabled' => 1, 'position' => 541),
319 'progress' => array('type' => 'integer', 'label' => 'Progression', 'visible' => -1, 'enabled' => 1, 'position' => 540, 'notnull' => -1, 'css' => 'right', 'help' => "", 'isameasure' => 1, 'csslist' => 'width50'),
320 'resolution' => array('type' => 'integer', 'label' => 'Resolution', 'visible' => -1, 'enabled' => 'getDolGlobalString("TICKET_ENABLE_RESOLUTION")', 'position' => 550, 'notnull' => 1),
321 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'PDFTemplate', 'enabled' => 1, 'visible' => 0, 'position' => 560),
322 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => 0, 'position' => 570),
323 'fk_statut' => array('type' => 'integer', 'label' => 'Status', 'visible' => 1, 'enabled' => 1, 'position' => 600, 'notnull' => 1, 'index' => 1, 'arrayofkeyval' => array(0 => 'Unread', 1 => 'Read', 2 => 'Assigned', 3 => 'InProgress', 5 => 'NeedMoreInformation', 7 => 'OnHold', 8 => 'SolvedClosed', 9 => 'Deleted')),
324 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 900),
325 );
326 // END MODULEBUILDER PROPERTIES
327
328
334 public function __construct(DoliDB $db)
335 {
336 $this->db = $db;
337
338 $this->ismultientitymanaged = 1;
339 $this->isextrafieldmanaged = 1;
340
341 $this->labelStatusShort = array(
342 self::STATUS_NOT_READ => 'Unread',
343 self::STATUS_READ => 'Read',
344 self::STATUS_ASSIGNED => 'Assigned',
345 self::STATUS_IN_PROGRESS => 'InProgress',
346 self::STATUS_NEED_MORE_INFO => 'NeedMoreInformationShort',
347 self::STATUS_WAITING => 'OnHold',
348 self::STATUS_CLOSED => 'SolvedClosed',
349 self::STATUS_CANCELED => 'Canceled'
350 );
351 $this->labelStatus = array(
352 self::STATUS_NOT_READ => 'Unread',
353 self::STATUS_READ => 'Read',
354 self::STATUS_ASSIGNED => 'Assigned',
355 self::STATUS_IN_PROGRESS => 'InProgress',
356 self::STATUS_NEED_MORE_INFO => 'NeedMoreInformation',
357 self::STATUS_WAITING => 'OnHold',
358 self::STATUS_CLOSED => 'SolvedClosed',
359 self::STATUS_CANCELED => 'Canceled'
360 );
361
362 if (!getDolGlobalString('TICKET_INCLUDE_SUSPENDED_STATUS')) {
363 unset($this->fields['fk_statut']['arrayofkeyval'][self::STATUS_WAITING]);
364 unset($this->labelStatusShort[self::STATUS_WAITING]);
365 unset($this->labelStatus[self::STATUS_WAITING]);
366 }
367 }
368
375 private function verify()
376 {
377 $this->errors = array();
378
379 $result = 0;
380
381 // Clean parameters
382 if (isset($this->ref)) {
383 $this->ref = trim($this->ref);
384 }
385
386 if (isset($this->track_id)) {
387 $this->track_id = trim($this->track_id);
388 }
389
390 if (isset($this->fk_soc)) {
391 $this->fk_soc = (int) $this->fk_soc;
392 }
393
394 if (isset($this->fk_project)) {
395 $this->fk_project = (int) $this->fk_project;
396 }
397
398 if (isset($this->origin_email)) {
399 $this->origin_email = trim($this->origin_email);
400 }
401
402 if (isset($this->fk_user_create)) {
403 $this->fk_user_create = (int) $this->fk_user_create;
404 }
405
406 if (isset($this->fk_user_assign)) {
407 $this->fk_user_assign = (int) $this->fk_user_assign;
408 }
409
410 if (isset($this->subject)) {
411 $this->subject = trim($this->subject);
412 }
413
414 if (isset($this->message)) {
415 $this->message = trim($this->message);
416 // Field for message is "mediumtext" that has a capacity in bytes (not in chars like it is with varchar), so we must use strlen()
417 if (strlen($this->message) > getDolGlobalInt('TICKET_MAX_LENGTH_FOR_MESSAGE', 16000000)) {
418 global $langs;
419 $langs->loadLangs(array('errors', 'ticket'));
420 $this->errors[] = $langs->trans('ErrorFieldTooLong', $langs->transnoentitiesnoconv('InitialMessage'));
421 dol_syslog(get_class($this).'::create error -1 message too long', LOG_ERR);
422 $result = -1;
423 }
424 }
425
426 if (isset($this->status)) {
427 $this->status = (int) $this->status;
428 }
429
430 if (isset($this->resolution)) {
431 $this->resolution = (int) $this->resolution;
432 }
433
434 if (isset($this->progress)) {
435 $this->progress = (int) $this->progress;
436 }
437
438 if (isset($this->timing)) {
439 $this->timing = trim($this->timing);
440 }
441
442 if (isset($this->type_code)) {
443 $this->type_code = trim($this->type_code);
444 }
445
446 if (isset($this->category_code)) {
447 $this->category_code = trim($this->category_code);
448 }
449
450 if (isset($this->severity_code)) {
451 $this->severity_code = trim($this->severity_code);
452 }
453
454 if (empty($this->ref)) {
455 $this->errors[] = 'ErrorTicketRefRequired';
456 dol_syslog(get_class($this)."::create error -1 ref null", LOG_ERR);
457 $result = -1;
458 }
459
460 return $result;
461 }
462
470 public function checkExistingRef(string $action, string $getRef)
471 {
472 $test = new self($this->db);
473
474 if ($test->fetch(0, $getRef) > 0) {
475 if (($action == 'add') || ($action == 'update' && $this->ref != $getRef)) {
476 return true;
477 }
478 }
479
480 $this->ref = $getRef;
481 return false;
482 }
483
491 public function create($user, $notrigger = 0)
492 {
493 global $conf;
494
495 $error = 0;
496
497 // Clean parameters
498 if (empty($this->datec)) {
499 $this->datec = dol_now();
500 }
501 if (empty($this->track_id)) {
502 $this->track_id = generate_random_id(16);
503 }
504
505 // Check more parameters
506 // If error, this->errors[] is filled
507 $result = $this->verify();
508
509 if ($result >= 0) {
510 // setEntity will set entity with the right value if empty or change it for the right value if multicompany module is active
511 $this->entity = setEntity($this);
512
513 // Insert request
514 $sql = "INSERT INTO ".MAIN_DB_PREFIX."ticket(";
515 $sql .= "ref,";
516 $sql .= "track_id,";
517 $sql .= "fk_soc,";
518 $sql .= "fk_project,";
519 $sql .= "fk_contract,";
520 $sql .= "origin_email,";
521 $sql .= "origin_replyto,";
522 $sql .= "origin_references,";
523 $sql .= "fk_user_create,";
524 $sql .= "fk_user_assign,";
525 $sql .= "email_msgid,";
526 $sql .= "email_date,";
527 $sql .= "subject,";
528 $sql .= "message,";
529 $sql .= "note_private,";
530 $sql .= "note_public,";
531 $sql .= "fk_statut,";
532 $sql .= "resolution,";
533 $sql .= "progress,";
534 $sql .= "timing,";
535 $sql .= "type_code,";
536 $sql .= "category_code,";
537 $sql .= "severity_code,";
538 $sql .= "datec,";
539 $sql .= "date_read,";
540 $sql .= "date_close,";
541 $sql .= "entity,";
542 $sql .= "notify_tiers_at_create,";
543 $sql .= "model_pdf,";
544 $sql .= "ip";
545 $sql .= ") VALUES (";
546 $sql .= " ".(!isset($this->ref) ? '' : "'".$this->db->escape($this->ref)."'").",";
547 $sql .= " ".(!isset($this->track_id) ? 'NULL' : "'".$this->db->escape($this->track_id)."'").",";
548 $sql .= " ".($this->fk_soc > 0 ? ((int) $this->fk_soc) : "null").",";
549 $sql .= " ".($this->fk_project > 0 ? ((int) $this->fk_project) : "null").",";
550 $sql .= " ".($this->fk_contract > 0 ? ((int) $this->fk_contract) : "null").",";
551 $sql .= " ".(!isset($this->origin_email) ? 'NULL' : "'".$this->db->escape($this->origin_email)."'").",";
552 $sql .= " ".(!isset($this->origin_replyto) ? 'NULL' : "'".$this->db->escape($this->origin_replyto)."'").",";
553 $sql .= " ".(!isset($this->origin_references) ? 'NULL' : "'".$this->db->escape($this->origin_references)."'").",";
554 $sql .= " ".(!isset($this->fk_user_create) ? ($user->id > 0 ? ((int) $user->id) : 'NULL') : ($this->fk_user_create > 0 ? ((int) $this->fk_user_create) : 'NULL')).",";
555 $sql .= " ".($this->fk_user_assign > 0 ? ((int) $this->fk_user_assign) : 'NULL').",";
556 $sql .= " ".(empty($this->email_msgid) ? 'NULL' : "'".$this->db->escape($this->email_msgid)."'").",";
557 $sql .= " ".(!isDolTms($this->email_date) ? 'NULL' : "'".$this->db->idate($this->email_date)."'").",";
558 $sql .= " ".(!isset($this->subject) ? 'NULL' : "'".$this->db->escape($this->subject)."'").",";
559 $sql .= " ".(!isset($this->message) ? 'NULL' : "'".$this->db->escape($this->message)."'").",";
560 $sql .= " ".(!isset($this->note_private) ? 'NULL' : "'".$this->db->escape($this->note_private)."'").",";
561 $sql .= " ".(!isset($this->note_public) ? 'NULL' : "'".$this->db->escape($this->note_public)."'").",";
562 $sql .= " ".(!isset($this->status) ? '0' : ((int) $this->status)).",";
563 $sql .= " ".(!isset($this->resolution) ? 'NULL' : ((int) $this->resolution)).",";
564 $sql .= " ".(!isset($this->progress) ? '0' : ((int) $this->progress)).",";
565 $sql .= " ".(!isset($this->timing) ? 'NULL' : "'".$this->db->escape($this->timing)."'").",";
566 $sql .= " ".(!isset($this->type_code) ? 'NULL' : "'".$this->db->escape($this->type_code)."'").",";
567 $sql .= " ".(empty($this->category_code) || $this->category_code == '-1' ? 'NULL' : "'".$this->db->escape($this->category_code)."'").",";
568 $sql .= " ".(!isset($this->severity_code) ? 'NULL' : "'".$this->db->escape($this->severity_code)."'").",";
569 $sql .= " ".(!isDolTms($this->datec) ? 'NULL' : "'".$this->db->idate($this->datec)."'").",";
570 $sql .= " ".(!isset($this->date_read) || dol_strlen((string) $this->date_read) == 0 ? 'NULL' : "'".$this->db->idate($this->date_read)."'").",";
571 $sql .= " ".(!isset($this->date_close) || dol_strlen((string) $this->date_close) == 0 ? 'NULL' : "'".$this->db->idate($this->date_close)."'");
572 $sql .= ", ".((int) $this->entity);
573 $sql .= ", ".(!isset($this->notify_tiers_at_create) ? 1 : ((int) $this->notify_tiers_at_create));
574 $sql .= ", '".$this->db->escape($this->model_pdf)."'";
575 $sql .= ", ".(!isset($this->ip) ? 'NULL' : "'".$this->db->escape($this->ip)."'");
576 $sql .= ")";
577
578 $this->db->begin();
579
580 dol_syslog(get_class($this)."::create", LOG_DEBUG);
581 $resql = $this->db->query($sql);
582 if (!$resql) {
583 $error++;
584 $this->errors[] = "Error ".$this->db->lasterror();
585 }
586
587 if (!$error) {
588 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."ticket");
589 }
590
591 if (!$error && getDolGlobalString('TICKET_ADD_AUTHOR_AS_CONTACT') && empty($this->context["createdfrompublicinterface"])) {
592 // add creator as contributor
593
594 // We first check the type of contact (internal or external)
595 if (!empty($user->socid) && !empty($user->contact_id) && getDolGlobalInt('TICKET_ADD_AUTHOR_AS_CONTACT') == 2) {
596 $contact_type = 'external';
597 $contributor_id = $user->contact_id;
598 } else {
599 $contact_type = 'internal';
600 $contributor_id = $user->id;
601 }
602
603 // We add the creator as contributor
604 if ($this->add_contact($contributor_id, 'CONTRIBUTOR', $contact_type) < 0) {
605 $error++;
606 }
607 }
608
609 if (!$error && $this->fk_user_assign > 0) {
610 if ($this->add_contact($this->fk_user_assign, 'SUPPORTTEC', 'internal') < 0) {
611 $error++;
612 }
613 }
614
615
616 //Update extrafield
617 if (!$error) {
618 $result = $this->insertExtraFields();
619 if ($result < 0) {
620 $error++;
621 }
622 }
623
624 if (!$error && !$notrigger) {
625 // Call trigger
626 $result = $this->call_trigger('TICKET_CREATE', $user);
627 if ($result < 0) {
628 $error++;
629 }
630 // End call triggers
631 }
632
633 // Commit or rollback
634 if ($error) {
635 foreach ($this->errors as $errmsg) {
636 dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
637 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
638 }
639 $this->db->rollback();
640 return -1 * $error;
641 } else {
642 $this->db->commit();
643 return $this->id;
644 }
645 } else {
646 dol_syslog(get_class($this)."::Create fails verify ".implode(',', $this->errors), LOG_WARNING);
647 return -3;
648 }
649 }
650
660 public function fetch($id = 0, $ref = '', $track_id = '', $email_msgid = '')
661 {
662 global $langs;
663
664 // Check parameters
665 if (empty($id) && empty($ref) && empty($track_id) && empty($email_msgid)) {
666 $this->error = 'ErrorWrongParameters';
667 dol_print_error(null, get_class($this)."::fetch ".$this->error);
668 return -1;
669 }
670
671 $sql = "SELECT";
672 $sql .= " t.rowid,";
673 $sql .= " t.entity,";
674 $sql .= " t.ref,";
675 $sql .= " t.track_id,";
676 $sql .= " t.fk_soc,";
677 $sql .= " t.fk_project,";
678 $sql .= " t.fk_contract,";
679 $sql .= " t.origin_email,";
680 $sql .= " t.origin_replyto,";
681 $sql .= " t.origin_references,";
682 $sql .= " t.fk_user_create,";
683 $sql .= " t.fk_user_assign,";
684 $sql .= " t.email_msgid,";
685 $sql .= " t.email_date,";
686 $sql .= " t.subject,";
687 $sql .= " t.message,";
688 $sql .= " t.note_private,";
689 $sql .= " t.note_public,";
690 $sql .= " t.fk_statut as status,";
691 $sql .= " t.resolution,";
692 $sql .= " t.progress,";
693 $sql .= " t.timing,";
694 $sql .= " t.type_code,";
695 $sql .= " t.category_code,";
696 $sql .= " t.severity_code,";
697 $sql .= " t.datec,";
698 $sql .= " t.date_read,";
699 $sql .= " t.date_last_msg_sent,";
700 $sql .= " t.date_close,";
701 $sql .= " t.tms,";
702 $sql .= " t.model_pdf,";
703 $sql .= " t.extraparams,";
704 $sql .= " t.ip,";
705 $sql .= " type.label as type_label, category.label as category_label, severity.label as severity_label";
706 $sql .= " FROM ".MAIN_DB_PREFIX."ticket as t";
707 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_type as type ON type.code=t.type_code";
708 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_category as category ON category.code=t.category_code";
709 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_severity as severity ON severity.code=t.severity_code";
710
711 if ($id) {
712 $sql .= " WHERE t.rowid = ".((int) $id);
713 } else {
714 $sql .= " WHERE t.entity IN (".getEntity($this->element, 1).")";
715 if (!empty($ref)) {
716 $sql .= " AND t.ref = '".$this->db->escape($ref)."'";
717 } elseif ($track_id) {
718 $sql .= " AND t.track_id = '".$this->db->escape($track_id)."'";
719 } else {
720 $sql .= " AND t.email_msgid = '".$this->db->escape($email_msgid)."'";
721 }
722 }
723
724 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
725 $resql = $this->db->query($sql);
726 if ($resql) {
727 if ($this->db->num_rows($resql)) {
728 $obj = $this->db->fetch_object($resql);
729
730 $this->id = $obj->rowid;
731 $this->entity = $obj->entity;
732 $this->ref = $obj->ref;
733 $this->track_id = $obj->track_id;
734 $this->fk_soc = $obj->fk_soc;
735 $this->socid = $obj->fk_soc; // for fetch_thirdparty() method
736 $this->fk_project = $obj->fk_project;
737 $this->fk_contract = $obj->fk_contract;
738 $this->origin_email = $obj->origin_email;
739 $this->origin_replyto = $obj->origin_replyto;
740 $this->origin_references = $obj->origin_references;
741 $this->fk_user_create = $obj->fk_user_create;
742 $this->fk_user_assign = $obj->fk_user_assign;
743 $this->email_msgid = $obj->email_msgid;
744 $this->email_date = $this->db->jdate($obj->email_date);
745 $this->subject = $obj->subject;
746 $this->message = $obj->message;
747 $this->note_private = $obj->note_private;
748 $this->note_public = $obj->note_public;
749 $this->model_pdf = $obj->model_pdf;
750 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
751 $this->ip = $obj->ip;
752
753 $this->status = $obj->status;
754 $this->fk_statut = $this->status; // For backward compatibility
755
756 $this->resolution = $obj->resolution;
757 $this->progress = $obj->progress;
758 $this->timing = $obj->timing;
759
760 $this->type_code = $obj->type_code;
761 // $langs may be null when called from a page with NOREQUIRETRAN (like viewimage.php)
762 $label_type = (is_object($langs) && $langs->trans("TicketTypeShort".$obj->type_code) != "TicketTypeShort".$obj->type_code ? $langs->trans("TicketTypeShort".$obj->type_code) : ($obj->type_label != '-' ? $obj->type_label : ''));
763 $this->type_label = $label_type;
764
765 $this->category_code = $obj->category_code;
766 $label_category = (is_object($langs) && $langs->trans("TicketCategoryShort".$obj->category_code) != "TicketCategoryShort".$obj->category_code ? $langs->trans("TicketCategoryShort".$obj->category_code) : ($obj->category_label != '-' ? $obj->category_label : ''));
767 $this->category_label = $label_category;
768
769 $this->severity_code = $obj->severity_code;
770 $label_severity = (is_object($langs) && $langs->trans("TicketSeverityShort".$obj->severity_code) != "TicketSeverityShort".$obj->severity_code ? $langs->trans("TicketSeverityShort".$obj->severity_code) : ($obj->severity_label != '-' ? $obj->severity_label : ''));
771 $this->severity_label = $label_severity;
772
773 $this->datec = $this->db->jdate($obj->datec);
774 $this->date_creation = $this->db->jdate($obj->datec);
775 $this->date_read = $this->db->jdate($obj->date_read);
776 $this->date_validation = $this->db->jdate($obj->date_read);
777 $this->date_last_msg_sent = $this->db->jdate($obj->date_last_msg_sent);
778 $this->date_close = $this->db->jdate($obj->date_close);
779 $this->tms = $this->db->jdate($obj->tms);
780 $this->date_modification = $this->db->jdate($obj->tms);
781
782 $this->fetch_optionals();
783
784 $this->db->free($resql);
785 return 1;
786 } else {
787 return 0;
788 }
789 } else {
790 $this->error = "Error ".$this->db->lasterror();
791 dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
792 return -1;
793 }
794 }
795
808 public function fetchAll($user, $sortorder = 'ASC', $sortfield = 't.datec', $limit = 0, $offset = 0, $arch = 0, $filter = '')
809 {
810 global $langs, $extrafields;
811
812 // fetch optionals attributes and labels
813 $extrafields->fetch_name_optionals_label($this->table_element);
814
815 $sql = "SELECT";
816 $sql .= " t.rowid,";
817 $sql .= " t.ref,";
818 $sql .= " t.track_id,";
819 $sql .= " t.fk_soc,";
820 $sql .= " t.fk_project,";
821 $sql .= " t.fk_contract,";
822 $sql .= " t.origin_email,";
823 $sql .= " t.origin_replyto,";
824 $sql .= " t.origin_references,";
825 $sql .= " t.fk_user_create, uc.lastname as user_create_lastname, uc.firstname as user_create_firstname,";
826 $sql .= " t.fk_user_assign, ua.lastname as user_assign_lastname, ua.firstname as user_assign_firstname,";
827 $sql .= " t.subject,";
828 $sql .= " t.message,";
829 $sql .= " t.note_private,";
830 $sql .= " t.note_public,";
831 $sql .= " t.fk_statut as status,";
832 $sql .= " t.resolution,";
833 $sql .= " t.progress,";
834 $sql .= " t.timing,";
835 $sql .= " t.type_code,";
836 $sql .= " t.category_code,";
837 $sql .= " t.severity_code,";
838 $sql .= " t.datec,";
839 $sql .= " t.date_read,";
840 $sql .= " t.date_last_msg_sent,";
841 $sql .= " t.date_close,";
842 $sql .= " t.tms,";
843 $sql .= " type.label as type_label, category.label as category_label, severity.label as severity_label";
844 // Add fields for extrafields
845 if ($extrafields->attributes[$this->table_element]['count'] > 0) {
846 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
847 $sql .= ($extrafields->attributes[$this->table_element]['type'][$key] != 'separate' ? ",ef.".$key." as options_".$key : '');
848 }
849 }
850 $sql .= " FROM ".MAIN_DB_PREFIX."ticket as t";
851 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_type as type ON type.code = t.type_code";
852 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_category as category ON category.code = t.category_code";
853 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_severity as severity ON severity.code = t.severity_code";
854 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = t.fk_soc";
855 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as uc ON uc.rowid = t.fk_user_create";
856 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as ua ON ua.rowid = t.fk_user_assign";
857 if ($extrafields->attributes[$this->table_element]['count'] > 0) {
858 if (is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label'])) {
859 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."ticket_extrafields as ef on (t.rowid = ef.fk_object)";
860 }
861 }
862 $sql .= " WHERE t.entity IN (".getEntity('ticket').")";
863
864 // Manage filter
865 if (is_array($filter)) {
866 foreach ($filter as $key => $value) {
867 if (strpos($key, 'date')) { // To allow $filter['YEAR(s.dated)']=>$year
868 $sql .= " AND ".$this->db->sanitize($key)." = '".$this->db->escape((string) $value)."'";
869 } elseif (($key == 't.fk_user_assign') || ($key == 't.type_code') || ($key == 't.category_code') || ($key == 't.severity_code') || ($key == 't.fk_soc')) {
870 $sql .= " AND ".$this->db->sanitize($key)." = '".$this->db->escape((string) $value)."'";
871 } elseif ($key == 't.fk_statut') {
872 if (is_array($value) && count($value) > 0) {
873 $sql .= " AND ".$this->db->sanitize($key)." IN (".$this->db->sanitize(implode(',', $value)).")";
874 } else {
875 $sql .= " AND ".$this->db->sanitize($key).' = '.((int) $value);
876 }
877 } elseif ($key == 't.fk_contract') {
878 $sql .= " AND ".$this->db->sanitize($key).' = '.((int) $value);
879 } else {
880 $sql .= " AND ".$this->db->sanitize($key)." LIKE '%".$this->db->escape($this->db->escapeforlike((string) $value))."%'";
881 }
882 }
883
884 $filter = '';
885 }
886
887 // Manage filter
888 $errormessage = '';
889 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
890 if ($errormessage) {
891 $this->errors[] = $errormessage;
892 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
893 return -1;
894 }
895
896 // Case of external user
897 $socid = $user->socid ?: 0;
898 // If the internal user must only see his customers, force searching by him
899 $search_sale = 0;
900 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
901 $search_sale = $user->id;
902 }
903 // Search on sale representative
904 if ($search_sale && $search_sale != '-1') {
905 if ($search_sale == -2) {
906 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
907 } elseif ($search_sale > 0) {
908 $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc AND sc.fk_user = ".((int) $search_sale).")";
909 }
910 }
911 // Search on socid
912 if ($socid) {
913 $sql .= " AND t.fk_soc = ".((int) $socid);
914 }
915
916 $sql .= $this->db->order($sortfield, $sortorder);
917 if (!empty($limit)) {
918 $sql .= $this->db->plimit($limit + 1, $offset);
919 }
920
921 dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG);
922 $resql = $this->db->query($sql);
923
924 if ($resql) {
925 $this->lines = array();
926
927 $num = $this->db->num_rows($resql);
928 $i = 0;
929
930 if ($num) {
931 while ($i < $num) {
932 $obj = $this->db->fetch_object($resql);
933
934 $line = new self($this->db);
935
936 $line->id = $obj->rowid;
937 //$line->rowid = $obj->rowid;
938 $line->ref = $obj->ref;
939 $line->track_id = $obj->track_id;
940 $line->fk_soc = $obj->fk_soc;
941 $line->fk_project = $obj->fk_project;
942 $line->fk_contract = $obj->fk_contract;
943 $line->origin_email = $obj->origin_email;
944 $line->origin_replyto = $obj->origin_replyto;
945 $line->origin_references = $obj->origin_references;
946
947 $line->fk_user_create = $obj->fk_user_create;
948 $line->fk_user_assign = $obj->fk_user_assign;
949
950 $line->subject = $obj->subject;
951 $line->message = $obj->message;
952 $line->note_private = $obj->note_private;
953 $line->note_public = $obj->note_public;
954 $line->fk_statut = $obj->status;
955 $line->status = $obj->status;
956 $line->resolution = $obj->resolution;
957 $line->progress = $obj->progress;
958 $line->timing = $obj->timing;
959
960 $label_type = ($langs->trans("TicketTypeShort".$obj->type_code) != "TicketTypeShort".$obj->type_code ? $langs->trans("TicketTypeShort".$obj->type_code) : ($obj->type_label != '-' ? $obj->type_label : ''));
961 $line->type_label = $label_type;
962
963 $this->category_code = $obj->category_code;
964 $label_category = ($langs->trans("TicketCategoryShort".$obj->category_code) != "TicketCategoryShort".$obj->category_code ? $langs->trans("TicketCategoryShort".$obj->category_code) : ($obj->category_label != '-' ? $obj->category_label : ''));
965 $line->category_label = $label_category;
966
967 $this->severity_code = $obj->severity_code;
968 $label_severity = ($langs->trans("TicketSeverityShort".$obj->severity_code) != "TicketSeverityShort".$obj->severity_code ? $langs->trans("TicketSeverityShort".$obj->severity_code) : ($obj->severity_label != '-' ? $obj->severity_label : ''));
969 $line->severity_label = $label_severity;
970
971 $line->datec = $this->db->jdate($obj->datec);
972 $line->date_read = $this->db->jdate($obj->date_read);
973 $line->date_last_msg_sent = $this->db->jdate($obj->date_last_msg_sent);
974 $line->date_close = $this->db->jdate($obj->date_close);
975
976 // Extra fields
977 if ($extrafields->attributes[$this->table_element]['count'] > 0) {
978 if (is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label'])) {
979 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
980 $tmpkey = 'options_'.$key;
981 $line->{$tmpkey} = $obj->$tmpkey;
982 }
983 }
984 }
985 $this->lines[$i] = $line;
986 $i++;
987 }
988 }
989 $this->db->free($resql);
990 return $num;
991 } else {
992 $this->error = "Error ".$this->db->lasterror();
993 dol_syslog(get_class($this)."::fetchAll ".$this->error, LOG_ERR);
994 return -1;
995 }
996 }
997
1005 public function update($user, $notrigger = 0)
1006 {
1007 $error = 0;
1008
1009 // $this->oldcopy should have been set by the caller of update
1010 //if (empty($this->oldcopy)) {
1011 // dol_syslog("this->oldcopy should have been set by the caller of update (here properties were already modified)", LOG_WARNING);
1012 // $this->oldcopy = dol_clone($this, 2);
1013 //}
1014
1015 // Clean parameters
1016 if (isset($this->ref)) {
1017 $this->ref = trim($this->ref);
1018 }
1019
1020 if (isset($this->track_id)) {
1021 $this->track_id = trim($this->track_id);
1022 }
1023
1024 if (isset($this->fk_soc)) {
1025 $this->fk_soc = (int) $this->fk_soc;
1026 }
1027
1028 if (isset($this->fk_project)) {
1029 $this->fk_project = (int) $this->fk_project;
1030 }
1031
1032 if (isset($this->fk_contract)) {
1033 $this->fk_contract = (int) $this->fk_contract;
1034 }
1035
1036 if (isset($this->origin_email)) {
1037 $this->origin_email = trim($this->origin_email);
1038 }
1039
1040 if (isset($this->fk_user_create)) {
1041 $this->fk_user_create = (int) $this->fk_user_create;
1042 }
1043
1044 if (isset($this->fk_user_assign)) {
1045 $this->fk_user_assign = (int) $this->fk_user_assign;
1046 }
1047
1048 if (isset($this->subject)) {
1049 $this->subject = trim($this->subject);
1050 }
1051
1052 if (isset($this->message)) {
1053 $this->message = trim($this->message);
1054 // Field for message is "mediumtext" that has a capacity in bytes (not in chars like it is with varchar), so we must use strlen()
1055 if (strlen($this->message) > getDolGlobalInt('TICKET_MAX_LENGTH_FOR_MESSAGE', 16000000)) {
1056 global $langs;
1057 $langs->loadLangs(array('errors', 'ticket'));
1058 $this->errors[] = $langs->trans('ErrorFieldTooLong', $langs->transnoentitiesnoconv('InitialMessage'));
1059 dol_syslog(get_class($this).'::update error -1 message too long', LOG_ERR);
1060 return -1;
1061 }
1062 }
1063
1064 if (isset($this->status)) {
1065 $this->status = (int) $this->status;
1066 }
1067
1068 if (isset($this->resolution)) {
1069 $this->resolution = (int) $this->resolution;
1070 }
1071
1072 if (isset($this->progress)) {
1073 $this->progress = (int) $this->progress;
1074 }
1075
1076 if (isset($this->timing)) {
1077 $this->timing = trim($this->timing);
1078 }
1079
1080 if (isset($this->type_code)) {
1081 $this->type_code = trim($this->type_code);
1082 }
1083
1084 if (isset($this->category_code)) {
1085 $this->category_code = trim($this->category_code);
1086 }
1087
1088 if (isset($this->severity_code)) {
1089 $this->severity_code = trim($this->severity_code);
1090 }
1091 if (isset($this->model_pdf)) {
1092 $this->model_pdf = trim($this->model_pdf);
1093 }
1094 // Check parameters
1095 // Put here code to add a control on parameters values
1096 // Update request
1097 $sql = "UPDATE ".MAIN_DB_PREFIX."ticket SET";
1098 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "").",";
1099 $sql .= " track_id=".(isset($this->track_id) ? "'".$this->db->escape($this->track_id)."'" : "null").",";
1100 $sql .= " fk_soc=".(isset($this->fk_soc) ? (int) $this->fk_soc : "null").",";
1101 $sql .= " fk_project=".(isset($this->fk_project) ? (int) $this->fk_project : "null").",";
1102 $sql .= " fk_contract=".(isset($this->fk_contract) ? (int) $this->fk_contract : "null").",";
1103 $sql .= " origin_email=".(isset($this->origin_email) ? "'".$this->db->escape($this->origin_email)."'" : "null").",";
1104 $sql .= " origin_replyto=".(isset($this->origin_replyto) ? "'".$this->db->escape($this->origin_replyto)."'" : "null").",";
1105 $sql .= " origin_references=".(isset($this->origin_references) ? "'".$this->db->escape($this->origin_references)."'" : "null").",";
1106 $sql .= " fk_user_create=".(isset($this->fk_user_create) ? (int) $this->fk_user_create : "null").",";
1107 $sql .= " fk_user_assign=".(isset($this->fk_user_assign) ? (int) $this->fk_user_assign : "null").",";
1108 $sql .= " subject=".(isset($this->subject) ? "'".$this->db->escape($this->subject)."'" : "null").",";
1109 $sql .= " message=".(isset($this->message) ? "'".$this->db->escape($this->message)."'" : "null").",";
1110 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1111 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1112 $sql .= " fk_statut=".(isset($this->status) ? (int) $this->status : "0").",";
1113 $sql .= " resolution=".(isset($this->resolution) ? (int) $this->resolution : "null").",";
1114 $sql .= " progress=".(isset($this->progress) ? "'".$this->db->escape((string) $this->progress)."'" : "null").",";
1115 $sql .= " timing=".(isset($this->timing) ? "'".$this->db->escape($this->timing)."'" : "null").",";
1116 $sql .= " type_code=".(isset($this->type_code) ? "'".$this->db->escape($this->type_code)."'" : "null").",";
1117 $sql .= " category_code=".(isset($this->category_code) ? "'".$this->db->escape($this->category_code)."'" : "null").",";
1118 $sql .= " severity_code=".(isset($this->severity_code) ? "'".$this->db->escape($this->severity_code)."'" : "null").",";
1119 $sql .= " datec=".(isDolTms($this->datec) ? "'".$this->db->idate($this->datec)."'" : 'null').",";
1120 $sql .= " date_read=".(dol_strlen((string) $this->date_read) != 0 ? "'".$this->db->idate($this->date_read)."'" : 'null').",";
1121 $sql .= " date_last_msg_sent=".(dol_strlen((string) $this->date_last_msg_sent) != 0 ? "'".$this->db->idate($this->date_last_msg_sent)."'" : 'null').",";
1122 $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
1123 $sql .= " date_close=".(dol_strlen((string) $this->date_close) != 0 ? "'".$this->db->idate($this->date_close)."'" : 'null');
1124 $sql .= " WHERE rowid=".((int) $this->id);
1125
1126 $this->db->begin();
1127
1128 $resql = $this->db->query($sql);
1129 if (!$resql) {
1130 $error++;
1131 $this->errors[] = "Error ".$this->db->lasterror();
1132 }
1133
1134 if (!$error) {
1135 // Update extrafields
1136 $result = $this->insertExtraFields();
1137 if ($result < 0) {
1138 $error++;
1139 }
1140 }
1141
1142 if (!$error && !$notrigger) {
1143 // Call trigger
1144 $result = $this->call_trigger('TICKET_MODIFY', $user);
1145 if ($result < 0) {
1146 $error++;
1147 }
1148 // End call triggers
1149 }
1150
1151 // Commit or rollback
1152 if ($error) {
1153 foreach ($this->errors as $errmsg) {
1154 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1155 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1156 }
1157 $this->db->rollback();
1158 return -1 * $error;
1159 } else {
1160 $this->db->commit();
1161 return 1;
1162 }
1163 }
1164
1172 public function delete($user, $notrigger = 0)
1173 {
1174 $error = 0;
1175
1176 $this->db->begin();
1177
1178 if (!$notrigger) {
1179 // Call trigger
1180 $result = $this->call_trigger('TICKET_DELETE', $user);
1181 if ($result < 0) {
1182 $error++;
1183 }
1184 // End call triggers
1185 }
1186
1187 if (!$error) {
1188 // Delete linked contacts
1189 $res = $this->delete_linked_contact();
1190 if ($res < 0) {
1191 dol_syslog(get_class($this)."::delete error", LOG_ERR);
1192 $error++;
1193 }
1194 }
1195
1196 if (!$error) {
1197 // Delete linked object
1198 $res = $this->deleteObjectLinked();
1199 if ($res < 0) {
1200 $error++;
1201 }
1202 }
1203
1204 // Removed extrafields
1205 if (!$error) {
1206 $result = $this->deleteExtraFields();
1207 if ($result < 0) {
1208 $error++;
1209 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1210 }
1211 }
1212
1213 // Delete all child tables
1214
1215 if (!$error) {
1216 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_ticket";
1217 $sql .= " WHERE fk_ticket = ".(int) $this->id;
1218
1219 $result = $this->db->query($sql);
1220 if (!$result) {
1221 $error++;
1222 $this->errors[] = $this->db->lasterror();
1223 }
1224 }
1225
1226 if (!$error) {
1227 $sql = "DELETE FROM ".MAIN_DB_PREFIX."ticket";
1228 $sql .= " WHERE rowid=".((int) $this->id);
1229
1230 dol_syslog(get_class($this)."::delete sql=".$sql);
1231 $resql = $this->db->query($sql);
1232 if (!$resql) {
1233 $error++;
1234 $this->errors[] = "Error ".$this->db->lasterror();
1235 } else {
1236 // we delete file with dol_delete_dir_recursive
1237 $this->deleteEcmFiles(1);
1238
1239 $dir = DOL_DATA_ROOT.'/'.$this->element.'/'.$this->ref;
1240 // For remove dir
1241 if (dol_is_dir($dir)) {
1242 if (!dol_delete_dir_recursive($dir)) {
1243 $this->errors[] = $this->error;
1244 }
1245 }
1246 }
1247 }
1248
1249 // Commit or rollback
1250 if ($error) {
1251 foreach ($this->errors as $errmsg) {
1252 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
1253 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1254 }
1255 $this->db->rollback();
1256 return -1 * $error;
1257 } else {
1258 $this->db->commit();
1259 return 1;
1260 }
1261 }
1262
1270 public function createFromClone(User $user, $fromid)
1271 {
1272 $error = 0;
1273
1274 $object = new Ticket($this->db);
1275
1276 $this->db->begin();
1277
1278 // Load source object
1279 $object->fetch($fromid);
1280
1281 // Clear fields
1282 $object->id = 0;
1283 $object->statut = 0;
1284 $object->status = 0;
1285 $object->ref = $object->getDefaultRef();
1286 $object->track_id = generate_random_id(16);
1287 $object->progress = 0;
1288 // Reset lifecycle timestamps so the clone starts fresh: datec is filled by
1289 // create() with dol_now() when empty, date_read and date_close stay null
1290 // because the new ticket has not been read or closed yet (see issue #38559).
1291 // Reset lifecycle timestamps and resolution so the clone starts fresh.
1292 // datec stays at 0 so Ticket::create()'s `if (empty($this->datec))` guard
1293 // fills it with dol_now(). date_read / date_close / resolution are unset
1294 // so the SQL writers' `!isset` checks emit NULL. We use these forms
1295 // rather than `= null` so phpstan stays happy with the int-typed
1296 // property declarations.
1297 $object->datec = 0;
1298 unset($object->date_read);
1299 unset($object->date_close);
1300 unset($object->resolution);
1301
1302 // Create clone
1303 $object->context['createfromclone'] = 'createfromclone';
1304 $result = $object->create($user);
1305
1306 // Other options
1307 if ($result < 0) {
1308 $this->error = $object->error;
1309 $error++;
1310 }
1311
1312 unset($object->context['createfromclone']);
1313
1314 // End
1315 if (!$error) {
1316 $this->db->commit();
1317 return $object->id;
1318 } else {
1319 $this->db->rollback();
1320 return -1;
1321 }
1322 }
1323
1330 public function initAsSpecimen()
1331 {
1332 $this->id = 0;
1333 $this->entity = 1;
1334 $this->ref = 'TI0501-001';
1335 $this->track_id = 'XXXXaaaa';
1336 $this->origin_email = 'email@email.com';
1337 $this->fk_project = 1;
1338 $this->fk_user_create = 1;
1339 $this->fk_user_assign = 1;
1340 $this->subject = 'Subject of ticket';
1341 $this->message = 'Message of ticket';
1342 $this->status = 0;
1343 $this->resolution = 1;
1344 $this->progress = 10;
1345 // $this->timing = '30';
1346 $this->type_code = 'TYPECODE';
1347 $this->category_code = 'CATEGORYCODE';
1348 $this->severity_code = 'SEVERITYCODE';
1349 $this->datec = dol_now();
1350 $this->date_read = dol_now();
1351 $this->date_last_msg_sent = dol_now();
1352 $this->date_close = dol_now();
1353 $this->tms = dol_now();
1354
1355 return 1;
1356 }
1357
1364 public function printSelectStatus($selected = "")
1365 {
1366 print Form::selectarray('search_fk_statut', $this->labelStatusShort, $selected, $show_empty = 1, $key_in_label = 0, $value_as_key = 0, $option = '', $translate = 1, $maxlen = 0, $disabled = 0, $sort = '', $morecss = '');
1367 }
1368
1369
1375 public function loadCacheTypesTickets()
1376 {
1377 global $langs, $hookmanager;
1378
1379 if (!empty($this->cache_types_tickets) && count($this->cache_types_tickets)) {
1380 return 0;
1381 }
1382 // Cache deja charge
1383
1384 // entity is returned so a hook on loadDictionaryCache can tell two rows apart when the
1385 // dictionary is read across entities
1386 $sql = "SELECT rowid, entity, code, label, use_default, pos, description";
1387 $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_type";
1388 $sql .= " WHERE entity IN (".getEntity('c_ticket_type').")";
1389 $sql .= " AND active > 0";
1390 $sql .= " ORDER BY pos";
1391 dol_syslog(get_class($this)."::load_cache_type_tickets", LOG_DEBUG);
1392 $resql = $this->db->query($sql);
1393 if ($resql) {
1394 $num = $this->db->num_rows($resql);
1395 $i = 0;
1396 while ($i < $num) {
1397 $obj = $this->db->fetch_object($resql);
1398 $label = ($langs->trans("TicketTypeShort".$obj->code) != "TicketTypeShort".$obj->code ? $langs->trans("TicketTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
1399 $this->cache_types_tickets[$obj->rowid]['code'] = $obj->code;
1400 $this->cache_types_tickets[$obj->rowid]['label'] = $label;
1401 $this->cache_types_tickets[$obj->rowid]['use_default'] = $obj->use_default;
1402 $this->cache_types_tickets[$obj->rowid]['pos'] = $obj->pos;
1403 $this->cache_types_tickets[$obj->rowid]['entity'] = (int) $obj->entity;
1404 $i++;
1405 }
1406
1407 $parameters = array('dictionary' => 'tickettype');
1408 $reshook = $hookmanager->executeHooks('loadDictionaryCache', $parameters, $this); // Note that $action and $object may have been modified by hook
1409 if (empty($reshook)) {
1410 if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
1411 $this->cache_types_tickets = array_merge($this->cache_types_tickets, $hookmanager->resArray);
1412 }
1413 } else {
1414 $this->cache_types_tickets = $hookmanager->resArray;
1415 }
1416
1417 return count($this->cache_types_tickets);
1418 } else {
1419 dol_print_error($this->db);
1420 return -1;
1421 }
1422 }
1423
1430 public function loadCacheCategoriesTickets($publicgroup = -1)
1431 {
1432 global $conf, $langs, $hookmanager;
1433
1434 if ($publicgroup == -1 && !empty($conf->cache['category_tickets']) && count($conf->cache['category_tickets'])) {
1435 // Cache already loaded
1436 return 0;
1437 }
1438
1439 // entity is returned so a hook on loadDictionaryCache can tell two rows apart when the
1440 // dictionary is read across entities
1441 $sql = "SELECT rowid, entity, code, label, use_default, pos, description, public, active, force_severity, fk_parent";
1442 $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_category";
1443 $sql .= " WHERE entity IN (".getEntity('c_ticket_category').")";
1444 $sql .= " AND active > 0";
1445 if ($publicgroup > -1) {
1446 $sql .= " AND public = ".((int) $publicgroup);
1447 }
1448 $sql .= " ORDER BY pos";
1449
1450 dol_syslog(get_class($this)."::load_cache_categories_tickets", LOG_DEBUG);
1451
1452 $resql = $this->db->query($sql);
1453 if ($resql) {
1454 $num = $this->db->num_rows($resql);
1455 $i = 0;
1456 $categorytickets = array();
1457 '@phan-var-force array<int,array{code:string,label:string,use_default:int,pos:int,public:int,active:int,force_severity:?string,fk_parent:int}> $categorytickets';
1458 while ($i < $num) {
1459 $obj = $this->db->fetch_object($resql);
1460 $categorytickets[$obj->rowid]['code'] = $obj->code;
1461 $categorytickets[$obj->rowid]['use_default'] = $obj->use_default;
1462 $categorytickets[$obj->rowid]['pos'] = $obj->pos;
1463 $categorytickets[$obj->rowid]['public'] = $obj->public;
1464 $categorytickets[$obj->rowid]['active'] = $obj->active;
1465 $categorytickets[$obj->rowid]['force_severity'] = $obj->force_severity;
1466 $categorytickets[$obj->rowid]['fk_parent'] = $obj->fk_parent;
1467
1468 // If translation exists, we use it to store already translated string.
1469 // Warning: You should not use this and recompute the translated string into caller code to get the value into expected language
1470 $label = ($langs->trans("TicketCategoryShort".$obj->code) != "TicketCategoryShort".$obj->code ? $langs->trans("TicketCategoryShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
1471 $categorytickets[$obj->rowid]['label'] = $label;
1472 $categorytickets[$obj->rowid]['entity'] = (int) $obj->entity;
1473
1474 $i++;
1475 }
1476 $conf->cache['category_tickets'] = $categorytickets;
1477
1478 $parameters = array('dictionary' => 'ticketcategory', 'publicgroup' => $publicgroup);
1479 $reshook = $hookmanager->executeHooks('loadDictionaryCache', $parameters, $this); // Note that $action and $object may have been modified by hook
1480 if (empty($reshook)) {
1481 if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
1482 $conf->cache['category_tickets'] = array_merge($conf->cache['category_tickets'], $hookmanager->resArray);
1483 }
1484 } else {
1485 $conf->cache['category_tickets'] = $hookmanager->resArray;
1486 }
1487
1488 return count($conf->cache['category_tickets']);
1489 } else {
1490 dol_print_error($this->db);
1491 return -1;
1492 }
1493 }
1494
1501 {
1502 global $conf, $langs, $hookmanager;
1503
1504 if (!empty($conf->cache['severity_tickets']) && count($conf->cache['severity_tickets'])) {
1505 // Cache already loaded
1506 return 0;
1507 }
1508
1509 // entity is returned so a hook on loadDictionaryCache can tell two rows apart when the
1510 // dictionary is read across entities
1511 $sql = "SELECT rowid, entity, code, label, use_default, pos, description";
1512 $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_severity";
1513 $sql .= " WHERE entity IN (".getEntity('c_ticket_severity').")";
1514 $sql .= " AND active > 0";
1515 $sql .= " ORDER BY pos";
1516 dol_syslog(get_class($this)."::loadCacheSeveritiesTickets", LOG_DEBUG);
1517 $resql = $this->db->query($sql);
1518 if ($resql) {
1519 $num = $this->db->num_rows($resql);
1520 $i = 0;
1521 $severitytickets = array();
1522 '@phan-var-force array<int,array{code:string,label:string,use_default:int,pos:int}> $severitytickets';
1523 while ($i < $num) {
1524 $obj = $this->db->fetch_object($resql);
1525
1526 $severitytickets[$obj->rowid]['code'] = $obj->code;
1527 $label = ($langs->trans("TicketSeverityShort".$obj->code) != "TicketSeverityShort".$obj->code ? $langs->trans("TicketSeverityShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
1528 $severitytickets[$obj->rowid]['label'] = $label;
1529 $severitytickets[$obj->rowid]['use_default'] = $obj->use_default;
1530 $severitytickets[$obj->rowid]['pos'] = $obj->pos;
1531 $severitytickets[$obj->rowid]['entity'] = (int) $obj->entity;
1532 $i++;
1533 }
1534 $conf->cache['severity_tickets'] = $severitytickets;
1535
1536 $parameters = array('dictionary' => 'ticketseverity');
1537 $reshook = $hookmanager->executeHooks('loadDictionaryCache', $parameters, $this); // Note that $action and $object may have been modified by hook
1538 if (empty($reshook)) {
1539 if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
1540 $conf->cache['severity_tickets'] = array_merge($conf->cache['severity_tickets'], $hookmanager->resArray);
1541 }
1542 } else {
1543 $conf->cache['severity_tickets'] = $hookmanager->resArray;
1544 }
1545
1546 return count($conf->cache['severity_tickets']);
1547 } else {
1548 dol_print_error($this->db);
1549 return -1;
1550 }
1551 }
1552
1553
1560 public function getLibStatut($mode = 0)
1561 {
1562 return $this->LibStatut($this->status, $mode, 0, $this->progress);
1563 }
1564
1565
1566 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1576 public function LibStatut($status, $mode = 0, $notooltip = 0, $progress = 0)
1577 {
1578 // phpcs:enable
1579 global $langs, $hookmanager;
1580
1581 $labelStatus = (isset($status) && !empty($this->labelStatus[$status])) ? $this->labelStatus[$status] : '';
1582 $labelStatusShort = (isset($status) && !empty($this->labelStatusShort[$status])) ? $this->labelStatusShort[$status] : '';
1583 $statusType = '';
1584
1585 $isUnknown = false;
1586 switch ($status) {
1587 case self::STATUS_NOT_READ: // Not read
1588 $statusType = 'status0';
1589 break;
1590 case self::STATUS_READ: // Read
1591 $statusType = 'status1';
1592 break;
1593 case self::STATUS_ASSIGNED: // Assigned
1594 $statusType = 'status2';
1595 break;
1596 case self::STATUS_IN_PROGRESS: // In progress
1597 $statusType = 'status4';
1598 break;
1599 case self::STATUS_WAITING: // Waiting/pending/suspended
1600 $statusType = 'status7';
1601 break;
1602 case self::STATUS_NEED_MORE_INFO: // Waiting more information from the requester
1603 $statusType = 'status3';
1604 break;
1605 case self::STATUS_CANCELED: // Canceled
1606 $statusType = 'status9';
1607 break;
1608 case self::STATUS_CLOSED: // Closed
1609 $statusType = 'status6';
1610 break;
1611 default:
1612 $isUnknown = true;
1613 break;
1614 }
1615
1616 $parameters = array(
1617 'status' => $status,
1618 'mode' => $mode,
1619 );
1620
1621 // Note that $action and $object may have been modified by hook
1622 $reshook = $hookmanager->executeHooks('LibStatut', $parameters, $this);
1623
1624 if ($reshook > 0) {
1625 return $hookmanager->resPrint;
1626 }
1627
1628 if ($isUnknown) {
1629 $labelStatus = 'Unknown';
1630 $labelStatusShort = 'Unknown';
1631 $statusType = 'status0';
1632 $mode = 0;
1633 }
1634
1635 $params = array();
1636 if ($notooltip) {
1637 $params = array('tooltip' => 'no');
1638 }
1639
1640 $labelStatus = $langs->transnoentitiesnoconv($labelStatus);
1641 $labelStatusShort = $langs->transnoentitiesnoconv($labelStatusShort);
1642
1643 if ($status == self::STATUS_IN_PROGRESS && $progress > 0) {
1644 $labelStatus .= ' ('.round($progress).'%)';
1645 $labelStatusShort .= ' ('.round($progress).'%)';
1646 }
1647
1648 return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode, '', $params);
1649 }
1650
1657 public function getTooltipContentArray($params)
1658 {
1659 global $langs;
1660
1661 $langs->load('ticket');
1662 $nofetch = !empty($params['nofetch']);
1663
1664 $datas = array();
1665 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Ticket").'</u>';
1666 $datas['picto'] .= ' '.$this->getLibStatut(4);
1667 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1668 $datas['track_id'] = '<br><b>'.$langs->trans('TicketTrackId').':</b> '.$this->track_id;
1669 $datas['subject'] = '<br><b>'.$langs->trans('Subject').':</b> '.$this->subject;
1670 if ($this->date_creation) {
1671 $datas['date_creation'] = '<br><b>'.$langs->trans('DateCreation').':</b> '.dol_print_date($this->date_creation, 'dayhour');
1672 }
1673 if ($this->date_modification) {
1674 $datas['date_modification'] = '<br><b>'.$langs->trans('DateModification').':</b> '.dol_print_date($this->date_modification, 'dayhour');
1675 }
1676 // show categories for this record only in ajax to not overload lists
1677 if (isModEnabled('category') && !$nofetch) {
1678 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
1679 $form = new Form($this->db);
1680 $datas['categories'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_TICKET, 1);
1681 }
1682
1683 return $datas;
1684 }
1685
1696 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
1697 {
1698 global $action, $conf, $hookmanager, $langs;
1699
1700 if (!empty($conf->dol_no_mouse_hover)) {
1701 $notooltip = 1; // Force disable tooltips
1702 }
1703
1704 $result = '';
1705
1706 $params = [
1707 'id' => $this->id,
1708 'objecttype' => $this->element,
1709 'option' => $option,
1710 'nofetch' => 1,
1711 ];
1712 $classfortooltip = 'classfortooltip';
1713 $dataparams = '';
1714 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1715 $classfortooltip = 'classforajaxtooltip';
1716 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1717 $label = '';
1718 } else {
1719 $label = implode($this->getTooltipContentArray($params));
1720 }
1721
1722 $query = ['id' => $this->id];
1723
1724 if ($option != 'nolink') {
1725 // Add param to save lastsearch_values or not
1726 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1727 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1728 $add_save_lastsearch_values = 1;
1729 }
1730 if ($add_save_lastsearch_values) {
1731 $query['save_lastsearch_values'] = 1;
1732 }
1733 }
1734 $url = dolBuildUrl(DOL_URL_ROOT.'/ticket/card.php', $query);
1735
1736 $linkclose = '';
1737 if (empty($notooltip)) {
1738 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1739 $label = $langs->trans("ShowTicket");
1740 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1741 }
1742 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
1743 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
1744 } else {
1745 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1746 }
1747
1748 $linkstart = '<a href="'.$url.'"';
1749 $linkstart .= $linkclose.'>';
1750 $linkend = '</a>';
1751
1752 $result .= $linkstart;
1753 if ($withpicto) {
1754 $result .= img_object(($notooltip ? '' : $label), ($this->picto ?: 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
1755 }
1756 if ($withpicto != 2) {
1757 $result .= $this->ref;
1758 }
1759 $result .= $linkend;
1760 //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
1761
1762 $hookmanager->initHooks(array('ticketdao'));
1763 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1764 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1765 if ($reshook > 0) {
1766 $result = $hookmanager->resPrint;
1767 } else {
1768 $result .= $hookmanager->resPrint;
1769 }
1770
1771 return $result;
1772 }
1773
1774
1782 public function markAsRead($user, $notrigger = 0)
1783 {
1784 global $langs;
1785
1786 $error = 0;
1787
1788 if ($this->status != self::STATUS_CANCELED) { // no closed
1789 $this->oldcopy = dol_clone($this, 2);
1790
1791 $this->db->begin();
1792
1793 $this->status = Ticket::STATUS_READ;
1794
1795 $sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
1796 $sql .= " SET fk_statut = ".((int) $this->status) .", date_read = '".$this->db->idate(dol_now())."'";
1797 $sql .= " WHERE rowid = ".((int) $this->id);
1798
1799 dol_syslog(get_class($this)."::markAsRead");
1800 $resql = $this->db->query($sql);
1801 if ($resql) {
1802 $this->context['actionmsg'] = $langs->trans('TicketLogMesgReadBy', $this->ref, $user->getFullName($langs));
1803 $this->context['actionmsg2'] = $langs->trans('TicketLogMesgReadBy', $this->ref, $user->getFullName($langs));
1804
1805 if (!$notrigger) {
1806 // Call trigger
1807 $result = $this->call_trigger('TICKET_MODIFY', $user);
1808 if ($result < 0) {
1809 $error++;
1810 }
1811 // End call triggers
1812 }
1813
1814 if (!$error) {
1815 $this->db->commit();
1816 return 1;
1817 } else {
1818 $this->status = $this->oldcopy->status;
1819
1820 $this->db->rollback();
1821
1822 $this->error = implode(',', $this->errors);
1823
1824 dol_syslog(get_class($this)."::markAsRead ".$this->error, LOG_ERR);
1825 return -1;
1826 }
1827 } else {
1828 $this->status = $this->oldcopy->status;
1829
1830 $this->db->rollback();
1831 $this->error = $this->db->lasterror();
1832 dol_syslog(get_class($this)."::markAsRead ".$this->error, LOG_ERR);
1833 return -1;
1834 }
1835 }
1836
1837 return 0;
1838 }
1839
1847 public function setReadDate($user, $notrigger = 0)
1848 {
1849 global $langs;
1850
1851 if (!empty($this->date_read)) {
1852 return 0;
1853 }
1854
1855 $this->oldcopy = dol_clone($this, 2);
1856
1857 $this->db->begin();
1858
1859 $sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
1860 $sql .= " SET date_read = '".$this->db->idate(dol_now())."'";
1861 $sql .= ", fk_user_modif = ".((int) $user->id);
1862 $sql .= " WHERE rowid = ".((int) $this->id);
1863
1864 dol_syslog(get_class($this)."::setReadDate");
1865
1866 $resql = $this->db->query($sql);
1867
1868 if (!$resql) {
1869 $this->db->rollback();
1870 $this->date_read = $this->oldcopy->date_read;
1871 $this->error = $this->db->lasterror();
1872
1873 dol_syslog(get_class($this)."::setReadDate ".$this->error, LOG_ERR);
1874 return -1;
1875 }
1876
1877 if (!$notrigger) {
1878 $result = $this->call_trigger('TICKET_MODIFY', $user);
1879 if ($result < 0) {
1880 $this->db->rollback();
1881 $this->date_read = $this->oldcopy->date_read;
1882 $this->error = implode(',', $this->errors);
1883
1884 dol_syslog(get_class($this)."::setReadDate ".$this->error, LOG_ERR);
1885 return -1;
1886 }
1887 }
1888
1889 $this->db->commit();
1890
1891 $this->date_read = dol_now();
1892 $this->fk_user_modif = $user->id;
1893 $this->user_modification_id = $user->id;
1894
1895 return 1;
1896 }
1897
1906 public function assignUser($user, $id_assign_user, $notrigger = 0)
1907 {
1908 $error = 0;
1909
1910 $this->oldcopy = dol_clone($this, 2);
1911
1912 $this->db->begin();
1913
1914 $sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
1915 if ($id_assign_user > 0) {
1916 $newstatus = Ticket::STATUS_ASSIGNED;
1917 if (getDolGlobalString('TICKET_AUTO_READ_WHEN_ASSIGN')) {
1918 $newstatus = Ticket::STATUS_READ;
1919 }
1920 $sql .= " SET fk_user_assign=".((int) $id_assign_user).", fk_statut = ".((int) $newstatus);
1921 } else {
1922 $sql .= " SET fk_user_assign=null, fk_statut = ".Ticket::STATUS_READ;
1923 }
1924 $sql .= " WHERE rowid = ".((int) $this->id);
1925
1926 dol_syslog(get_class($this)."::assignUser sql=".$sql);
1927 $resql = $this->db->query($sql);
1928 if ($resql) {
1929 $this->fk_user_assign = $id_assign_user; // May be used by trigger
1930
1931 if (!$notrigger) {
1932 // Call trigger
1933 $result = $this->call_trigger('TICKET_ASSIGNED', $user);
1934 if ($result < 0) {
1935 $error++;
1936 }
1937 // End call triggers
1938 }
1939
1940 if (!$error) {
1941 $this->db->commit();
1942 return 1;
1943 } else {
1944 $this->db->rollback();
1945 $this->error = implode(',', $this->errors);
1946 dol_syslog(get_class($this)."::assignUser ".$this->error, LOG_ERR);
1947 return -1;
1948 }
1949 } else {
1950 $this->db->rollback();
1951 $this->error = $this->db->lasterror();
1952 dol_syslog(get_class($this)."::assignUser ".$this->error, LOG_ERR);
1953 return -1;
1954 }
1955 }
1956
1971 public function createTicketMessage($user, $notrigger = 0, $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array(), $send_email = false, $public_area = 0, $summary = '', $external_contacts = [])
1972 {
1973 global $conf, $langs, $hookmanager;
1974 $error = 0;
1975
1976 $now = dol_now();
1977
1978 // Clean parameters
1979 if (isset($this->track_id)) {
1980 $this->track_id = trim($this->track_id);
1981 }
1982
1983 if (isset($this->message)) {
1984 $this->message = trim($this->message);
1985 }
1986
1987 $this->db->begin();
1988
1989 // Insert entry into agenda with code 'TICKET_MSG'
1990 include_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
1991 $actioncomm = new ActionComm($this->db);
1992 $actioncomm->type_code = 'AC_OTH_AUTO'; // This is not an entry that must appears into manual calendar but only into CRM calendar
1993 $actioncomm->code = 'TICKET_MSG';
1994 if ($this->private) {
1995 $actioncomm->code = 'TICKET_MSG_PRIVATE';
1996 }
1997 if ($send_email) {
1998 $actioncomm->code .= '_SENTBYMAIL';
1999 }
2000 if ((empty($user->id) || $user->id == 0) && isset($_SESSION['email_customer'])) {
2001 $actioncomm->email_from = $_SESSION['email_customer'];
2002 }
2003 $actioncomm->socid = $this->socid;
2004 $actioncomm->label = $this->subject;
2005 if ($summary) {
2006 $actioncomm->label = preg_replace('/(\[[^\]]*\]).*$/', '\1', $actioncomm->label);
2007 if ($actioncomm->label) {
2008 $actioncomm->label .= ' ';
2009 }
2010 $actioncomm->label .= (string) $summary;
2011 }
2012
2013 $actioncomm->note_private = $this->message;
2014 $actioncomm->userassigned = array($user->id => array('id' => $user->id,'transparency' => 0));
2015
2016 $parameters = array();
2017 $reshook = $hookmanager->executeHooks('createTicketMessageExternalContacts', $parameters, $actioncomm);
2018 if ($reshook < 0) {
2019 $actioncomm->socpeopleassigned = $external_contacts;
2020 } elseif ($reshook == 0) {
2021 $actioncomm->socpeopleassigned += $external_contacts;
2022 }
2023
2024 $actioncomm->userownerid = $user->id;
2025 $actioncomm->datep = $now;
2026 $actioncomm->percentage = -1; // percentage is not relevant for punctual events
2027 $actioncomm->elementtype = 'ticket';
2028 $actioncomm->fk_element = $this->id;
2029 $actioncomm->elementid = $this->id;
2030 $actioncomm->elementtype = 'ticket';
2031 $actioncomm->fk_project = $this->fk_project;
2032
2033 // Add first contact id found in database from submitter email entered into public interface
2034 // Feature disabled by default: This has a security trouble. The public interface is a no login interface, so being able to show the contact info from an
2035 // email decided by the submiter allows anybody to get information on any contact (customer or supplier) in Dolibarr database.
2036 // He can even check if contact exists by trying any email if this feature is enabled.
2037 if ($public_area && !empty($this->origin_email) && getDolGlobalString('TICKET_ASSIGN_CONTACT_TO_MESSAGE')) {
2038 $contacts = $this->searchContactByEmail($this->origin_email);
2039 if (!empty($contacts)) {
2040 // Ensure that contact is active and select first active contact
2041 foreach ($contacts as $contact) {
2042 if ((int) $contact->status == 1) {
2043 $actioncomm->contact_id = $contact->id;
2044 break;
2045 }
2046 }
2047 }
2048 }
2049
2050 $attachedfiles = array();
2051 $attachedfiles['paths'] = $filename_list;
2052 $attachedfiles['names'] = $mimefilename_list;
2053 $attachedfiles['mimes'] = $mimetype_list;
2054 if (is_array($attachedfiles) && count($attachedfiles) > 0) {
2055 $actioncomm->attachedfiles = $attachedfiles;
2056 }
2057
2058 //if (!empty($mimefilename_list) && is_array($mimefilename_list)) {
2059 // $actioncomm->note_private = dol_concatdesc($actioncomm->note_private, "\n".$langs->transnoentities("AttachedFiles").': '.implode(';', $mimefilename_list));
2060 //}
2061 $actionid = $actioncomm->create($user);
2062 if ($actionid <= 0) {
2063 $error++;
2064 $this->error = $actioncomm->error;
2065 $this->errors = $actioncomm->errors;
2066 }
2067
2068 if ($actionid > 0) {
2069 if (is_array($attachedfiles) && array_key_exists('paths', $attachedfiles) && count($attachedfiles['paths']) > 0) {
2070 // If there is some files, we must now link them to the event, so we can show them per event.
2071 foreach ($attachedfiles['paths'] as $key => $filespath) {
2072 // Disabled the move into another directory, Files for a ticket should be stored into ticket directory. It generates too much troubles.
2073 $destdir = $conf->ticket->dir_output.'/'.$this->ref;
2074 //$destfile = $destdir.'/'.$attachedfiles['names'][$key];
2075 //if (dol_mkdir($destdir) >= 0) {
2076 //require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2077 //dol_move($filespath, $destfile); // Disabled, a file for a ticket should be stored into ticket directory. It generates big trouble.
2078 if (in_array($actioncomm->code, array('TICKET_MSG', 'TICKET_MSG_SENTBYMAIL', 'TICKET_MSG_PRIVATE'))) {
2079 $ecmfile = new EcmFiles($this->db);
2080 $destdir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $destdir);
2081 $destdir = preg_replace('/[\\/]$/', '', $destdir);
2082 $destdir = preg_replace('/^[\\/]/', '', $destdir);
2083
2084 $result = $ecmfile->fetch(0, '', $destdir.'/'.$attachedfiles['names'][$key]);
2085
2086 // We also store the ID of event.
2087 $ecmfile->agenda_id = $actionid;
2088
2089 if ($result > 0) {
2090 $result = $ecmfile->update($user);
2091 if ($result < 0) {
2092 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
2093 }
2094 }
2095 }
2096 //}
2097 }
2098 }
2099 }
2100
2101 // Commit or rollback
2102 if ($error) {
2103 $this->db->rollback();
2104 return -1 * $error;
2105 } else {
2106 $this->db->commit();
2107 return $actionid;
2108 }
2109 }
2110
2116 public function loadCacheMsgsTicket()
2117 {
2118 if (!empty($this->cache_msgs_ticket) && is_array($this->cache_msgs_ticket) && count($this->cache_msgs_ticket)) {
2119 return 0;
2120 }
2121
2122 // Cache already loaded
2123
2124 $sql = "SELECT id as rowid, fk_user_author, fk_user_action, email_from, datec, datep, label, note as message, code";
2125 $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm";
2126 $sql .= " WHERE fk_element = ".(int) $this->id;
2127 $sql .= " AND elementtype = 'ticket'";
2128 $sql .= " ORDER BY datep DESC";
2129
2130 dol_syslog(get_class($this)."::load_cache_actions_ticket", LOG_DEBUG);
2131 $resql = $this->db->query($sql);
2132 if ($resql) {
2133 $num = $this->db->num_rows($resql);
2134 $i = 0;
2135 while ($i < $num) {
2136 $obj = $this->db->fetch_object($resql);
2137 $this->cache_msgs_ticket[$i]['id'] = $obj->rowid;
2138 $this->cache_msgs_ticket[$i]['fk_user_author'] = $obj->fk_user_author;
2139 $this->cache_msgs_ticket[$i]['fk_user_action'] = $obj->fk_user_action; // owner of the action
2140 if (in_array($obj->code, array('TICKET_MSG', 'AC_TICKET_CREATE')) && empty($obj->fk_user_author)) {
2141 $this->cache_msgs_ticket[$i]['fk_contact_author'] = $obj->email_from;
2142 }
2143 $this->cache_msgs_ticket[$i]['datec'] = $this->db->jdate($obj->datec);
2144 $this->cache_msgs_ticket[$i]['datep'] = $this->db->jdate($obj->datep);
2145 $this->cache_msgs_ticket[$i]['subject'] = $obj->label;
2146 $this->cache_msgs_ticket[$i]['message'] = $obj->message;
2147 $this->cache_msgs_ticket[$i]['private'] = (preg_match('/^TICKET_MSG_PRIVATE/', $obj->code) ? 1 : 0);
2148 $i++;
2149 }
2150 return $num;
2151 } else {
2152 $this->error = "Error ".$this->db->lasterror();
2153 dol_syslog(get_class($this)."::load_cache_actions_ticket ".$this->error, LOG_ERR);
2154 return -1;
2155 }
2156 }
2157
2165 public function close(User $user, $mode = 0)
2166 {
2167
2168 if ($this->status != Ticket::STATUS_CLOSED && $this->status != Ticket::STATUS_CANCELED) { // not closed
2169 $this->db->begin();
2170
2171 $this->oldcopy = dol_clone($this);
2172 $this->status = ($mode ? Ticket::STATUS_CANCELED : Ticket::STATUS_CLOSED);
2173
2174 $sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
2175 $sql .= " SET fk_statut = ".((int) $this->status).", progress=100, date_close='".$this->db->idate(dol_now())."'";
2176 $sql .= " WHERE rowid = ".((int) $this->id);
2177
2178 dol_syslog(get_class($this)."::close mode=".$mode);
2179 $resql = $this->db->query($sql);
2180 if ($resql) {
2181 $error = 0;
2182
2183 // Valid and close fichinter linked
2184 if (isModEnabled('intervention') && getDolGlobalString('WORKFLOW_TICKET_CLOSE_INTERVENTION')) {
2185 dol_syslog("We have closed the ticket, so we close all linked interventions");
2186 $this->fetchObjectLinked($this->id, $this->element, null, 'fichinter');
2187 if ($this->linkedObjectsIds) {
2188 foreach ($this->linkedObjectsIds['fichinter'] as $fichinter_id) {
2189 $fichinter = new Fichinter($this->db);
2190 $fichinter->fetch($fichinter_id);
2191 if ($fichinter->statut == 0) {
2192 $result = $fichinter->setValid($user);
2193 if (!$result) {
2194 $this->errors[] = $fichinter->error;
2195 $error++;
2196 }
2197 }
2198 if ($fichinter->statut < 3) {
2199 $result = $fichinter->setStatut(3);
2200 if (!$result) {
2201 $this->errors[] = $fichinter->error;
2202 $error++;
2203 }
2204 }
2205 }
2206 }
2207 }
2208
2209 // Call trigger
2210 $result = $this->call_trigger('TICKET_CLOSE', $user);
2211 if ($result < 0) {
2212 $error++;
2213 }
2214 // End call triggers
2215
2216 if (!$error) {
2217 $this->db->commit();
2218 return 1;
2219 } else {
2220 $this->db->rollback();
2221 $this->error = implode(',', $this->errors);
2222 dol_syslog(get_class($this)."::close ".$this->error, LOG_ERR);
2223 return -1;
2224 }
2225 } else {
2226 $this->db->rollback();
2227 $this->error = $this->db->lasterror();
2228 dol_syslog(get_class($this)."::close ".$this->error, LOG_ERR);
2229 return -1;
2230 }
2231 }
2232
2233 return 0;
2234 }
2235
2245 public function searchSocidByEmail($email, $type = 0, $filters = array(), $clause = 'AND')
2246 {
2247 $thirdparties = array();
2248 $exact = 0;
2249
2250 // Generation requete recherche
2251 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe";
2252 $sql .= " WHERE entity IN (".getEntity('ticket', 1).")";
2253 if (!empty($type)) {
2254 if ($type == 1 || $type == 2) {
2255 $sql .= " AND client = ".((int) $type);
2256 } elseif ($type == 3) {
2257 $sql .= " AND fournisseur = 1";
2258 }
2259 }
2260 if (!empty($email)) {
2261 if (empty($exact)) {
2262 $regs = array();
2263 if (preg_match('/^([\*])?[^*]+([\*])?$/', $email, $regs) && count($regs) > 1) {
2264 $email = str_replace('*', '%', $email);
2265 } else {
2266 $email = '%'.$email.'%';
2267 }
2268 }
2269 $sql .= " AND ";
2270 if (is_array($filters) && !empty($filters)) {
2271 $sql .= "(";
2272 }
2273
2274 $sql .= "email LIKE '".$this->db->escape($email)."'";
2275 }
2276 if (is_array($filters) && !empty($filters)) {
2277 foreach ($filters as $field => $value) {
2278 $sql .= " ".$clause." ".$this->db->sanitize($field)." LIKE '".$this->db->escape($value)."'";
2279 }
2280 if (!empty($email)) {
2281 $sql .= ")";
2282 }
2283 }
2284
2285 $res = $this->db->query($sql);
2286 if ($res) {
2287 while ($rec = $this->db->fetch_array($res)) {
2288 $soc = new Societe($this->db);
2289 $soc->fetch($rec['rowid']);
2290 $thirdparties[] = $soc;
2291 }
2292
2293 return $thirdparties;
2294 } else {
2295 $this->error = $this->db->error().' sql='.$sql;
2296 dol_syslog(get_class($this)."::searchSocidByEmail ".$this->error, LOG_ERR);
2297 return -1;
2298 }
2299 }
2300
2309 public function searchContactByEmail($email, $socid = 0, $case = '')
2310 {
2311 $contacts = array();
2312
2313 // Forge the search SQL
2314 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople";
2315 $sql .= " WHERE entity IN (".getEntity('contact').")";
2316 if (!empty($socid)) {
2317 $sql .= " AND fk_soc = ".((int) $socid);
2318 }
2319 if (!empty($email)) {
2320 $sql .= " AND ";
2321 if (!$case) {
2322 $sql .= "email = '".$this->db->escape($email)."'";
2323 } else {
2324 $sql .= "email LIKE BINARY '".$this->db->escape($this->db->escapeforlike($email))."'";
2325 }
2326 }
2327
2328 $res = $this->db->query($sql);
2329 if ($res) {
2330 while ($rec = $this->db->fetch_object($res)) {
2331 include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
2332 $contactstatic = new Contact($this->db);
2333 $contactstatic->fetch($rec->rowid);
2334 $contacts[] = $contactstatic;
2335 }
2336
2337 return $contacts;
2338 } else {
2339 $this->error = $this->db->error().' sql='.$sql;
2340 dol_syslog(get_class($this)."::searchContactByEmail ".$this->error, LOG_ERR);
2341 return -1;
2342 }
2343 }
2344
2351 public function setCustomer($id)
2352 {
2353 if ($this->id) {
2354 $this->db->begin();
2355
2356 $sql = "UPDATE ".$this->db->prefix()."ticket";
2357 $sql .= " SET fk_soc = ".($id > 0 ? (int) $id : "null");
2358 $sql .= " WHERE rowid = ".((int) $this->id);
2359 dol_syslog(get_class($this).'::setCustomer sql='.$sql);
2360 $resql = $this->db->query($sql);
2361 if (!$resql) {
2362 $this->error = $this->db->lasterror();
2363 dol_syslog(get_class($this).'::setCustomer '.$this->error, LOG_ERR);
2364 $this->db->rollback();
2365
2366 return -1;
2367 }
2368
2369 // The Agenda tab of a third party filters on actioncomm.fk_soc alone, so the events already recorded on
2370 // the ticket must follow it, as Societe::mergeCompany() already does when two third parties are merged.
2371 $sql = "UPDATE ".$this->db->prefix()."actioncomm";
2372 $sql .= " SET fk_soc = ".($id > 0 ? (int) $id : "null");
2373 $sql .= " WHERE elementtype = 'ticket' AND fk_element = ".((int) $this->id);
2374 dol_syslog(get_class($this).'::setCustomer sql='.$sql);
2375 $resql = $this->db->query($sql);
2376 if (!$resql) {
2377 $this->error = $this->db->lasterror();
2378 dol_syslog(get_class($this).'::setCustomer '.$this->error, LOG_ERR);
2379 $this->db->rollback();
2380
2381 return -1;
2382 }
2383
2384 $this->db->commit();
2385
2386 return 1;
2387 } else {
2388 return -1;
2389 }
2390 }
2391
2398 public function setProgression($percent)
2399 {
2400 if ($this->id) {
2401 $sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
2402 $sql .= " SET progress = ".($percent > 0 ? (float) $percent : "null");
2403 $sql .= " WHERE rowid = ".((int) $this->id);
2404 dol_syslog(get_class($this).'::set_progression sql='.$sql);
2405 $resql = $this->db->query($sql);
2406 if ($resql) {
2407 return 1;
2408 } else {
2409 return -1;
2410 }
2411 } else {
2412 return -1;
2413 }
2414 }
2415
2422 public function setContract($contractid)
2423 {
2424 if ($this->id) {
2425 $sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
2426 $sql .= " SET fk_contract = ".($contractid > 0 ? (int) $contractid : "null");
2427 $sql .= " WHERE rowid = ".((int) $this->id);
2428 dol_syslog(get_class($this).'::setContract sql='.$sql);
2429 $resql = $this->db->query($sql);
2430 if ($resql) {
2431 return 1;
2432 } else {
2433 return -1;
2434 }
2435 } else {
2436 return -1;
2437 }
2438 }
2439
2440 /* gestion des contacts d'un ticket */
2441
2448 {
2449 return $this->getIdContact('internal', 'SUPPORTTEC');
2450 }
2451
2458 public function getInfosTicketInternalContact($status = -1)
2459 {
2460 return $this->listeContact(-1, 'internal', 0, '', $status);
2461 }
2462
2469 {
2470 return $this->getIdContact('external', 'SUPPORTCLI');
2471 }
2472
2479 public function getInfosTicketExternalContact($status = -1)
2480 {
2481 return $this->listeContact(-1, 'external', 0, '', $status);
2482 }
2483
2490 {
2491 return $this->getIdContact('internal', 'CONTRIBUTOR');
2492 }
2493
2500 {
2501 return $this->getIdContact('external', 'CONTRIBUTOR');
2502 }
2503
2509 public function getTicketAllContacts()
2510 {
2511 $array_contact = $this->getIdTicketInternalContact();
2512
2513 $array_contact = array_merge($array_contact, $this->getIdTicketCustomerContact());
2514
2515 $array_contact = array_merge($array_contact, $this->getIdTicketInternalInvolvedContact());
2516
2517 $array_contact = array_merge($array_contact, $this->getIdTicketCustomerInvolvedContact());
2518
2519 return $array_contact;
2520 }
2521
2528 {
2529 $array_contact = array();
2530
2531 $array_contact = array_merge($array_contact, $this->getIdTicketCustomerContact());
2532
2533 $array_contact = array_merge($array_contact, $this->getIdTicketCustomerInvolvedContact());
2534
2535 return $array_contact;
2536 }
2537
2538
2550 public function listeContact($statusoflink = -1, $source = 'external', $list = 0, $code = '', $status = -1)
2551 {
2552 global $langs;
2553
2554 $tab = array();
2555
2556 $sql = "SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user
2557 if ($source == 'internal') {
2558 $sql .= ", '-1' as socid, t.statut as statuscontact";
2559 }
2560
2561 if ($source == 'external' || $source == 'thirdparty') {
2562 $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
2563 }
2564
2565 $sql .= ", t.civility, t.lastname as lastname, t.firstname, t.email";
2566 if ($source == 'internal') {
2567 $sql .= ", t.office_phone as phone, t.user_mobile as phone_mobile";
2568 }
2569
2570 if ($source == 'external' || $source == 'thirdparty') {
2571 $sql .= ", t.phone as phone, t.phone_mobile as phone_mobile, t.phone_perso as phone_perso";
2572 }
2573
2574 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_contact_label";
2575 $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
2576 $sql .= ", ".MAIN_DB_PREFIX."element_contact ec";
2577 if ($source == 'internal') {
2578 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
2579 }
2580
2581 if ($source == 'external' || $source == 'thirdparty') {
2582 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
2583 }
2584
2585 $sql .= " WHERE ec.element_id = ".((int) $this->id);
2586 $sql .= " AND ec.fk_c_type_contact=tc.rowid";
2587 $sql .= " AND tc.element='".$this->db->escape($this->element)."'";
2588 if ($source == 'internal') {
2589 $sql .= " AND tc.source = 'internal'";
2590 if ($status >= 0) {
2591 $sql .= " AND t.statut = ".((int) $status);
2592 }
2593 }
2594
2595 if ($source == 'external' || $source == 'thirdparty') {
2596 $sql .= " AND tc.source = 'external'";
2597 if ($status >= 0) {
2598 $sql .= " AND t.statut = ".((int) $status);
2599 }
2600 }
2601
2602 if (!empty($code)) {
2603 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
2604 }
2605
2606 $sql .= " AND tc.active=1";
2607 if ($statusoflink >= 0) {
2608 $sql .= " AND ec.statut = ".((int) $statusoflink);
2609 }
2610
2611 $sql .= " ORDER BY t.lastname ASC";
2612
2613 $resql = $this->db->query($sql);
2614 if ($resql) {
2615 $num = $this->db->num_rows($resql);
2616 $i = 0;
2617 while ($i < $num) {
2618 $obj = $this->db->fetch_object($resql);
2619
2620 if (!$list) {
2621 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
2622 $labelType = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_contact_label);
2623 $tab[$i] = array(
2624 'source' => $obj->source,
2625 'socid' => (int) $obj->socid,
2626 'id' => (int) $obj->id,
2627 'nom' => $obj->lastname, // For backward compatibility
2628 'civility' => $obj->civility,
2629 'lastname' => $obj->lastname,
2630 'firstname' => $obj->firstname,
2631 'email' => $obj->email,
2632 'rowid' => (int) $obj->rowid,
2633 'code' => $obj->code,
2634 'libelle' => $labelType, // deprecated, replaced with labeltype
2635 'labeltype' => $labelType,
2636 'status' => $obj->statuslink,
2637 'statuscontact' => (int) $obj->statuscontact,
2638 'fk_c_type_contact' => (int) $obj->fk_c_type_contact,
2639 'phone' => $obj->phone,
2640 'phone_mobile' => $obj->phone_mobile);
2641 if ($source == 'external') {
2642 $tab[$i]['phone_perso'] = $obj->phone_perso;
2643 }
2644 } else {
2645 $tab[$i] = $obj->id;
2646 }
2647
2648 $i++;
2649 }
2650
2651 return $tab;
2652 } else {
2653 $this->error = $this->db->error();
2654 dol_print_error($this->db);
2655 return -1;
2656 }
2657 }
2658
2665 public function getDefaultRef($thirdparty = null)
2666 {
2667 global $conf;
2668
2669 $defaultref = '';
2670 $modele = getDolGlobalString('TICKET_ADDON', 'mod_ticket_simple');
2671
2672 // Search template files
2673 $file = '';
2674 $classname = '';
2675 $reldir = '';
2676 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
2677 foreach ($dirmodels as $reldir) {
2678 $file = dol_buildpath($reldir."core/modules/ticket/".$modele.'.php', 0);
2679 if (file_exists($file)) {
2680 $classname = $modele;
2681 break;
2682 }
2683 }
2684
2685 if ($classname !== '') {
2686 $result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php');
2687 $modTicket = new $classname();
2688 '@phan-var-force ModeleNumRefTicket $modTicket';
2689
2690 $defaultref = $modTicket->getNextValue($thirdparty, $this);
2691 }
2692
2693 if (is_numeric($defaultref) && $defaultref <= 0) {
2694 $defaultref = '';
2695 }
2696
2697 return $defaultref;
2698 }
2699
2700
2701 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2708 public function is_photo_available($sdir)
2709 {
2710 // phpcs:enable
2711 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2712
2713 $dir = $sdir.'/';
2714
2715 $dir_osencoded = dol_osencode($dir);
2716 if (file_exists($dir_osencoded)) {
2717 $handle = opendir($dir_osencoded);
2718 if (is_resource($handle)) {
2719 while (($file = readdir($handle)) !== false) {
2720 if (!utf8_check($file)) {
2721 $file = mb_convert_encoding($file, 'UTF-8', 'ISO-8859-1'); // To be sure data is stored in UTF8 in memory
2722 }
2723 if (dol_is_file($dir.$file)) {
2724 return true;
2725 }
2726 }
2727 }
2728 }
2729 return false;
2730 }
2731
2732
2741 public function copyFilesForTicket($forcetrackid = null)
2742 {
2743 global $conf;
2744
2745 // Create form object
2746 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
2747 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2748 include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
2749
2750 $maxwidthsmall = 270;
2751 $maxheightsmall = 150;
2752 $maxwidthmini = 128;
2753 $maxheightmini = 72;
2754
2755 $formmail = new FormMail($this->db);
2756 $formmail->trackid = (is_null($forcetrackid) ? 'tic'.$this->id : '');
2757 $attachedfiles = $formmail->get_attached_files();
2758
2759 $filepath = $attachedfiles['paths']; // path is for example user->dir_temp.'/'.$user->id.'/'...
2760 $filename = $attachedfiles['names'];
2761 $mimetype = $attachedfiles['mimes'];
2762
2763 // Copy files into ticket directory
2764 $destdir = $conf->ticket->dir_output.'/'.$this->ref;
2765
2766 if (!dol_is_dir($destdir)) {
2767 dol_mkdir($destdir);
2768 }
2769
2770 $listofpaths = array();
2771 $listofnames = array();
2772 foreach ($filename as $i => $val) {
2773 $destfile = $destdir.'/'.$filename[$i];
2774 // If destination file already exists, we add a suffix to avoid to overwrite
2775 if (is_file($destfile)) {
2776 $pathinfo = pathinfo($filename[$i]);
2777 $now = dol_now();
2778 $destfile = $destdir.'/'.$pathinfo['filename'].' - '.dol_print_date($now, 'dayhourlog').'.'.$pathinfo['extension'];
2779 }
2780
2781 $moreinfo = array(
2782 'description' => 'File saved by copyFilesForTicket',
2783 'src_object_type' => $this->element,
2784 'src_object_id' => $this->id,
2785 'gen_or_uploaded' => 'uploaded'
2786 );
2787
2788 $res = dol_move($filepath[$i], $destfile, '0', 1, 0, 1, $moreinfo);
2789
2790 if (!$res) {
2791 // Move has failed
2792 $this->error = "Failed to move file ".dirbasename($filepath[$i])." into ".dirbasename($destfile);
2793 return -1;
2794 } else {
2795 // If file is an image, we create thumbs
2796 if (image_format_supported($destfile) == 1) {
2797 // Create small thumbs for image (Ratio is near 16/9)
2798 // Used on logon for example
2799 $imgThumbSmall = vignette($destfile, $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs");
2800 // Create mini thumbs for image (Ratio is near 16/9)
2801 // Used on menu or for setup page for example
2802 $imgThumbMini = vignette($destfile, $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs");
2803 }
2804 }
2805
2806 // Clear variables into session
2807 $formmail->remove_attached_files($i);
2808
2809 // Fill array with new names
2810 $listofpaths[$i] = $destfile;
2811 $listofnames[$i] = basename($destfile);
2812 }
2813
2814 return array('listofpaths' => $listofpaths, 'listofnames' => $listofnames, 'listofmimes' => $mimetype);
2815 }
2816
2827 public function setCategories($categories)
2828 {
2829 // Handle single category
2830 if (!is_array($categories)) {
2831 $categories = array($categories);
2832 }
2833
2834 // Get current categories
2835 include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2836 $c = new Categorie($this->db);
2837 $existing = $c->containing($this->id, Categorie::TYPE_TICKET, 'id');
2838
2839 // Diff
2840 if (is_array($existing)) {
2841 $to_del = array_diff($existing, $categories);
2842 $to_add = array_diff($categories, $existing);
2843 } else {
2844 $to_del = array(); // Nothing to delete
2845 $to_add = $categories;
2846 }
2847
2848 // Process
2849 foreach ($to_del as $del) {
2850 if ($c->fetch($del) > 0) {
2851 $c->del_type($this, Categorie::TYPE_TICKET);
2852 }
2853 }
2854 foreach ($to_add as $add) {
2855 if ($c->fetch($add) > 0) {
2856 $c->add_type($this, Categorie::TYPE_TICKET);
2857 }
2858 }
2859
2860 return 1;
2861 }
2862
2875 public function newMessage($user, &$action, $private = 1, $public_area = 0)
2876 {
2877 global $mysoc, $langs, $hookmanager;
2878
2879 $error = 0;
2880
2881 $object = new Ticket($this->db);
2882
2883 $ret = $object->fetch(0, '', GETPOST('track_id', 'alpha'));
2884
2885 $object->socid = $object->fk_soc;
2886 $object->fetch_thirdparty();
2887 $object->fetchProject();
2888
2889 if ($ret < 0) {
2890 $error++;
2891 array_push($this->errors, $langs->trans("ErrorTicketIsNotValid"));
2892 $action = '';
2893 }
2894
2895 if (!GETPOST("message")) {
2896 $error++;
2897 array_push($this->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("Message")));
2898 $action = 'add_message';
2899 }
2900
2901 if (!$error) {
2902 $summary = mb_strcut(GETPOST('summary', 'alphanohtml'), 0, 42, 'UTF-8');
2903 $object->subject = GETPOST('subject', 'alphanohtml');
2904 $object->message = GETPOST("message", "restricthtml");
2905 $object->private = GETPOST("private_message", "alpha");
2906
2907 $send_email = (bool) GETPOSTINT('send_email');
2908
2909 // Copy attached files (saved into $_SESSION) as linked files to ticket. Return array with final name used.
2910 $resarray = $object->copyFilesForTicket();
2911 if (is_numeric($resarray) && $resarray == -1) {
2912 $this->setErrorsFromObject($object);
2913 return -1;
2914 }
2915
2916 $listofpaths = $resarray['listofpaths'];
2917 $listofnames = $resarray['listofnames'];
2918 $listofmimes = $resarray['listofmimes'];
2919
2920 // Retrieve email of all contacts (external)
2921 $external_contacts = $object->getInfosTicketExternalContact(1);
2922 $external_resources = [];
2923 if (!empty($external_contacts)) {
2924 foreach ($external_contacts as $eContact) {
2925 $external_resources[$eContact['id']] = $eContact;
2926 }
2927 }
2928
2929 // Add the ticket message in database (even if email is requested, we store a simple record
2930 // like a simple private message, with no information about emails) because
2931 // information about emails sent will be fill later after email sending.
2932 $id = $object->createTicketMessage($user, 0, $listofpaths, $listofmimes, $listofnames, $send_email, $public_area, $summary, $external_resources);
2933
2934 if ($id <= 0) {
2935 $error++;
2936 $this->error = $object->error;
2937 $this->errors = $object->errors;
2938 $action = 'add_message';
2939 }
2940
2941 if (!$error && $id > 0) {
2942 setEventMessages($langs->trans('TicketMessageSuccessfullyAdded'), null, 'mesgs');
2943
2944 // Now send emails
2945 if (!empty($public_area)) {
2946 /*
2947 * Message created from the Public interface
2948 *
2949 * Send emails to assigned users (public area notification)
2950 */
2951 if (getDolGlobalString('TICKET_PUBLIC_NOTIFICATION_NEW_MESSAGE_ENABLED')) {
2952 // Retrieve internal contact datas
2953 $internal_contacts = $object->getInfosTicketInternalContact(1);
2954
2955 $assigned_user_dont_have_email = '';
2956
2957 $sendto = array();
2958
2959 if ($this->fk_user_assign > 0) {
2960 $assigned_user = new User($this->db);
2961 $assigned_user->fetch($this->fk_user_assign);
2962 if (!empty($assigned_user->email)) {
2963 $sendto[$assigned_user->email] = $assigned_user->getFullName($langs)." <".$assigned_user->email.">";
2964 } else {
2965 $assigned_user_dont_have_email = $assigned_user->getFullName($langs);
2966 }
2967 } else {
2968 $assigned_user = null;
2969 }
2970
2971 // Build array to display recipient list
2972 foreach ($internal_contacts as $key => $info_sendto) {
2973 // Avoid duplicate notifications
2974 if ($info_sendto['id'] == $user->id) {
2975 continue;
2976 }
2977
2978 // We check if the email address is not the assignee's address to prevent notification from being sent twice
2979 if (!empty($info_sendto['email']) && ($assigned_user === null || $assigned_user->email != $info_sendto['email'])) {
2980 $sendto[] = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'])." <".$info_sendto['email'].">";
2981 }
2982 }
2983
2984 if (empty($sendto)) {
2985 if (getDolGlobalString('TICKET_PUBLIC_NOTIFICATION_NEW_MESSAGE_DEFAULT_EMAIL')) {
2986 $sendto[getDolGlobalString('TICKET_PUBLIC_NOTIFICATION_NEW_MESSAGE_DEFAULT_EMAIL')] = getDolGlobalString('TICKET_PUBLIC_NOTIFICATION_NEW_MESSAGE_DEFAULT_EMAIL');
2987 } elseif (getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO')) {
2988 $sendto[getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO')] = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO');
2989 }
2990 }
2991
2992 // Add global email address recipient
2993 if (getDolGlobalString('TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS') && !array_key_exists(getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO'), $sendto)) {
2994 if (getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO')) {
2995 $sendto[getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO')] = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO');
2996 }
2997 }
2998
2999 $parameters = array('sendto' => $sendto);
3000 $reshook = $hookmanager->executeHooks('updateSendtoTicketMessage', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
3001 if (empty($reshook)) {
3002 $sendto = array_merge($sendto, $hookmanager->resArray);
3003 } elseif ($reshook > 0) {
3004 $sendto = $hookmanager->resArray;
3005 }
3006
3007 if (!empty($sendto)) {
3008 $appli = getDolGlobalString('MAIN_APPLICATION_TITLE', $mysoc->name);
3009
3010 $subject = '['.$appli.'- ticket #'.$object->track_id.'] '.$this->subject;
3011
3012 // Message send
3013 $message = getDolGlobalString('TICKET_MESSAGE_MAIL_INTRO', $langs->trans('TicketMessageMailIntroText'));
3014 $message .= '<br><br>';
3015 $messagePost = GETPOST('message', 'restricthtml');
3016 if (!dol_textishtml($messagePost)) {
3017 $messagePost = dol_nl2br($messagePost);
3018 }
3019 $message .= $messagePost;
3020
3021 // Customer company infos
3022 $message .= '<br><br>';
3023 $message .= "==============================================";
3024 $message .= !empty($object->thirdparty->name) ? '<br>'.$langs->trans('ThirdParty')." : ".$object->thirdparty->name : '';
3025 $message .= !empty($object->thirdparty->town) ? '<br>'.$langs->trans('Town')." : ".$object->thirdparty->town : '';
3026 $message .= !empty($object->thirdparty->phone) ? '<br>'.$langs->trans('Phone')." : ".$object->thirdparty->phone : '';
3027
3028 // Email send to
3029 $message .= '<br><br>';
3030 if (!empty($assigned_user_dont_have_email)) {
3031 $message .= '<br>'.$langs->trans('NoEMail').' : '.$assigned_user_dont_have_email;
3032 }
3033 foreach ($sendto as $val) {
3034 $message .= '<br>'.$langs->trans('TicketNotificationRecipient').' : '.$val;
3035 }
3036
3037 // URL ticket
3038 $url_internal_ticket = dol_buildpath('/ticket/card.php', 2).'?track_id='.$object->track_id;
3039 $message .= '<br><br>';
3040 $message .= $langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal').' : <a href="'.$url_internal_ticket.'">'.$object->track_id.'</a>';
3041
3042 $email_from = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_FROM');
3043
3044 $replyto = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_REPLYTO');
3045
3046 // don't try to send email if no recipient
3047 $this->sendTicketMessageByEmail($subject, $message, 0, $sendto, $listofpaths, $listofmimes, $listofnames, array(), $email_from, $replyto);
3048 }
3049 }
3050 } else {
3051 /*
3052 * Message created from the Backoffice / Private area
3053 *
3054 * Send emails to internal users (linked contacts) then, if private is not set, to external users (linked contacts or thirdparty email if no contact set)
3055 */
3056 if ((int) $send_email > 0) {
3057 // Retrieve internal contact datas
3058 $internal_contacts = $object->getInfosTicketInternalContact(1);
3059
3060 $sendto = array();
3061 if (is_array($internal_contacts) && count($internal_contacts) > 0) {
3062 // Set default subject
3063 $appli = getDolGlobalString('MAIN_APPLICATION_TITLE', $mysoc->name);
3064
3065 $subject = GETPOST('subject', 'alphanohtml') ? GETPOST('subject', 'alphanohtml') : '['.$appli.' - '.$langs->trans("Ticket").' #'.$object->track_id.'] '.$langs->trans('TicketNewMessage');
3066
3067 $message_intro = $langs->trans('TicketNotificationEmailBody', "#".$object->id);
3068 $message_signature = GETPOST('mail_signature') ? GETPOST('mail_signature') : getDolGlobalString('TICKET_MESSAGE_MAIL_SIGNATURE');
3069
3070 $message = getDolGlobalString('TICKET_MESSAGE_MAIL_INTRO', $langs->trans('TicketMessageMailIntroText'));
3071 $message .= '<br><br>';
3072 $messagePost = GETPOST('message', 'restricthtml');
3073 if (!dol_textishtml($messagePost)) {
3074 $messagePost = dol_nl2br($messagePost);
3075 }
3076 $message .= $messagePost;
3077
3078 // Data about customer
3079 $message .= '<br><br>';
3080 $message .= "==============================================<br>";
3081 $message .= !empty($object->thirdparty->name) ? $langs->trans('ThirdParty')." : ".$object->thirdparty->name : '';
3082 $message .= !empty($object->thirdparty->town) ? '<br>'.$langs->trans('Town')." : ".$object->thirdparty->town : '';
3083 $message .= !empty($object->thirdparty->phone) ? '<br>'.$langs->trans('Phone')." : ".$object->thirdparty->phone : '';
3084
3085 // Build array to display recipient list
3086 foreach ($internal_contacts as $key => $info_sendto) {
3087 // Check if recipient email is current user, if yes, we avoid to send email to him.
3088 if ($info_sendto['id'] == $user->id) {
3089 dol_syslog("We cancel sending email to internal user ".$info_sendto['email']." because it is current user", LOG_DEBUG);
3090 continue;
3091 }
3092
3093 if ($info_sendto['email'] != '') {
3094 $email = $info_sendto['email'];
3095 if ($email != null) {
3096 $sendto[$email] = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'])." <".$info_sendto['email'].">";
3097 }
3098
3099 // Contact type
3100 $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], -1).' ('.strtolower((string) $info_sendto['libelle']).')';
3101 $message .= (!empty($recipient) ? '<br>'.$langs->trans('TicketNotificationRecipient').' : '.$recipient.'<br>' : '');
3102 }
3103 }
3104 $message .= '<br>';
3105 // URL ticket
3106 $url_internal_ticket = dol_buildpath('/ticket/card.php', 2).'?track_id='.$object->track_id;
3107
3108 // Add html link on url
3109 $message .= '<br>'.$langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal').' : <a href="'.$url_internal_ticket.'">'.$object->track_id.'</a><br>';
3110
3111 // Add global email address recipient
3112 if (getDolGlobalString('TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS') && !array_key_exists(getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO'), $sendto)) {
3113 if (getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO')) {
3114 $sendto[getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO')] = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO');
3115 }
3116 }
3117
3118 $parameters = array('sendto' => $sendto);
3119 $reshook = $hookmanager->executeHooks('updateSendtoTicketMessage', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
3120 if (empty($reshook)) {
3121 $sendto = array_merge($sendto, $hookmanager->resArray);
3122 } elseif ($reshook > 0) {
3123 $sendto = $hookmanager->resArray;
3124 }
3125
3126 $sendtocc = array();
3127 if (getDolGlobalString("TICKET_SEND_INTERNAL_CC")) {
3128 $sendtocc = explode(',', getDolGlobalString("TICKET_SEND_INTERNAL_CC"));
3129 }
3130
3131 $email_from = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_FROM');
3132
3133 $replyto = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_REPLYTO');
3134
3135 // don't try to send email if no recipient
3136 if (!empty($sendto)) {
3137 $this->sendTicketMessageByEmail($subject, $message, 0, $sendto, $listofpaths, $listofmimes, $listofnames, $sendtocc, $email_from, $replyto);
3138 }
3139 }
3140
3141 /*
3142 * Send emails for externals users if not private (linked contacts)
3143 */
3144 if (empty($object->private)) {
3145 // If no contact, get email from thirdparty
3146 if (is_array($external_contacts) && count($external_contacts) === 0) {
3147 if (!empty($object->fk_soc)) {
3148 $object->fetch_thirdparty($object->fk_soc);
3149 $array_company = array(array('id' => -1, 'firstname' => '', 'lastname' => $object->thirdparty->name, 'email' => $object->thirdparty->email, 'libelle' => $langs->transnoentities('Customer'), 'socid' => $object->thirdparty->id));
3150 $external_contacts = array_merge($external_contacts, $array_company);
3151 } elseif (empty($object->fk_soc) && !empty($object->origin_replyto)) {
3152 $array_external = array(array('id' => -1, 'firstname' => '', 'lastname' => $object->origin_replyto, 'email' => $object->origin_replyto, 'libelle' => $langs->transnoentities('Customer'), 'socid' => 0));
3153 $external_contacts = array_merge($external_contacts, $array_external);
3154 } elseif (empty($object->fk_soc) && !empty($object->origin_email)) {
3155 $array_external = array(array('id' => -1, 'firstname' => '', 'lastname' => $object->origin_email, 'email' => $object->origin_email, 'libelle' => $langs->transnoentities('Customer'), 'socid' => 0)); // no fk_soc here, so $object->thirdparty was never fetched (mirrors the origin_replyto branch above)
3156 $external_contacts = array_merge($external_contacts, $array_external);
3157 }
3158 }
3159
3160 $sendto = array();
3161 if (is_array($external_contacts) && count($external_contacts) > 0) {
3162 // Get default subject for email to external contacts
3163 $appli = getDolGlobalString('MAIN_APPLICATION_TITLE', $mysoc->name);
3164
3165 $subject = GETPOST('subject') ? GETPOST('subject') : '['.$appli.' - '.$langs->trans("Ticket").' #'.$object->track_id.'] '.$langs->trans('TicketNewMessage');
3166
3167 $message_intro = GETPOST('mail_intro') ? GETPOST('mail_intro', 'restricthtml') : getDolGlobalString('TICKET_MESSAGE_MAIL_INTRO');
3168 $message_signature = GETPOST('mail_signature') ? GETPOST('mail_signature', 'restricthtml') : getDolGlobalString('TICKET_MESSAGE_MAIL_SIGNATURE');
3169 if (!dol_textishtml($message_intro)) {
3170 $message_intro = dol_nl2br($message_intro);
3171 }
3172 if (!dol_textishtml($message_signature)) {
3173 $message_signature = dol_nl2br($message_signature);
3174 }
3175
3176 // We put intro after
3177 $messagePost = GETPOST('message', 'restricthtml');
3178 if (!dol_textishtml($messagePost)) {
3179 $messagePost = dol_nl2br($messagePost);
3180 }
3181 $message = $messagePost;
3182 $message .= '<br><br>';
3183
3184 foreach ($external_contacts as $key => $info_sendto) {
3185 // Check if recipient email is current user, if yes, we avoid to send email to him.
3186 if ($info_sendto['id'] == $user->contact_id) {
3187 continue;
3188 }
3189
3190 if ($info_sendto['email'] != '' && $info_sendto['email'] != $object->origin_email) {
3191 $email = $info_sendto['email'];
3192 if ($email != null) {
3193 $sendto[$email] = trim($info_sendto['firstname']." ".$info_sendto['lastname'])." <".$info_sendto['email'].">";
3194 }
3195
3196 $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], -1).' ('.strtolower((string) $info_sendto['libelle']).')';
3197 $message .= (!empty($recipient) ? '<br>'.$langs->trans('TicketNotificationRecipient').' : '.$recipient.'<br>' : '');
3198 }
3199 }
3200
3201 // If public interface is not enable, use link to internal page into mail
3202 $url_public_ticket = (getDolGlobalInt('TICKET_ENABLE_PUBLIC_INTERFACE') ?
3203 (getDolGlobalString('TICKET_URL_PUBLIC_INTERFACE') ? getDolGlobalString('TICKET_URL_PUBLIC_INTERFACE') . 'view.php' : dol_buildpath('/public/ticket/view.php', 2)) : dol_buildpath('/ticket/card.php', 2)).'?track_id='.urlencode($object->track_id);
3204
3205 if (getDolGlobalInt('TICKET_INCLUDE_LINK_TO_PUBLIC_INTERFACE_IN_MESSAGE')) {
3206 $message .= '<br>' . $langs->trans('TicketNewEmailBodyInfosTrackUrlCustomer') . ' : <a href="' . $url_public_ticket . '">' . $object->track_id . '</a><br>';
3207 }
3208
3209 // Build final message
3210 $message = $message_intro.'<br><br>'.$message;
3211
3212 // Add signature
3213 $message .= '<br>'.$message_signature;
3214
3215 if (!empty($object->origin_replyto)) {
3216 $sendto[$object->origin_replyto] = $object->origin_replyto;
3217 } elseif (!empty($object->origin_email)) {
3218 $sendto[$object->origin_email] = $object->origin_email;
3219 }
3220
3221 if ($object->fk_soc > 0 && !array_key_exists($object->origin_replyto, $sendto) && !array_key_exists($object->origin_email, $sendto)) {
3222 $object->socid = $object->fk_soc;
3223 $object->fetch_thirdparty();
3224 if (!empty($object->thirdparty->email)) {
3225 $sendto[$object->thirdparty->email] = $object->thirdparty->email;
3226 }
3227 }
3228
3229 // Add global email address recipient
3230 if (getDolGlobalString('TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS') && !array_key_exists(getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO'), $sendto)) {
3231 if (getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO')) {
3232 $sendto[getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO')] = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO');
3233 }
3234 }
3235
3236 $parameters = array('sendto' => $sendto);
3237 $reshook = $hookmanager->executeHooks('updateSendtoTicketMessage', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
3238 if (empty($reshook)) {
3239 $sendto = array_merge($sendto, $hookmanager->resArray);
3240 } elseif ($reshook > 0) {
3241 $sendto = $hookmanager->resArray;
3242 }
3243
3244 // If standardised form submitted, override auto-computed recipients with user selection
3245 if (GETPOSTISSET('receiver_multiselect')) {
3246 $sendto_manual = array();
3247
3248 $receiver_selected = GETPOST('receiver', 'array');
3249 if (is_array($receiver_selected)) {
3250 foreach ($receiver_selected as $email) {
3251 $email = trim((string) $email);
3252 if ($email && filter_var($email, FILTER_VALIDATE_EMAIL)) {
3253 $sendto_manual[$email] = $email;
3254 }
3255 }
3256 }
3257
3258 // Free input: plain email or "Name <email>", comma-separated
3259 $sendto_free = GETPOST('sendto', 'alphawithlgt');
3260 if ($sendto_free !== '') {
3261 foreach (explode(',', $sendto_free) as $entry) {
3262 $entry = trim($entry);
3263 if ($entry === '') {
3264 continue;
3265 }
3266 if (preg_match('/.*<\s*([^>]+)\s*>/', $entry, $matches)) {
3267 $email = trim($matches[1]);
3268 } else {
3269 $email = $entry;
3270 }
3271 if ($email && filter_var($email, FILTER_VALIDATE_EMAIL)) {
3272 $sendto_manual[$email] = $entry;
3273 }
3274 }
3275 }
3276
3277 $sendto = $sendto_manual;
3278 }
3279
3280 // CC: start with TICKET_SEND_INTERNAL_CC, then append form selection
3281 $sendtocc = array();
3282 $sendtocc_emails = array(); // lowercase email index for case-insensitive dedup
3283 if (getDolGlobalString("TICKET_SEND_INTERNAL_CC")) {
3284 foreach (explode(',', getDolGlobalString("TICKET_SEND_INTERNAL_CC")) as $cc_entry) {
3285 $cc_entry = trim($cc_entry);
3286 if (!$cc_entry) {
3287 continue;
3288 }
3289 // Extract bare email from optional "Name <email>" format
3290 if (preg_match('/<\s*([^>]+)\s*>/', $cc_entry, $m)) {
3291 $cc_email = strtolower(trim($m[1]));
3292 } else {
3293 $cc_email = strtolower($cc_entry);
3294 }
3295 if (!in_array($cc_email, $sendtocc_emails)) {
3296 $sendtocc[] = $cc_entry;
3297 $sendtocc_emails[] = $cc_email;
3298 }
3299 }
3300 }
3301
3302 if (GETPOSTISSET('receivercc_multiselect')) {
3303 $receivercc_selected = GETPOST('receivercc', 'array');
3304 if (is_array($receivercc_selected)) {
3305 foreach ($receivercc_selected as $email) {
3306 $email = trim((string) $email);
3307 if ($email && filter_var($email, FILTER_VALIDATE_EMAIL) && !in_array(strtolower($email), $sendtocc_emails)) {
3308 $sendtocc[] = $email;
3309 $sendtocc_emails[] = strtolower($email);
3310 }
3311 }
3312 }
3313
3314 // Free input: plain email or "Name <email>", comma-separated
3315 $sendtocc_free = GETPOST('sendtocc', 'alphawithlgt');
3316 if ($sendtocc_free !== '') {
3317 foreach (explode(',', $sendtocc_free) as $entry) {
3318 $entry = trim($entry);
3319 if ($entry === '') {
3320 continue;
3321 }
3322 if (preg_match('/.*<\s*([^>]+)\s*>/', $entry, $matches)) {
3323 $email = trim($matches[1]);
3324 } else {
3325 $email = $entry;
3326 }
3327 if ($email && filter_var($email, FILTER_VALIDATE_EMAIL) && !in_array(strtolower($email), $sendtocc_emails)) {
3328 $sendtocc[] = $email;
3329 $sendtocc_emails[] = strtolower($email);
3330 }
3331 }
3332 }
3333 }
3334
3335 // Don't try to send email when no recipient
3336 if (!empty($sendto)) {
3337 $email_from = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_FROM');
3338
3339 $replyto = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_REPLYTO');
3340
3341 $result = $this->sendTicketMessageByEmail($subject, $message, 0, $sendto, $listofpaths, $listofmimes, $listofnames, $sendtocc, $email_from, $replyto);
3342 if ($result) {
3343 // update last_msg_sent date of ticket (for last message sent to external users)
3344 $this->date_last_msg_sent = dol_now();
3345 $this->update($user, 1); // disable trigger when updating date_last_msg_sent. sendTicketMessageByEmail already create an event in actioncomm table.
3346
3347 // update event actioncomm $id
3348 //print 'update actioncomm id='.$id.' with sendto='.json_encode($sendto)." sendtocc=".json_encode($sendtocc)." email_msgid=".json_encode($this->email_msgid);
3349 $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm";
3350 $sql .= " SET email_msgid = '".$this->db->escape($this->email_msgid)."',";
3351 $sql .= " email_subject = '".$this->db->escape($subject)."',";
3352 $sql .= " email_from = '".$this->db->escape($email_from)."',";
3353 $sql .= " email_to = '".$this->db->escape(implode(',', $sendto))."',";
3354 $sql .= " email_tocc = '".$this->db->escape(implode(',', $sendtocc))."',";
3355 $sql .= " reply_to = '".$this->db->escape($replyto)."'";
3356 $sql .= " WHERE id = ".((int) $id);
3357
3358 $resql = $this->db->query($sql);
3359 }
3360 }
3361 }
3362 }
3363 }
3364 }
3365
3366 // Set status back to "In progress" if not set yet, but only if internal user and not a private message
3367 // Or set status to "In progress" if the client has answered and if the ticket has started
3368 // So we are sure to leave the STATUS_DRAFT, STATUS_NEED_INFO.
3369 // Except if TICKET_SET_STATUS_ON_ANSWER has been defined
3370 if ((getDolGlobalInt('TICKET_SET_STATUS_ON_ANSWER', -1) < 0
3371 && ($object->status < self::STATUS_IN_PROGRESS && !$user->socid && !$private))
3372 || ($object->status > self::STATUS_IN_PROGRESS && $public_area)) {
3373 // Set status
3374 $object->setStatut($object::STATUS_IN_PROGRESS, null, '', 'TICKET_MODIFY');
3375 } elseif (getDolGlobalInt('TICKET_SET_STATUS_ON_ANSWER', -1) >= 0 && empty($user->socid) && empty($private)) {
3376 // Set status
3377 $object->setStatut(getDolGlobalInt('TICKET_SET_STATUS_ON_ANSWER'), null, '', 'TICKET_MODIFY');
3378 }
3379
3380 return 1;
3381 } else {
3382 $this->setErrorsFromObject($object);
3383 return -1;
3384 }
3385 } else {
3386 return -1;
3387 }
3388 }
3389
3390
3406 public function sendTicketMessageByEmail($subject, $message, $send_internal_cc = 0, $array_receiver = array(), $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array(), $array_receiver_cc = array(), $email_from = '', $replyto = '')
3407 {
3408 global $conf, $langs, $user, $hookmanager;
3409
3410 if (getDolGlobalString('TICKET_DISABLE_ALL_MAILS')) {
3411 dol_syslog(get_class($this).'::sendTicketMessageByEmail: Emails are disable into ticket setup by option TICKET_DISABLE_ALL_MAILS', LOG_WARNING);
3412 return false;
3413 }
3414
3415 $langs->load("mails");
3416
3417 include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3418 //$contactstatic = new Contact($this->db);
3419
3420 // If no receiver defined, load all ticket linked contacts
3421 if (!is_array($array_receiver) || !count($array_receiver) > 0) {
3422 $array_receiver = $this->getInfosTicketInternalContact(1);
3423 $array_receiver = array_merge($array_receiver, $this->getInfosTicketExternalContact(1));
3424 }
3425
3426 dol_syslog("sendTicketMessageByEmail array_receiver=".json_encode($array_receiver), LOG_DEBUG);
3427 dol_syslog("sendTicketMessageByEmail array_receiver_cc=".json_encode($array_receiver_cc), LOG_DEBUG);
3428
3429 $sendtocc = '';
3430 if ($send_internal_cc) {
3431 $sendtocc = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_FROM');
3432 }
3433 if (!empty($array_receiver_cc) && is_array($array_receiver_cc)) {
3434 $sendtocc .= ($sendtocc ? ',' : '').implode(',', $array_receiver_cc);
3435 }
3436
3437 if (empty($email_from)) {
3438 $email_from = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_FROM');
3439 }
3440
3441 $parameters = array('from' => $email_from);
3442 $action = '';
3443 $reshook = $hookmanager->executeHooks('getTicketMessageEmailFrom', $parameters, $this, $action);
3444 if ($reshook && !empty($hookmanager->resArray['from'])) {
3445 $email_from = $hookmanager->resArray['from'];
3446 }
3447
3448 $is_sent = false;
3449 $this->email_msgids = array();
3450
3451 if (is_array($array_receiver) && count($array_receiver) > 0) {
3452 //foreach ($array_receiver as $key => $receiver) {
3453 $deliveryreceipt = 0;
3454 $filepath = $filename_list;
3455 $filename = $mimefilename_list;
3456 $mimetype = $mimetype_list;
3457
3458 // Send email
3459
3460 $old_MAIN_MAIL_AUTOCOPY_TO = getDolGlobalString('MAIN_MAIL_AUTOCOPY_TO');
3461 if (getDolGlobalString('TICKET_DISABLE_MAIL_AUTOCOPY_TO')) {
3462 $conf->global->MAIN_MAIL_AUTOCOPY_TO = '';
3463 }
3464
3465 $upload_dir_tmp = $conf->user->dir_output."/".$user->id.'/temp';
3466
3467 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
3468 $trackid = "tic".$this->id;
3469
3470 $moreinheader = 'X-Dolibarr-Info: sendTicketMessageByEmail'."\r\n";
3471 if (!empty($this->email_msgid)) {
3472 // We must also add 1 entry In-Reply-To: <$this->email_msgid> with Message-ID we respond from (See RFC5322).
3473 $moreinheader .= 'In-Reply-To: <'.$this->email_msgid.'>'."\r\n";
3474 // TODO We should now be able to give the in_reply_to as a dedicated parameter of new CMailFile() instead of into $moreinheader.
3475 }
3476
3477 // We should add here also a header 'References:'
3478 // According to RFC5322, we should add here all the References fields of the initial message concatenated with
3479 // the Message-ID of the message we respond from (but each ID must be once).
3480 $references = '';
3481 if (!empty($this->origin_references)) { // $this->origin_references should be '<'.$this->origin_references.'>'
3482 $references .= (empty($references) ? '' : ' ').$this->origin_references;
3483 }
3484 if (!empty($this->email_msgid) && !preg_match('/'.preg_quote($this->email_msgid, '/').'/', $references)) {
3485 $references .= (empty($references) ? '' : ' ').'<'.$this->email_msgid.'>';
3486 }
3487 if ($references) {
3488 $moreinheader .= 'References: '.$references."\r\n";
3489 // TODO We should now be able to give the references as a dedicated parameter of new CMailFile() instead of into $moreinheader.
3490 }
3491
3492 $receiverstring = '';
3493 foreach ($array_receiver as $key => $receiver) {
3494 $receiverstring .= ($receiverstring ? ',' : '').$receiver;
3495 }
3496
3497 $sendcontext = 'ticket';
3498
3499 // Send email
3500 $mailfile = new CMailFile($subject, $receiverstring, $email_from, $message, $filepath, $mimetype, $filename, $sendtocc, '', $deliveryreceipt, -1, '', '', $trackid, $moreinheader, $sendcontext, $replyto, $upload_dir_tmp);
3501
3502
3503 if ($mailfile->error) {
3504 setEventMessages($mailfile->error, null, 'errors');
3505 } else {
3506 $result = $mailfile->sendfile();
3507
3508 if ($result) {
3509 setEventMessages($langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($email_from, 2), $mailfile->getValidAddress($receiverstring, 2)), null, 'mesgs');
3510 $is_sent = true;
3511
3512 $this->email_msgid = $mailfile->msgid;
3513 } else {
3514 $langs->load("other");
3515 if ($mailfile->error) {
3516 setEventMessages($langs->trans('ErrorFailedToSendMail', $email_from, $receiverstring), null, 'errors');
3517 dol_syslog('ErrorFailedToSendMail from='.$email_from.' to='.$receiverstring.' : '.$mailfile->error);
3518 } elseif (getDolGlobalString('MAIN_DISABLE_ALL_MAILS')) {
3519 setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'errors');
3520 } else {
3521 setEventMessages($langs->trans('ErrorFailedToSendMail', $email_from, $receiverstring), null, 'errors');
3522 dol_syslog('ErrorFailedToSendMail from='.$email_from.' to='.$receiverstring.' : (no error details)', LOG_WARNING);
3523 }
3524 }
3525 }
3526
3527 if (getDolGlobalString('TICKET_DISABLE_MAIL_AUTOCOPY_TO')) {
3528 $conf->global->MAIN_MAIL_AUTOCOPY_TO = $old_MAIN_MAIL_AUTOCOPY_TO;
3529 }
3530 //}
3531 } else {
3532 $langs->load("other");
3533 setEventMessages($langs->trans('ErrorMailRecipientIsEmptyForSendTicketMessage'), null, 'warnings');
3534 }
3535
3536 return $is_sent;
3537 }
3538
3539 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3547 public function load_board($user, $mode)
3548 {
3549 // phpcs:enable
3550 global $user, $langs;
3551
3552 $now = dol_now();
3553 $delay_warning = 0;
3554
3555 $clause = " WHERE";
3556
3557 // The count is computed by the database instead of reading every ticket. No ticket is counted as late: the delay is 0
3558 // and the check on the creation date was doing nothing.
3559 $sql = "SELECT COUNT(p.rowid) as nb";
3560 $sql .= " FROM ".MAIN_DB_PREFIX."ticket as p";
3561 if (empty($user->socid) && isModEnabled('societe') && !$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
3562 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc";
3563 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
3564 $clause = " AND";
3565 }
3566 $sql .= $clause." p.entity IN (".getEntity('ticket').")";
3567 if ($mode == 'opened') {
3568 $sql .= " AND p.fk_statut NOT IN (".Ticket::STATUS_CLOSED.", ".Ticket::STATUS_CANCELED.")";
3569 }
3570 if ($user->socid) {
3571 $sql .= " AND p.fk_soc = ".((int) $user->socid);
3572 }
3573
3574 $resql = $this->db->query($sql);
3575 if ($resql) {
3576 $label = $labelShort = '';
3577 $status = '';
3578 if ($mode == 'opened') {
3579 $status = 'openall';
3580 //$delay_warning = $conf->ticket->warning_delay;
3581 $delay_warning = 0;
3582 $label = $langs->trans("MenuListNonClosed");
3583 $labelShort = $langs->trans("MenuListNonClosed");
3584 }
3585
3586 $response = new WorkboardResponse();
3587 //$response->warning_delay = $delay_warning / 60 / 60 / 24;
3588 $response->label = $label;
3589 $response->labelShort = $labelShort;
3590 $response->url = DOL_URL_ROOT.'/ticket/list.php?search_fk_statut[]='.$status;
3591 $response->img = img_object('', "ticket");
3592
3593 // This assignment in condition is not a bug. It allows walking the results.
3594 $obj = $this->db->fetch_object($resql);
3595 if ($obj) {
3596 $response->nbtodo = (int) $obj->nb;
3597 }
3598 return $response;
3599 } else {
3600 $this->error = $this->db->lasterror();
3601 return -1;
3602 }
3603 }
3604
3610 public function loadStateBoard()
3611 {
3612 global $user;
3613
3614 $this->nb = array();
3615 $clause = "WHERE";
3616
3617 $sql = "SELECT count(p.rowid) as nb";
3618 $sql .= " FROM ".MAIN_DB_PREFIX."ticket as p";
3619 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
3620 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
3621 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3622 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
3623 $clause = "AND";
3624 }
3625 $sql .= " ".$clause." p.entity IN (".getEntity('ticket').")";
3626
3627 $resql = $this->db->query($sql);
3628 if ($resql) {
3629 // This assignment in condition is not a bug. It allows walking the results.
3630 while ($obj = $this->db->fetch_object($resql)) {
3631 $this->nb["ticket"] = $obj->nb;
3632 }
3633 $this->db->free($resql);
3634 return 1;
3635 } else {
3636 dol_print_error($this->db);
3637 $this->error = $this->db->lasterror();
3638 return -1;
3639 }
3640 }
3641
3650 public static function replaceThirdparty($db, $origin_id, $dest_id)
3651 {
3652 $tables = array('ticket');
3653
3654 return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
3655 }
3656
3664 public function getKanbanView($option = '', $arraydata = null)
3665 {
3666 global $langs;
3667
3668 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3669
3670 $return = '<div class="box-flex-item box-flex-grow-zero">';
3671 $return .= '<div class="info-box info-box-sm">';
3672 $return .= '<span class="info-box-icon bg-infobox-action">';
3673 $return .= img_picto('', $this->picto);
3674 $return .= '</span>';
3675 $return .= '<div class="info-box-content">';
3676 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).'</span>';
3677 if ($selected >= 0) {
3678 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3679 }
3680 if (!empty($arraydata['user_assignment'])) {
3681 $return .= '<br><span class="info-box-label" title="'.dol_escape_htmltag($langs->trans("AssignedTo")).'">'.$arraydata['user_assignment'].'</span>';
3682 }
3683 if (property_exists($this, 'type_code') && !empty($this->type_code)) {
3684 $return .= '<br>';
3685 $return .= '<div class="tdoverflowmax125 inline-block">'.$langs->getLabelFromKey($this->db, 'TicketTypeShort'.$this->type_code, 'c_ticket_type', 'code', 'label', $this->type_code).'</div>';
3686 }
3687 if (method_exists($this, 'getLibStatut')) {
3688 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
3689 }
3690 $return .= '</div>';
3691 $return .= '</div>';
3692 $return .= '</div>';
3693
3694 return $return;
3695 }
3696
3708 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3709 {
3710 global $langs;
3711
3712 $langs->load("ticket");
3713 $outputlangs->load("ticket");
3714
3715 if (!dol_strlen($modele)) {
3716 $modele = 'generic_ticket_odt';
3717
3718 if (!empty($this->model_pdf)) {
3719 $modele = $this->model_pdf;
3720 } elseif (getDolGlobalString('TICKET_ADDON_PDF')) {
3721 $modele = getDolGlobalString('TICKET_ADDON_PDF');
3722 }
3723 }
3724
3725 $modelpath = "core/modules/ticket/doc/";
3726
3727 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3728 }
3729
3746 {
3747 global $conf, $langs, $user;
3748
3749 $error = 0;
3750 $this->output = '';
3751 $this->error = '';
3752
3753 if (!isModEnabled('ticket')) { // Should not happen. If module disabled, cron job should not be visible.
3754 $langs->load("agenda");
3755 $this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Ticket"));
3756 return 0;
3757 }
3758
3759 $delaybeforefirstresponse = getDolGlobalInt('TICKET_DELAY_BEFORE_FIRST_RESPONSE');
3760 $delaysincelastresponse = getDolGlobalInt('TICKET_DELAY_SINCE_LAST_RESPONSE');
3761 if (empty($delaybeforefirstresponse) && empty($delaysincelastresponse)) {
3762 $this->output = 'Neither TICKET_DELAY_BEFORE_FIRST_RESPONSE nor TICKET_DELAY_SINCE_LAST_RESPONSE is set, nothing to check.';
3763 return 0;
3764 }
3765
3766 $langs->loadLangs(array('main', 'ticket'));
3767
3768 $now = dol_now();
3769 $nbok = 0;
3770 $nbko = 0;
3771
3772 $listofticketsok = array();
3773 $listofticketsko = array();
3774
3775 // Label of the event recorded once a reminder is sent for a ticket. Also used to not send the same reminder twice the same day.
3776 $labelreminderok = 'sendReminderForStaleTicketsOK';
3777
3778 $sql = "SELECT t.rowid FROM ".MAIN_DB_PREFIX."ticket as t";
3779 $sql .= " WHERE t.entity IN (".getEntity('ticket').")";
3780 $sql .= " AND t.fk_statut NOT IN (".self::STATUS_CLOSED.", ".self::STATUS_CANCELED.")";
3781 $sql .= " AND t.fk_user_assign > 0";
3782 $sql .= " AND NOT EXISTS (SELECT a.id FROM ".MAIN_DB_PREFIX."actioncomm as a";
3783 $sql .= " WHERE a.elementtype = 'ticket' AND a.fk_element = t.rowid AND a.code = 'AC_EMAIL'";
3784 $sql .= " AND a.label = '".$this->db->escape($labelreminderok)."'";
3785 $sql .= " AND a.datep >= '".$this->db->idate(dol_get_first_hour($now))."')";
3786
3787 $resql = $this->db->query($sql);
3788 if ($resql) {
3789 $num_rows = $this->db->num_rows($resql);
3790
3791 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
3792 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
3793 $formmail = new FormMail($this->db);
3794
3795 $i = 0;
3796 while ($i < $num_rows) {
3797 $obj = $this->db->fetch_object($resql);
3798
3799 $ticketstatic = new Ticket($this->db);
3800 $ticketstatic->fetch($obj->rowid);
3801
3802 // Same late/not-late decision as the warning icon on ticket/list.php, so the email only ever
3803 // fires for tickets that already show as late there.
3804 $islate = false;
3805 $datelastmsgsent = (int) $ticketstatic->date_last_msg_sent;
3806 if ($delaybeforefirstresponse && $datelastmsgsent == 0) {
3807 $hourdiffcreation = ($now - (int) $ticketstatic->datec) / 3600;
3808 $islate = ($hourdiffcreation > $delaybeforefirstresponse);
3809 } elseif ($delaysincelastresponse) {
3810 $hourdiff = ($now - $datelastmsgsent) / 3600;
3811 $islate = ($hourdiff > $delaysincelastresponse);
3812 }
3813 if (!$islate) {
3814 $i++;
3815 continue;
3816 }
3817
3818 $recipient = new User($this->db);
3819 $recipientres = $recipient->fetch($ticketstatic->fk_user_assign);
3820
3821 if ($recipientres <= 0 || empty($recipient->email)) {
3822 $nbko++;
3823 $listofticketsko[$ticketstatic->id] = $ticketstatic->id;
3824 } else {
3825 $ticketstatic->fetch_thirdparty();
3826
3827 $arraydefaultmessage = null;
3828 $labeltouse = getDolGlobalString('TICKET_EMAIL_TEMPLATE_REMIND_STALE');
3829
3830 if (!empty($labeltouse)) {
3831 $arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'ticket', $user, $langs, 0, 1, $labeltouse);
3832 }
3833
3834 if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
3835 $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $ticketstatic);
3836 complete_substitutions_array($substitutionarray, $langs, $ticketstatic);
3837 $substitutionarray['__TICKET_STALE_SINCE_HOURS__'] = ($datelastmsgsent == 0)
3838 ? (string) round(($now - (int) $ticketstatic->datec) / 3600)
3839 : (string) round(($now - $datelastmsgsent) / 3600);
3840
3841 $subject = make_substitutions($arraydefaultmessage->topic, $substitutionarray, $langs);
3842 $msg = make_substitutions($arraydefaultmessage->content, $substitutionarray, $langs);
3843 $email_from = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_FROM', $conf->email_from);
3844 $to = (string) $recipient->email;
3845
3846 $trackid = 'tic'.$ticketstatic->id;
3847 $moreinheader = 'X-Dolibarr-Info: sendReminderForStaleTickets'."\r\n";
3848
3849 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
3850 $cmail = new CMailFile($subject, $to, $email_from, $msg, array(), array(), array(), '', '', 0, 1, '', '', $trackid, $moreinheader);
3851 $result = $cmail->sendfile();
3852 if (!$result) {
3853 $error++;
3854 $this->error .= $cmail->error.' ';
3855 if (!is_null($cmail->errors)) {
3856 $this->errors = array_merge($this->errors, $cmail->errors);
3857 }
3858 $nbko++;
3859 $listofticketsko[$ticketstatic->id] = $ticketstatic->id;
3860 } else {
3861 $nbok++;
3862 $listofticketsok[$ticketstatic->id] = $ticketstatic->id;
3863
3864 // Insert record of email sent, as an agenda event on the ticket (same convention as other automated reminder emails)
3865 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
3866
3867 $actioncomm = new ActionComm($this->db);
3868 $actioncomm->type_code = 'AC_OTH_AUTO';
3869 $actioncomm->code = 'AC_EMAIL';
3870 $actioncomm->label = $labelreminderok;
3871 $actioncomm->note_private = $msg;
3872 $actioncomm->fk_project = 0;
3873 $actioncomm->datep = $now;
3874 $actioncomm->datef = $now;
3875 $actioncomm->percentage = -1; // Not applicable
3876 $actioncomm->socid = (is_object($ticketstatic->thirdparty) ? $ticketstatic->thirdparty->id : 0);
3877 $actioncomm->contact_id = 0;
3878 $actioncomm->authorid = $user->id;
3879 $actioncomm->userownerid = $user->id;
3880 $actioncomm->email_msgid = $cmail->msgid;
3881 $actioncomm->email_from = $email_from;
3882 $actioncomm->email_sender = '';
3883 $actioncomm->email_to = $to;
3884 $actioncomm->email_subject = $subject;
3885
3886 $actioncomm->fk_element = $ticketstatic->id;
3887 $actioncomm->elementid = $ticketstatic->id;
3888 $actioncomm->elementtype = $ticketstatic->element;
3889
3890 $actioncomm->create($user);
3891 }
3892 } else {
3893 $error++;
3894 $this->error .= "Can't find email template with label=".$labeltouse.", to use for the reminding email ";
3895
3896 $nbko++;
3897 $listofticketsko[$ticketstatic->id] = $ticketstatic->id;
3898
3899 // Do not break here: a template issue for one ticket (ex: template not found) must not
3900 // prevent the reminder from being sent for the other late tickets.
3901 }
3902 }
3903
3904 $i++;
3905 }
3906 } else {
3907 $this->error = $this->db->lasterror();
3908 return 1;
3909 }
3910
3911 $this->output = 'Found '.($nbok + $nbko).' late tickets to send reminder for.';
3912 $this->output .= ' Sent email successfully for '.$nbok.' tickets';
3913 if ($nbko) {
3914 $this->output .= ' - Canceled for '.$nbko.' ticket(s) (no email for the assigned user, missing template, or send error)';
3915 }
3916
3917 if ($error) {
3918 return 1;
3919 }
3920 return 0;
3921 }
3922}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$c
Definition line.php:353
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
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...
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.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Class to manage contact/addresses.
Class to manage Dolibarr database access.
Class to manage ECM files.
Class to manage generation of HTML components Only common components must be here.
static selectarray($htmlname, $array, $id='', $show_empty=0, $key_in_label=0, $value_as_key=0, $moreparam='', $translate=0, $maxlen=0, $disabled=0, $sort='', $morecss='minwidth75', $addjscombo=1, $moreparamonempty='', $disablebademail=0, $nohtmlescape=0)
Return a HTML select string, built from an array of key+value.
Class to manage a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
Class to manage third parties objects (customers, suppliers, prospects...)
fetch($id=0, $ref='', $track_id='', $email_msgid='')
Load object in memory from the database.
fetchAll($user, $sortorder='ASC', $sortfield='t.datec', $limit=0, $offset=0, $arch=0, $filter='')
Load all objects in memory from database.
static replaceThirdparty($db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
createTicketMessage($user, $notrigger=0, $filename_list=array(), $mimetype_list=array(), $mimefilename_list=array(), $send_email=false, $public_area=0, $summary='', $external_contacts=[])
Add message into database.
listeContact($statusoflink=-1, $source='external', $list=0, $code='', $status=-1)
Get array of all contacts for a ticket Override method of file commonobject.class....
loadCacheMsgsTicket()
Load the list of event on ticket into ->cache_msgs_ticket.
setProgression($percent)
Define progression of current ticket.
searchSocidByEmail($email, $type=0, $filters=array(), $clause='AND')
Search and fetch thirparties by email.
loadCacheSeveritiesTickets()
Load into cache the list of ticket severities (configurable in the dictionary)
$fields
'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]',...
getInfosTicketExternalContact($status=-1)
Retrieve information about external contacts.
searchContactByEmail($email, $socid=0, $case='')
Search and fetch contacts by email.
getIdTicketCustomerInvolvedContact()
Return id des contacts clients des intervenants.
LibStatut($status, $mode=0, $notooltip=0, $progress=0)
Return status label of object.
setContract($contractid)
Link element with a contract.
setReadDate($user, $notrigger=0)
Set read date if not already set.
getTicketAllContacts()
Return id of all contacts for ticket.
createFromClone(User $user, $fromid)
Load an object from its id and create a new one in database.
assignUser($user, $id_assign_user, $notrigger=0)
Set an assigned user to a ticket.
loadStateBoard()
Load indicator this->nb of global stats widget.
getTooltipContentArray($params)
getTooltipContentArray
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
printSelectStatus($selected="")
Print selected status.
is_photo_available($sdir)
Return if at least one photo is available.
getIdTicketInternalContact()
Return id des contacts interne de suivi.
update($user, $notrigger=0)
Update object into database.
loadCacheCategoriesTickets($publicgroup=-1)
Load into a cache array, the list of ticket categories (setup done into dictionary)
setCustomer($id)
Define parent commany of current ticket.
markAsRead($user, $notrigger=0)
Mark a message as read.
getDefaultRef($thirdparty=null)
Get a default reference.
const STATUS_NOT_READ
Status.
sendTicketMessageByEmail($subject, $message, $send_internal_cc=0, $array_receiver=array(), $filename_list=array(), $mimetype_list=array(), $mimefilename_list=array(), $array_receiver_cc=array(), $email_from='', $replyto='')
Send ticket by email to linked contacts.
getTicketAllCustomerContacts()
Return id of all contacts for ticket.
sendReminderForStaleTickets()
Send an email to the assigned user when a non-closed ticket has gone too long without a reply.
verify()
Check properties of ticket are ok (like ref, track_id, ...).
setCategories($categories)
Sets object to supplied categories.
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
newMessage($user, &$action, $private=1, $public_area=0)
Add new message on a ticket (private/public area).
getIdTicketCustomerContact()
Return id des contacts clients pour le suivi ticket.
checkExistingRef(string $action, string $getRef)
Check if ref exists or not.
__construct(DoliDB $db)
Constructor.
loadCacheTypesTickets()
Load into a cache the types of tickets (setup done into dictionaries)
getLibStatut($mode=0)
Return status label of object.
close(User $user, $mode=0)
Close a ticket.
getIdTicketInternalInvolvedContact()
Return id des contacts clients des intervenants.
copyFilesForTicket($forcetrackid=null)
Copy files defined into $_SESSION array into the ticket directory of attached files.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1)
Return a link to the object card (with optionally the picto)
load_board($user, $mode)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
getInfosTicketInternalContact($status=-1)
Retrieve information about internal contacts.
create($user, $notrigger=0)
Create object into database.
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_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
Definition date.lib.php:686
dirbasename($pathfile)
Return the relative dirname (relative to DOL_DATA_ROOT) of a full path string.
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=null)
Move a file into another name.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_is_file($pathoffile)
Return if path is a file.
dol_is_dir($folder)
Test if filename is a directory.
dol_now($mode='gmt')
Return date for now.
setEntity($currentobject)
Set entity id to use when to create an object.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
isDolTms($timestamp)
isDolTms check if a timestamp is valid.
dol_nl2br($stringtoencode, $nl2brmode=0, $forxml=false)
Replace CRLF in string with a HTML BR tag.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
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.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
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).
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
utf8_check($str)
Check if a string is in UTF8.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
vignette($file, $maxWidth=160, $maxHeight=120, $extName='_small', $quality=50, $outdir='thumbs', $targetformat=0)
Create a thumbnail from an image file (Supported extensions are gif, jpg, png and bmp).
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
Class to generate the form for creating a new ticket.
generate_random_id($car=16)
Generate a random id.