dolibarr 23.0.4
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-2025 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-2025 MDW <mdeweerd@users.noreply.github.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 */
24
31// Put here all includes required by your class file
32require_once DOL_DOCUMENT_ROOT."/core/class/commonobject.class.php";
33require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
34require_once DOL_DOCUMENT_ROOT.'/core/lib/ticket.lib.php';
35
36
40class Ticket extends CommonObject
41{
45 public $db;
46
50 public $element = 'ticket';
51
55 public $table_element = 'ticket';
56
60 public $fk_element = 'fk_ticket';
61
65 public $picto = 'ticket';
66
70 public $track_id;
71
75 public $fk_soc;
76
80 public $socid;
81
85 public $fk_contract;
86
90 public $origin_email;
91
95 public $fk_user_create;
96
100 public $fk_user_assign;
101
105 public $subject;
106
110 public $message;
111
115 public $private;
116
122 public $fk_statut;
123
127 public $status;
128
132 public $resolution;
133
137 public $progress;
138
142 public $timing;
143
147 public $type_code;
148
152 public $category_code;
153
157 public $severity_code;
158
162 public $type_label;
163
167 public $category_label;
168
172 public $severity_label;
173
177 public $email_from;
178
182 public $origin_replyto;
183
187 public $origin_references;
188
192 public $datec;
193
197 public $date_read;
198
202 public $date_last_msg_sent;
203
207 public $date_close;
208
212 public $cache_types_tickets;
213
217 public $cache_msgs_ticket;
218
222 public $notify_tiers_at_create;
223
227 public $email_msgid;
228
232 public $email_date;
233
237 public $ip;
238
242 public $lines;
243
247 public $regeximgext = '\.gif|\.jpg|\.jpeg|\.png|\.bmp|\.webp|\.xpm|\.xbm'; // See also into images.lib.php
248
252 const STATUS_NOT_READ = 0; // Draft. Not take into account yet.
253 const STATUS_READ = 1; // Ticket was read.
254 const STATUS_ASSIGNED = 2; // Ticket was just assigned to someone. Not in progress yet.
255 const STATUS_IN_PROGRESS = 3; // In progress
256 const STATUS_NEED_MORE_INFO = 5; // Waiting requester feedback
257 const STATUS_WAITING = 7; // On hold
258 const STATUS_CLOSED = 8; // Closed - Solved
259 const STATUS_CANCELED = 9; // Closed - Not solved
260
261
288 // BEGIN MODULEBUILDER PROPERTIES
289 public $fields = array(
290 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'visible' => -2, 'enabled' => 1, 'position' => 1, 'notnull' => 1, 'index' => 1, 'comment' => "Id"),
291 'entity' => array('type' => 'integer', 'label' => 'Entity', 'visible' => 0, 'enabled' => 1, 'position' => 5, 'notnull' => 1, 'index' => 1),
292 '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),
293 'track_id' => array('type' => 'varchar(255)', 'label' => 'TicketTrackId', 'visible' => -2, 'enabled' => 1, 'position' => 11, 'notnull' => -1, 'searchall' => 1, 'help' => "Help text"),
294 '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'),
295 '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'),
296 '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'),
297 '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'),
298 '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),
299 'type_code' => array('type' => 'varchar(32)', 'label' => 'Type', 'visible' => 1, 'enabled' => 1, 'position' => 20, 'notnull' => -1, 'help' => "", 'csslist' => 'tdoverflowmax100'),
300 'category_code' => array('type' => 'varchar(32)', 'label' => 'TicketCategory', 'visible' => -1, 'enabled' => 1, 'position' => 21, 'notnull' => -1, 'help' => "", 'css' => 'maxwidth100 tdoverflowmax200'),
301 'severity_code' => array('type' => 'varchar(32)', 'label' => 'Severity', 'visible' => 1, 'enabled' => 1, 'position' => 22, 'notnull' => -1, 'help' => "", 'css' => 'maxwidth100 tdoverflowmax100'),
302 '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'),
303 'notify_tiers_at_create' => array('type' => 'integer', 'label' => 'NotifyThirdparty', 'visible' => -1, 'enabled' => 0, 'position' => 51, 'notnull' => 1, 'index' => 1),
304 '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"),
305 '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"),
306 //'timing' => array('type'=>'varchar(20)', 'label'=>'Timing', 'visible'=>-1, 'enabled'=>1, 'position'=>42, 'notnull'=>-1, 'help'=>""), // what is this ?
307 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'visible' => 1, 'enabled' => 1, 'position' => 500, 'notnull' => 1, 'csslist' => 'nowraponall'),
308 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'visible' => -1, 'enabled' => 1, 'position' => 501, 'notnull' => 1),
309 'date_read' => array('type' => 'datetime', 'label' => 'DateReading', 'visible' => -1, 'enabled' => 1, 'position' => 505, 'notnull' => 1, 'csslist' => 'nowraponall'),
310 'date_last_msg_sent' => array('type' => 'datetime', 'label' => 'TicketLastMessageDate', 'visible' => 0, 'enabled' => 1, 'position' => 506, 'notnull' => -1),
311 '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'),
312 'date_close' => array('type' => 'datetime', 'label' => 'TicketCloseOn', 'visible' => -1, 'enabled' => 1, 'position' => 510, 'notnull' => 1),
313 'message' => array('type' => 'html', 'label' => 'Message', 'visible' => -2, 'enabled' => 1, 'position' => 540, 'notnull' => -1,),
314 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 110),
315 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 115),
316 'email_msgid' => array('type' => 'varchar(255)', 'label' => 'EmailMsgID', 'visible' => -2, 'enabled' => 1, 'position' => 540, 'notnull' => -1, 'help' => 'EmailMsgIDDesc', 'csslist' => 'tdoverflowmax100'),
317 'email_date' => array('type' => 'datetime', 'label' => 'EmailDate', 'visible' => -2, 'enabled' => 1, 'position' => 541),
318 'progress' => array('type' => 'integer', 'label' => 'Progression', 'visible' => -1, 'enabled' => 1, 'position' => 540, 'notnull' => -1, 'css' => 'right', 'help' => "", 'isameasure' => 1, 'csslist' => 'width50'),
319 'resolution' => array('type' => 'integer', 'label' => 'Resolution', 'visible' => -1, 'enabled' => 'getDolGlobalString("TICKET_ENABLE_RESOLUTION")', 'position' => 550, 'notnull' => 1),
320 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'PDFTemplate', 'enabled' => 1, 'visible' => 0, 'position' => 560),
321 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => 0, 'position' => 570),
322 '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')),
323 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 900),
324 );
325 // END MODULEBUILDER PROPERTIES
326
327
333 public function __construct(DoliDB $db)
334 {
335 $this->db = $db;
336
337 $this->ismultientitymanaged = 1;
338 $this->isextrafieldmanaged = 1;
339
340 $this->labelStatusShort = array(
341 self::STATUS_NOT_READ => 'Unread',
342 self::STATUS_READ => 'Read',
343 self::STATUS_ASSIGNED => 'Assigned',
344 self::STATUS_IN_PROGRESS => 'InProgress',
345 self::STATUS_NEED_MORE_INFO => 'NeedMoreInformationShort',
346 self::STATUS_WAITING => 'OnHold',
347 self::STATUS_CLOSED => 'SolvedClosed',
348 self::STATUS_CANCELED => 'Canceled'
349 );
350 $this->labelStatus = array(
351 self::STATUS_NOT_READ => 'Unread',
352 self::STATUS_READ => 'Read',
353 self::STATUS_ASSIGNED => 'Assigned',
354 self::STATUS_IN_PROGRESS => 'InProgress',
355 self::STATUS_NEED_MORE_INFO => 'NeedMoreInformation',
356 self::STATUS_WAITING => 'OnHold',
357 self::STATUS_CLOSED => 'SolvedClosed',
358 self::STATUS_CANCELED => 'Canceled'
359 );
360
361 if (!getDolGlobalString('TICKET_INCLUDE_SUSPENDED_STATUS')) {
362 unset($this->fields['fk_statut']['arrayofkeyval'][self::STATUS_WAITING]);
363 unset($this->labelStatusShort[self::STATUS_WAITING]);
364 unset($this->labelStatus[self::STATUS_WAITING]);
365 }
366 }
367
374 private function verify()
375 {
376 $this->errors = array();
377
378 $result = 0;
379
380 // Clean parameters
381 if (isset($this->ref)) {
382 $this->ref = trim($this->ref);
383 }
384
385 if (isset($this->track_id)) {
386 $this->track_id = trim($this->track_id);
387 }
388
389 if (isset($this->fk_soc)) {
390 $this->fk_soc = (int) $this->fk_soc;
391 }
392
393 if (isset($this->fk_project)) {
394 $this->fk_project = (int) $this->fk_project;
395 }
396
397 if (isset($this->origin_email)) {
398 $this->origin_email = trim($this->origin_email);
399 }
400
401 if (isset($this->fk_user_create)) {
402 $this->fk_user_create = (int) $this->fk_user_create;
403 }
404
405 if (isset($this->fk_user_assign)) {
406 $this->fk_user_assign = (int) $this->fk_user_assign;
407 }
408
409 if (isset($this->subject)) {
410 $this->subject = trim($this->subject);
411 }
412
413 if (isset($this->message)) {
414 $this->message = trim($this->message);
415 if (dol_strlen($this->message) > 65000) {
416 global $langs;
417 $langs->loadLangs(array('errors', 'ticket'));
418 $this->errors[] = $langs->trans('ErrorFieldTooLong', $langs->transnoentitiesnoconv('InitialMessage'));
419 dol_syslog(get_class($this).'::create error -1 message too long', LOG_ERR);
420 $result = -1;
421 }
422 }
423
424 if (isset($this->status)) {
425 $this->status = (int) $this->status;
426 }
427
428 if (isset($this->resolution)) {
429 $this->resolution = (int) $this->resolution;
430 }
431
432 if (isset($this->progress)) {
433 $this->progress = (int) $this->progress;
434 }
435
436 if (isset($this->timing)) {
437 $this->timing = trim($this->timing);
438 }
439
440 if (isset($this->type_code)) {
441 $this->type_code = trim($this->type_code);
442 }
443
444 if (isset($this->category_code)) {
445 $this->category_code = trim($this->category_code);
446 }
447
448 if (isset($this->severity_code)) {
449 $this->severity_code = trim($this->severity_code);
450 }
451
452 if (empty($this->ref)) {
453 $this->errors[] = 'ErrorTicketRefRequired';
454 dol_syslog(get_class($this)."::create error -1 ref null", LOG_ERR);
455 $result = -1;
456 }
457
458 return $result;
459 }
460
468 public function checkExistingRef(string $action, string $getRef)
469 {
470 $test = new self($this->db);
471
472 if ($test->fetch(0, $getRef) > 0) {
473 if (($action == 'add') || ($action == 'update' && $this->ref != $getRef)) {
474 return true;
475 }
476 }
477
478 $this->ref = $getRef;
479 return false;
480 }
481
489 public function create($user, $notrigger = 0)
490 {
491 global $conf;
492
493 $error = 0;
494
495 // Clean parameters
496 if (empty($this->datec)) {
497 $this->datec = dol_now();
498 }
499 if (empty($this->track_id)) {
500 $this->track_id = generate_random_id(16);
501 }
502
503 // Check more parameters
504 // If error, this->errors[] is filled
505 $result = $this->verify();
506
507 if ($result >= 0) {
508 // setEntity will set entity with the right value if empty or change it for the right value if multicompany module is active
509 $this->entity = setEntity($this);
510
511 // Insert request
512 $sql = "INSERT INTO ".MAIN_DB_PREFIX."ticket(";
513 $sql .= "ref,";
514 $sql .= "track_id,";
515 $sql .= "fk_soc,";
516 $sql .= "fk_project,";
517 $sql .= "fk_contract,";
518 $sql .= "origin_email,";
519 $sql .= "origin_replyto,";
520 $sql .= "origin_references,";
521 $sql .= "fk_user_create,";
522 $sql .= "fk_user_assign,";
523 $sql .= "email_msgid,";
524 $sql .= "email_date,";
525 $sql .= "subject,";
526 $sql .= "message,";
527 $sql .= "note_private,";
528 $sql .= "note_public,";
529 $sql .= "fk_statut,";
530 $sql .= "resolution,";
531 $sql .= "progress,";
532 $sql .= "timing,";
533 $sql .= "type_code,";
534 $sql .= "category_code,";
535 $sql .= "severity_code,";
536 $sql .= "datec,";
537 $sql .= "date_read,";
538 $sql .= "date_close,";
539 $sql .= "entity,";
540 $sql .= "notify_tiers_at_create,";
541 $sql .= "model_pdf,";
542 $sql .= "ip";
543 $sql .= ") VALUES (";
544 $sql .= " ".(!isset($this->ref) ? '' : "'".$this->db->escape($this->ref)."'").",";
545 $sql .= " ".(!isset($this->track_id) ? 'NULL' : "'".$this->db->escape($this->track_id)."'").",";
546 $sql .= " ".($this->fk_soc > 0 ? ((int) $this->fk_soc) : "null").",";
547 $sql .= " ".($this->fk_project > 0 ? ((int) $this->fk_project) : "null").",";
548 $sql .= " ".($this->fk_contract > 0 ? ((int) $this->fk_contract) : "null").",";
549 $sql .= " ".(!isset($this->origin_email) ? 'NULL' : "'".$this->db->escape($this->origin_email)."'").",";
550 $sql .= " ".(!isset($this->origin_replyto) ? 'NULL' : "'".$this->db->escape($this->origin_replyto)."'").",";
551 $sql .= " ".(!isset($this->origin_references) ? 'NULL' : "'".$this->db->escape($this->origin_references)."'").",";
552 $sql .= " ".(!isset($this->fk_user_create) ? ($user->id > 0 ? ((int) $user->id) : 'NULL') : ($this->fk_user_create > 0 ? ((int) $this->fk_user_create) : 'NULL')).",";
553 $sql .= " ".($this->fk_user_assign > 0 ? ((int) $this->fk_user_assign) : 'NULL').",";
554 $sql .= " ".(empty($this->email_msgid) ? 'NULL' : "'".$this->db->escape($this->email_msgid)."'").",";
555 $sql .= " ".(!isDolTms($this->email_date) ? 'NULL' : "'".$this->db->idate($this->email_date)."'").",";
556 $sql .= " ".(!isset($this->subject) ? 'NULL' : "'".$this->db->escape($this->subject)."'").",";
557 $sql .= " ".(!isset($this->message) ? 'NULL' : "'".$this->db->escape($this->message)."'").",";
558 $sql .= " ".(!isset($this->note_private) ? 'NULL' : "'".$this->db->escape($this->note_private)."'").",";
559 $sql .= " ".(!isset($this->note_public) ? 'NULL' : "'".$this->db->escape($this->note_public)."'").",";
560 $sql .= " ".(!isset($this->status) ? '0' : ((int) $this->status)).",";
561 $sql .= " ".(!isset($this->resolution) ? 'NULL' : ((int) $this->resolution)).",";
562 $sql .= " ".(!isset($this->progress) ? '0' : ((int) $this->progress)).",";
563 $sql .= " ".(!isset($this->timing) ? 'NULL' : "'".$this->db->escape($this->timing)."'").",";
564 $sql .= " ".(!isset($this->type_code) ? 'NULL' : "'".$this->db->escape($this->type_code)."'").",";
565 $sql .= " ".(empty($this->category_code) || $this->category_code == '-1' ? 'NULL' : "'".$this->db->escape($this->category_code)."'").",";
566 $sql .= " ".(!isset($this->severity_code) ? 'NULL' : "'".$this->db->escape($this->severity_code)."'").",";
567 $sql .= " ".(!isDolTms($this->datec) ? 'NULL' : "'".$this->db->idate($this->datec)."'").",";
568 $sql .= " ".(!isset($this->date_read) || dol_strlen((string) $this->date_read) == 0 ? 'NULL' : "'".$this->db->idate($this->date_read)."'").",";
569 $sql .= " ".(!isset($this->date_close) || dol_strlen((string) $this->date_close) == 0 ? 'NULL' : "'".$this->db->idate($this->date_close)."'");
570 $sql .= ", ".((int) $this->entity);
571 $sql .= ", ".(!isset($this->notify_tiers_at_create) ? 1 : ((int) $this->notify_tiers_at_create));
572 $sql .= ", '".$this->db->escape($this->model_pdf)."'";
573 $sql .= ", ".(!isset($this->ip) ? 'NULL' : "'".$this->db->escape($this->ip)."'");
574 $sql .= ")";
575
576 $this->db->begin();
577
578 dol_syslog(get_class($this)."::create", LOG_DEBUG);
579 $resql = $this->db->query($sql);
580 if (!$resql) {
581 $error++;
582 $this->errors[] = "Error ".$this->db->lasterror();
583 }
584
585 if (!$error) {
586 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."ticket");
587 }
588
589 if (!$error && getDolGlobalString('TICKET_ADD_AUTHOR_AS_CONTACT') && empty($this->context["createdfrompublicinterface"])) {
590 // add creator as contributor
591
592 // We first check the type of contact (internal or external)
593 if (!empty($user->socid) && !empty($user->contact_id) && getDolGlobalInt('TICKET_ADD_AUTHOR_AS_CONTACT') == 2) {
594 $contact_type = 'external';
595 $contributor_id = $user->contact_id;
596 } else {
597 $contact_type = 'internal';
598 $contributor_id = $user->id;
599 }
600
601 // We add the creator as contributor
602 if ($this->add_contact($contributor_id, 'CONTRIBUTOR', $contact_type) < 0) {
603 $error++;
604 }
605 }
606
607 if (!$error && $this->fk_user_assign > 0) {
608 if ($this->add_contact($this->fk_user_assign, 'SUPPORTTEC', 'internal') < 0) {
609 $error++;
610 }
611 }
612
613
614 //Update extrafield
615 if (!$error) {
616 $result = $this->insertExtraFields();
617 if ($result < 0) {
618 $error++;
619 }
620 }
621
622 if (!$error && !$notrigger) {
623 // Call trigger
624 $result = $this->call_trigger('TICKET_CREATE', $user);
625 if ($result < 0) {
626 $error++;
627 }
628 // End call triggers
629 }
630
631 // Commit or rollback
632 if ($error) {
633 foreach ($this->errors as $errmsg) {
634 dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
635 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
636 }
637 $this->db->rollback();
638 return -1 * $error;
639 } else {
640 $this->db->commit();
641 return $this->id;
642 }
643 } else {
644 dol_syslog(get_class($this)."::Create fails verify ".implode(',', $this->errors), LOG_WARNING);
645 return -3;
646 }
647 }
648
658 public function fetch($id = 0, $ref = '', $track_id = '', $email_msgid = '')
659 {
660 global $langs;
661
662 // Check parameters
663 if (empty($id) && empty($ref) && empty($track_id) && empty($email_msgid)) {
664 $this->error = 'ErrorWrongParameters';
665 dol_print_error(null, get_class($this)."::fetch ".$this->error);
666 return -1;
667 }
668
669 $sql = "SELECT";
670 $sql .= " t.rowid,";
671 $sql .= " t.entity,";
672 $sql .= " t.ref,";
673 $sql .= " t.track_id,";
674 $sql .= " t.fk_soc,";
675 $sql .= " t.fk_project,";
676 $sql .= " t.fk_contract,";
677 $sql .= " t.origin_email,";
678 $sql .= " t.origin_replyto,";
679 $sql .= " t.origin_references,";
680 $sql .= " t.fk_user_create,";
681 $sql .= " t.fk_user_assign,";
682 $sql .= " t.email_msgid,";
683 $sql .= " t.email_date,";
684 $sql .= " t.subject,";
685 $sql .= " t.message,";
686 $sql .= " t.note_private,";
687 $sql .= " t.note_public,";
688 $sql .= " t.fk_statut as status,";
689 $sql .= " t.resolution,";
690 $sql .= " t.progress,";
691 $sql .= " t.timing,";
692 $sql .= " t.type_code,";
693 $sql .= " t.category_code,";
694 $sql .= " t.severity_code,";
695 $sql .= " t.datec,";
696 $sql .= " t.date_read,";
697 $sql .= " t.date_last_msg_sent,";
698 $sql .= " t.date_close,";
699 $sql .= " t.tms,";
700 $sql .= " t.model_pdf,";
701 $sql .= " t.extraparams,";
702 $sql .= " t.ip,";
703 $sql .= " type.label as type_label, category.label as category_label, severity.label as severity_label";
704 $sql .= " FROM ".MAIN_DB_PREFIX."ticket as t";
705 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_type as type ON type.code=t.type_code";
706 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_category as category ON category.code=t.category_code";
707 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_severity as severity ON severity.code=t.severity_code";
708
709 if ($id) {
710 $sql .= " WHERE t.rowid = ".((int) $id);
711 } else {
712 $sql .= " WHERE t.entity IN (".getEntity($this->element, 1).")";
713 if (!empty($ref)) {
714 $sql .= " AND t.ref = '".$this->db->escape($ref)."'";
715 } elseif ($track_id) {
716 $sql .= " AND t.track_id = '".$this->db->escape($track_id)."'";
717 } else {
718 $sql .= " AND t.email_msgid = '".$this->db->escape($email_msgid)."'";
719 }
720 }
721
722 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
723 $resql = $this->db->query($sql);
724 if ($resql) {
725 if ($this->db->num_rows($resql)) {
726 $obj = $this->db->fetch_object($resql);
727
728 $this->id = $obj->rowid;
729 $this->entity = $obj->entity;
730 $this->ref = $obj->ref;
731 $this->track_id = $obj->track_id;
732 $this->fk_soc = $obj->fk_soc;
733 $this->socid = $obj->fk_soc; // for fetch_thirdparty() method
734 $this->fk_project = $obj->fk_project;
735 $this->fk_contract = $obj->fk_contract;
736 $this->origin_email = $obj->origin_email;
737 $this->origin_replyto = $obj->origin_replyto;
738 $this->origin_references = $obj->origin_references;
739 $this->fk_user_create = $obj->fk_user_create;
740 $this->fk_user_assign = $obj->fk_user_assign;
741 $this->email_msgid = $obj->email_msgid;
742 $this->email_date = $this->db->jdate($obj->email_date);
743 $this->subject = $obj->subject;
744 $this->message = $obj->message;
745 $this->note_private = $obj->note_private;
746 $this->note_public = $obj->note_public;
747 $this->model_pdf = $obj->model_pdf;
748 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
749 $this->ip = $obj->ip;
750
751 $this->status = $obj->status;
752 $this->fk_statut = $this->status; // For backward compatibility
753
754 $this->resolution = $obj->resolution;
755 $this->progress = $obj->progress;
756 $this->timing = $obj->timing;
757
758 $this->type_code = $obj->type_code;
759 $label_type = ($langs->trans("TicketTypeShort".$obj->type_code) != "TicketTypeShort".$obj->type_code ? $langs->trans("TicketTypeShort".$obj->type_code) : ($obj->type_label != '-' ? $obj->type_label : ''));
760 $this->type_label = $label_type;
761
762 $this->category_code = $obj->category_code;
763 $label_category = ($langs->trans("TicketCategoryShort".$obj->category_code) != "TicketCategoryShort".$obj->category_code ? $langs->trans("TicketCategoryShort".$obj->category_code) : ($obj->category_label != '-' ? $obj->category_label : ''));
764 $this->category_label = $label_category;
765
766 $this->severity_code = $obj->severity_code;
767 $label_severity = ($langs->trans("TicketSeverityShort".$obj->severity_code) != "TicketSeverityShort".$obj->severity_code ? $langs->trans("TicketSeverityShort".$obj->severity_code) : ($obj->severity_label != '-' ? $obj->severity_label : ''));
768 $this->severity_label = $label_severity;
769
770 $this->datec = $this->db->jdate($obj->datec);
771 $this->date_creation = $this->db->jdate($obj->datec);
772 $this->date_read = $this->db->jdate($obj->date_read);
773 $this->date_validation = $this->db->jdate($obj->date_read);
774 $this->date_last_msg_sent = $this->db->jdate($obj->date_last_msg_sent);
775 $this->date_close = $this->db->jdate($obj->date_close);
776 $this->tms = $this->db->jdate($obj->tms);
777 $this->date_modification = $this->db->jdate($obj->tms);
778
779 $this->fetch_optionals();
780
781 $this->db->free($resql);
782 return 1;
783 } else {
784 return 0;
785 }
786 } else {
787 $this->error = "Error ".$this->db->lasterror();
788 dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
789 return -1;
790 }
791 }
792
805 public function fetchAll($user, $sortorder = 'ASC', $sortfield = 't.datec', $limit = 0, $offset = 0, $arch = 0, $filter = '')
806 {
807 global $langs, $extrafields;
808
809 // fetch optionals attributes and labels
810 $extrafields->fetch_name_optionals_label($this->table_element);
811
812 $sql = "SELECT";
813 $sql .= " t.rowid,";
814 $sql .= " t.ref,";
815 $sql .= " t.track_id,";
816 $sql .= " t.fk_soc,";
817 $sql .= " t.fk_project,";
818 $sql .= " t.fk_contract,";
819 $sql .= " t.origin_email,";
820 $sql .= " t.origin_replyto,";
821 $sql .= " t.origin_references,";
822 $sql .= " t.fk_user_create, uc.lastname as user_create_lastname, uc.firstname as user_create_firstname,";
823 $sql .= " t.fk_user_assign, ua.lastname as user_assign_lastname, ua.firstname as user_assign_firstname,";
824 $sql .= " t.subject,";
825 $sql .= " t.message,";
826 $sql .= " t.note_private,";
827 $sql .= " t.note_public,";
828 $sql .= " t.fk_statut as status,";
829 $sql .= " t.resolution,";
830 $sql .= " t.progress,";
831 $sql .= " t.timing,";
832 $sql .= " t.type_code,";
833 $sql .= " t.category_code,";
834 $sql .= " t.severity_code,";
835 $sql .= " t.datec,";
836 $sql .= " t.date_read,";
837 $sql .= " t.date_last_msg_sent,";
838 $sql .= " t.date_close,";
839 $sql .= " t.tms,";
840 $sql .= " type.label as type_label, category.label as category_label, severity.label as severity_label";
841 // Add fields for extrafields
842 if ($extrafields->attributes[$this->table_element]['count'] > 0) {
843 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
844 $sql .= ($extrafields->attributes[$this->table_element]['type'][$key] != 'separate' ? ",ef.".$key." as options_".$key : '');
845 }
846 }
847 $sql .= " FROM ".MAIN_DB_PREFIX."ticket as t";
848 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_type as type ON type.code = t.type_code";
849 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_category as category ON category.code = t.category_code";
850 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_severity as severity ON severity.code = t.severity_code";
851 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = t.fk_soc";
852 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as uc ON uc.rowid = t.fk_user_create";
853 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as ua ON ua.rowid = t.fk_user_assign";
854 if ($extrafields->attributes[$this->table_element]['count'] > 0) {
855 if (is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label'])) {
856 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."ticket_extrafields as ef on (t.rowid = ef.fk_object)";
857 }
858 }
859 $sql .= " WHERE t.entity IN (".getEntity('ticket').")";
860
861 // Manage filter
862 if (is_array($filter)) {
863 foreach ($filter as $key => $value) {
864 if (strpos($key, 'date')) { // To allow $filter['YEAR(s.dated)']=>$year
865 $sql .= " AND ".$this->db->sanitize($key)." = '".$this->db->escape((string) $value)."'";
866 } elseif (($key == 't.fk_user_assign') || ($key == 't.type_code') || ($key == 't.category_code') || ($key == 't.severity_code') || ($key == 't.fk_soc')) {
867 $sql .= " AND ".$this->db->sanitize($key)." = '".$this->db->escape((string) $value)."'";
868 } elseif ($key == 't.fk_statut') {
869 if (is_array($value) && count($value) > 0) {
870 $sql .= " AND ".$this->db->sanitize($key)." IN (".$this->db->sanitize(implode(',', $value)).")";
871 } else {
872 $sql .= " AND ".$this->db->sanitize($key).' = '.((int) $value);
873 }
874 } elseif ($key == 't.fk_contract') {
875 $sql .= " AND ".$this->db->sanitize($key).' = '.((int) $value);
876 } else {
877 $sql .= " AND ".$this->db->sanitize($key)." LIKE '%".$this->db->escape($this->db->escapeforlike((string) $value))."%'";
878 }
879 }
880
881 $filter = '';
882 }
883
884 // Manage filter
885 $errormessage = '';
886 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
887 if ($errormessage) {
888 $this->errors[] = $errormessage;
889 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
890 return -1;
891 }
892
893 // Case of external user
894 $socid = $user->socid ?: 0;
895 // If the internal user must only see his customers, force searching by him
896 $search_sale = 0;
897 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
898 $search_sale = $user->id;
899 }
900 // Search on sale representative
901 if ($search_sale && $search_sale != '-1') {
902 if ($search_sale == -2) {
903 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
904 } elseif ($search_sale > 0) {
905 $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).")";
906 }
907 }
908 // Search on socid
909 if ($socid) {
910 $sql .= " AND t.fk_soc = ".((int) $socid);
911 }
912
913 $sql .= $this->db->order($sortfield, $sortorder);
914 if (!empty($limit)) {
915 $sql .= $this->db->plimit($limit + 1, $offset);
916 }
917
918 dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG);
919 $resql = $this->db->query($sql);
920
921 if ($resql) {
922 $this->lines = array();
923
924 $num = $this->db->num_rows($resql);
925 $i = 0;
926
927 if ($num) {
928 while ($i < $num) {
929 $obj = $this->db->fetch_object($resql);
930
931 $line = new self($this->db);
932
933 $line->id = $obj->rowid;
934 //$line->rowid = $obj->rowid;
935 $line->ref = $obj->ref;
936 $line->track_id = $obj->track_id;
937 $line->fk_soc = $obj->fk_soc;
938 $line->fk_project = $obj->fk_project;
939 $line->fk_contract = $obj->fk_contract;
940 $line->origin_email = $obj->origin_email;
941 $line->origin_replyto = $obj->origin_replyto;
942 $line->origin_references = $obj->origin_references;
943
944 $line->fk_user_create = $obj->fk_user_create;
945 $line->fk_user_assign = $obj->fk_user_assign;
946
947 $line->subject = $obj->subject;
948 $line->message = $obj->message;
949 $line->note_private = $obj->note_private;
950 $line->note_public = $obj->note_public;
951 $line->fk_statut = $obj->status;
952 $line->status = $obj->status;
953 $line->resolution = $obj->resolution;
954 $line->progress = $obj->progress;
955 $line->timing = $obj->timing;
956
957 $label_type = ($langs->trans("TicketTypeShort".$obj->type_code) != "TicketTypeShort".$obj->type_code ? $langs->trans("TicketTypeShort".$obj->type_code) : ($obj->type_label != '-' ? $obj->type_label : ''));
958 $line->type_label = $label_type;
959
960 $this->category_code = $obj->category_code;
961 $label_category = ($langs->trans("TicketCategoryShort".$obj->category_code) != "TicketCategoryShort".$obj->category_code ? $langs->trans("TicketCategoryShort".$obj->category_code) : ($obj->category_label != '-' ? $obj->category_label : ''));
962 $line->category_label = $label_category;
963
964 $this->severity_code = $obj->severity_code;
965 $label_severity = ($langs->trans("TicketSeverityShort".$obj->severity_code) != "TicketSeverityShort".$obj->severity_code ? $langs->trans("TicketSeverityShort".$obj->severity_code) : ($obj->severity_label != '-' ? $obj->severity_label : ''));
966 $line->severity_label = $label_severity;
967
968 $line->datec = $this->db->jdate($obj->datec);
969 $line->date_read = $this->db->jdate($obj->date_read);
970 $line->date_last_msg_sent = $this->db->jdate($obj->date_last_msg_sent);
971 $line->date_close = $this->db->jdate($obj->date_close);
972
973 // Extra fields
974 if ($extrafields->attributes[$this->table_element]['count'] > 0) {
975 if (is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label'])) {
976 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
977 $tmpkey = 'options_'.$key;
978 $line->{$tmpkey} = $obj->$tmpkey;
979 }
980 }
981 }
982 $this->lines[$i] = $line;
983 $i++;
984 }
985 }
986 $this->db->free($resql);
987 return $num;
988 } else {
989 $this->error = "Error ".$this->db->lasterror();
990 dol_syslog(get_class($this)."::fetchAll ".$this->error, LOG_ERR);
991 return -1;
992 }
993 }
994
1002 public function update($user, $notrigger = 0)
1003 {
1004 $error = 0;
1005
1006 // $this->oldcopy should have been set by the caller of update
1007 //if (empty($this->oldcopy)) {
1008 // dol_syslog("this->oldcopy should have been set by the caller of update (here properties were already modified)", LOG_WARNING);
1009 // $this->oldcopy = dol_clone($this, 2);
1010 //}
1011
1012 // Clean parameters
1013 if (isset($this->ref)) {
1014 $this->ref = trim($this->ref);
1015 }
1016
1017 if (isset($this->track_id)) {
1018 $this->track_id = trim($this->track_id);
1019 }
1020
1021 if (isset($this->fk_soc)) {
1022 $this->fk_soc = (int) $this->fk_soc;
1023 }
1024
1025 if (isset($this->fk_project)) {
1026 $this->fk_project = (int) $this->fk_project;
1027 }
1028
1029 if (isset($this->fk_contract)) {
1030 $this->fk_contract = (int) $this->fk_contract;
1031 }
1032
1033 if (isset($this->origin_email)) {
1034 $this->origin_email = trim($this->origin_email);
1035 }
1036
1037 if (isset($this->fk_user_create)) {
1038 $this->fk_user_create = (int) $this->fk_user_create;
1039 }
1040
1041 if (isset($this->fk_user_assign)) {
1042 $this->fk_user_assign = (int) $this->fk_user_assign;
1043 }
1044
1045 if (isset($this->subject)) {
1046 $this->subject = trim($this->subject);
1047 }
1048
1049 if (isset($this->message)) {
1050 $this->message = trim($this->message);
1051 if (dol_strlen($this->message) > 65000) {
1052 global $langs;
1053 $langs->loadLangs(array('errors', 'ticket'));
1054 $this->errors[] = $langs->trans('ErrorFieldTooLong', $langs->transnoentitiesnoconv('InitialMessage'));
1055 dol_syslog(get_class($this).'::update error -1 message too long', LOG_ERR);
1056 return -1;
1057 }
1058 }
1059
1060 if (isset($this->status)) {
1061 $this->status = (int) $this->status;
1062 }
1063
1064 if (isset($this->resolution)) {
1065 $this->resolution = (int) $this->resolution;
1066 }
1067
1068 if (isset($this->progress)) {
1069 $this->progress = (int) $this->progress;
1070 }
1071
1072 if (isset($this->timing)) {
1073 $this->timing = trim($this->timing);
1074 }
1075
1076 if (isset($this->type_code)) {
1077 $this->type_code = trim($this->type_code);
1078 }
1079
1080 if (isset($this->category_code)) {
1081 $this->category_code = trim($this->category_code);
1082 }
1083
1084 if (isset($this->severity_code)) {
1085 $this->severity_code = trim($this->severity_code);
1086 }
1087 if (isset($this->model_pdf)) {
1088 $this->model_pdf = trim($this->model_pdf);
1089 }
1090 // Check parameters
1091 // Put here code to add a control on parameters values
1092 // Update request
1093 $sql = "UPDATE ".MAIN_DB_PREFIX."ticket SET";
1094 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "").",";
1095 $sql .= " track_id=".(isset($this->track_id) ? "'".$this->db->escape($this->track_id)."'" : "null").",";
1096 $sql .= " fk_soc=".(isset($this->fk_soc) ? (int) $this->fk_soc : "null").",";
1097 $sql .= " fk_project=".(isset($this->fk_project) ? (int) $this->fk_project : "null").",";
1098 $sql .= " fk_contract=".(isset($this->fk_contract) ? (int) $this->fk_contract : "null").",";
1099 $sql .= " origin_email=".(isset($this->origin_email) ? "'".$this->db->escape($this->origin_email)."'" : "null").",";
1100 $sql .= " origin_replyto=".(isset($this->origin_replyto) ? "'".$this->db->escape($this->origin_replyto)."'" : "null").",";
1101 $sql .= " origin_references=".(isset($this->origin_references) ? "'".$this->db->escape($this->origin_references)."'" : "null").",";
1102 $sql .= " fk_user_create=".(isset($this->fk_user_create) ? (int) $this->fk_user_create : "null").",";
1103 $sql .= " fk_user_assign=".(isset($this->fk_user_assign) ? (int) $this->fk_user_assign : "null").",";
1104 $sql .= " subject=".(isset($this->subject) ? "'".$this->db->escape($this->subject)."'" : "null").",";
1105 $sql .= " message=".(isset($this->message) ? "'".$this->db->escape($this->message)."'" : "null").",";
1106 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1107 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1108 $sql .= " fk_statut=".(isset($this->status) ? (int) $this->status : "0").",";
1109 $sql .= " resolution=".(isset($this->resolution) ? (int) $this->resolution : "null").",";
1110 $sql .= " progress=".(isset($this->progress) ? "'".$this->db->escape((string) $this->progress)."'" : "null").",";
1111 $sql .= " timing=".(isset($this->timing) ? "'".$this->db->escape($this->timing)."'" : "null").",";
1112 $sql .= " type_code=".(isset($this->type_code) ? "'".$this->db->escape($this->type_code)."'" : "null").",";
1113 $sql .= " category_code=".(isset($this->category_code) ? "'".$this->db->escape($this->category_code)."'" : "null").",";
1114 $sql .= " severity_code=".(isset($this->severity_code) ? "'".$this->db->escape($this->severity_code)."'" : "null").",";
1115 $sql .= " datec=".(isDolTms($this->datec) ? "'".$this->db->idate($this->datec)."'" : 'null').",";
1116 $sql .= " date_read=".(dol_strlen((string) $this->date_read) != 0 ? "'".$this->db->idate($this->date_read)."'" : 'null').",";
1117 $sql .= " date_last_msg_sent=".(dol_strlen((string) $this->date_last_msg_sent) != 0 ? "'".$this->db->idate($this->date_last_msg_sent)."'" : 'null').",";
1118 $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
1119 $sql .= " date_close=".(dol_strlen((string) $this->date_close) != 0 ? "'".$this->db->idate($this->date_close)."'" : 'null');
1120 $sql .= " WHERE rowid=".((int) $this->id);
1121
1122 $this->db->begin();
1123
1124 $resql = $this->db->query($sql);
1125 if (!$resql) {
1126 $error++;
1127 $this->errors[] = "Error ".$this->db->lasterror();
1128 }
1129
1130 if (!$error) {
1131 // Update extrafields
1132 $result = $this->insertExtraFields();
1133 if ($result < 0) {
1134 $error++;
1135 }
1136 }
1137
1138 if (!$error && !$notrigger) {
1139 // Call trigger
1140 $result = $this->call_trigger('TICKET_MODIFY', $user);
1141 if ($result < 0) {
1142 $error++;
1143 }
1144 // End call triggers
1145 }
1146
1147 // Commit or rollback
1148 if ($error) {
1149 foreach ($this->errors as $errmsg) {
1150 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1151 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1152 }
1153 $this->db->rollback();
1154 return -1 * $error;
1155 } else {
1156 $this->db->commit();
1157 return 1;
1158 }
1159 }
1160
1168 public function delete($user, $notrigger = 0)
1169 {
1170 $error = 0;
1171
1172 $this->db->begin();
1173
1174 if (!$notrigger) {
1175 // Call trigger
1176 $result = $this->call_trigger('TICKET_DELETE', $user);
1177 if ($result < 0) {
1178 $error++;
1179 }
1180 // End call triggers
1181 }
1182
1183 if (!$error) {
1184 // Delete linked contacts
1185 $res = $this->delete_linked_contact();
1186 if ($res < 0) {
1187 dol_syslog(get_class($this)."::delete error", LOG_ERR);
1188 $error++;
1189 }
1190 }
1191
1192 if (!$error) {
1193 // Delete linked object
1194 $res = $this->deleteObjectLinked();
1195 if ($res < 0) {
1196 $error++;
1197 }
1198 }
1199
1200 // Removed extrafields
1201 if (!$error) {
1202 $result = $this->deleteExtraFields();
1203 if ($result < 0) {
1204 $error++;
1205 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1206 }
1207 }
1208
1209 // Delete all child tables
1210
1211 if (!$error) {
1212 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_ticket";
1213 $sql .= " WHERE fk_ticket = ".(int) $this->id;
1214
1215 $result = $this->db->query($sql);
1216 if (!$result) {
1217 $error++;
1218 $this->errors[] = $this->db->lasterror();
1219 }
1220 }
1221
1222 if (!$error) {
1223 $sql = "DELETE FROM ".MAIN_DB_PREFIX."ticket";
1224 $sql .= " WHERE rowid=".((int) $this->id);
1225
1226 dol_syslog(get_class($this)."::delete sql=".$sql);
1227 $resql = $this->db->query($sql);
1228 if (!$resql) {
1229 $error++;
1230 $this->errors[] = "Error ".$this->db->lasterror();
1231 } else {
1232 // we delete file with dol_delete_dir_recursive
1233 $this->deleteEcmFiles(1);
1234
1235 $dir = DOL_DATA_ROOT.'/'.$this->element.'/'.$this->ref;
1236 // For remove dir
1237 if (dol_is_dir($dir)) {
1238 if (!dol_delete_dir_recursive($dir)) {
1239 $this->errors[] = $this->error;
1240 }
1241 }
1242 }
1243 }
1244
1245 // Commit or rollback
1246 if ($error) {
1247 foreach ($this->errors as $errmsg) {
1248 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
1249 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1250 }
1251 $this->db->rollback();
1252 return -1 * $error;
1253 } else {
1254 $this->db->commit();
1255 return 1;
1256 }
1257 }
1258
1266 public function createFromClone(User $user, $fromid)
1267 {
1268 $error = 0;
1269
1270 $object = new Ticket($this->db);
1271
1272 $this->db->begin();
1273
1274 // Load source object
1275 $object->fetch($fromid);
1276
1277 // Clear fields
1278 $object->id = 0;
1279 $object->statut = 0;
1280 $object->status = 0;
1281 $object->ref = $object->getDefaultRef();
1282 $object->track_id = generate_random_id(16);
1283 $object->progress = 0;
1284 // Reset lifecycle timestamps so the clone starts fresh: datec is filled by
1285 // create() with dol_now() when empty, date_read and date_close stay null
1286 // because the new ticket has not been read or closed yet (see issue #38559).
1287 // Reset lifecycle timestamps and resolution so the clone starts fresh.
1288 // datec stays at 0 so Ticket::create()'s `if (empty($this->datec))` guard
1289 // fills it with dol_now(). date_read / date_close / resolution are unset
1290 // so the SQL writers' `!isset` checks emit NULL. We use these forms
1291 // rather than `= null` so phpstan stays happy with the int-typed
1292 // property declarations.
1293 $object->datec = 0;
1294 unset($object->date_read);
1295 unset($object->date_close);
1296 unset($object->resolution);
1297
1298 // Create clone
1299 $object->context['createfromclone'] = 'createfromclone';
1300 $result = $object->create($user);
1301
1302 // Other options
1303 if ($result < 0) {
1304 $this->error = $object->error;
1305 $error++;
1306 }
1307
1308 unset($object->context['createfromclone']);
1309
1310 // End
1311 if (!$error) {
1312 $this->db->commit();
1313 return $object->id;
1314 } else {
1315 $this->db->rollback();
1316 return -1;
1317 }
1318 }
1319
1326 public function initAsSpecimen()
1327 {
1328 $this->id = 0;
1329 $this->entity = 1;
1330 $this->ref = 'TI0501-001';
1331 $this->track_id = 'XXXXaaaa';
1332 $this->origin_email = 'email@email.com';
1333 $this->fk_project = 1;
1334 $this->fk_user_create = 1;
1335 $this->fk_user_assign = 1;
1336 $this->subject = 'Subject of ticket';
1337 $this->message = 'Message of ticket';
1338 $this->status = 0;
1339 $this->resolution = 1;
1340 $this->progress = 10;
1341 // $this->timing = '30';
1342 $this->type_code = 'TYPECODE';
1343 $this->category_code = 'CATEGORYCODE';
1344 $this->severity_code = 'SEVERITYCODE';
1345 $this->datec = dol_now();
1346 $this->date_read = dol_now();
1347 $this->date_last_msg_sent = dol_now();
1348 $this->date_close = dol_now();
1349 $this->tms = dol_now();
1350
1351 return 1;
1352 }
1353
1360 public function printSelectStatus($selected = "")
1361 {
1362 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 = '');
1363 }
1364
1365
1371 public function loadCacheTypesTickets()
1372 {
1373 global $langs;
1374
1375 if (!empty($this->cache_types_tickets) && count($this->cache_types_tickets)) {
1376 return 0;
1377 }
1378 // Cache deja charge
1379
1380 $sql = "SELECT rowid, code, label, use_default, pos, description";
1381 $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_type";
1382 $sql .= " WHERE entity IN (".getEntity('c_ticket_type').")";
1383 $sql .= " AND active > 0";
1384 $sql .= " ORDER BY pos";
1385 dol_syslog(get_class($this)."::load_cache_type_tickets", LOG_DEBUG);
1386 $resql = $this->db->query($sql);
1387 if ($resql) {
1388 $num = $this->db->num_rows($resql);
1389 $i = 0;
1390 while ($i < $num) {
1391 $obj = $this->db->fetch_object($resql);
1392 $label = ($langs->trans("TicketTypeShort".$obj->code) != "TicketTypeShort".$obj->code ? $langs->trans("TicketTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
1393 $this->cache_types_tickets[$obj->rowid]['code'] = $obj->code;
1394 $this->cache_types_tickets[$obj->rowid]['label'] = $label;
1395 $this->cache_types_tickets[$obj->rowid]['use_default'] = $obj->use_default;
1396 $this->cache_types_tickets[$obj->rowid]['pos'] = $obj->pos;
1397 $i++;
1398 }
1399 return $num;
1400 } else {
1401 dol_print_error($this->db);
1402 return -1;
1403 }
1404 }
1405
1412 public function loadCacheCategoriesTickets($publicgroup = -1)
1413 {
1414 global $conf, $langs;
1415
1416 if ($publicgroup == -1 && !empty($conf->cache['category_tickets']) && count($conf->cache['category_tickets'])) {
1417 // Cache already loaded
1418 return 0;
1419 }
1420
1421 $sql = "SELECT rowid, code, label, use_default, pos, description, public, active, force_severity, fk_parent";
1422 $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_category";
1423 $sql .= " WHERE entity IN (".getEntity('c_ticket_category').")";
1424 $sql .= " AND active > 0";
1425 if ($publicgroup > -1) {
1426 $sql .= " AND public = ".((int) $publicgroup);
1427 }
1428 $sql .= " ORDER BY pos";
1429
1430 dol_syslog(get_class($this)."::load_cache_categories_tickets", LOG_DEBUG);
1431
1432 $resql = $this->db->query($sql);
1433 if ($resql) {
1434 $num = $this->db->num_rows($resql);
1435 $i = 0;
1436 while ($i < $num) {
1437 $obj = $this->db->fetch_object($resql);
1438 $conf->cache['category_tickets'][$obj->rowid]['code'] = $obj->code;
1439 $conf->cache['category_tickets'][$obj->rowid]['use_default'] = $obj->use_default;
1440 $conf->cache['category_tickets'][$obj->rowid]['pos'] = $obj->pos;
1441 $conf->cache['category_tickets'][$obj->rowid]['public'] = $obj->public;
1442 $conf->cache['category_tickets'][$obj->rowid]['active'] = $obj->active;
1443 $conf->cache['category_tickets'][$obj->rowid]['force_severity'] = $obj->force_severity;
1444 $conf->cache['category_tickets'][$obj->rowid]['fk_parent'] = $obj->fk_parent;
1445
1446 // If translation exists, we use it to store already translated string.
1447 // Warning: You should not use this and recompute the translated string into caller code to get the value into expected language
1448 $label = ($langs->trans("TicketCategoryShort".$obj->code) != "TicketCategoryShort".$obj->code ? $langs->trans("TicketCategoryShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
1449 $conf->cache['category_tickets'][$obj->rowid]['label'] = $label;
1450
1451 $i++;
1452 }
1453 return $num;
1454 } else {
1455 dol_print_error($this->db);
1456 return -1;
1457 }
1458 }
1459
1466 {
1467 global $conf, $langs;
1468
1469 if (!empty($conf->cache['severity_tickets']) && count($conf->cache['severity_tickets'])) {
1470 // Cache already loaded
1471 return 0;
1472 }
1473
1474 $sql = "SELECT rowid, code, label, use_default, pos, description";
1475 $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_severity";
1476 $sql .= " WHERE entity IN (".getEntity('c_ticket_severity').")";
1477 $sql .= " AND active > 0";
1478 $sql .= " ORDER BY pos";
1479 dol_syslog(get_class($this)."::loadCacheSeveritiesTickets", LOG_DEBUG);
1480 $resql = $this->db->query($sql);
1481 if ($resql) {
1482 $num = $this->db->num_rows($resql);
1483 $i = 0;
1484 while ($i < $num) {
1485 $obj = $this->db->fetch_object($resql);
1486
1487 $conf->cache['severity_tickets'][$obj->rowid]['code'] = $obj->code;
1488 $label = ($langs->trans("TicketSeverityShort".$obj->code) != "TicketSeverityShort".$obj->code ? $langs->trans("TicketSeverityShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
1489 $conf->cache['severity_tickets'][$obj->rowid]['label'] = $label;
1490 $conf->cache['severity_tickets'][$obj->rowid]['use_default'] = $obj->use_default;
1491 $conf->cache['severity_tickets'][$obj->rowid]['pos'] = $obj->pos;
1492 $i++;
1493 }
1494 return $num;
1495 } else {
1496 dol_print_error($this->db);
1497 return -1;
1498 }
1499 }
1500
1501
1508 public function getLibStatut($mode = 0)
1509 {
1510 return $this->LibStatut($this->status, $mode, 0, $this->progress);
1511 }
1512
1513
1514 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1524 public function LibStatut($status, $mode = 0, $notooltip = 0, $progress = 0)
1525 {
1526 // phpcs:enable
1527 global $langs, $hookmanager;
1528
1529 $labelStatus = (isset($status) && !empty($this->labelStatus[$status])) ? $this->labelStatus[$status] : '';
1530 $labelStatusShort = (isset($status) && !empty($this->labelStatusShort[$status])) ? $this->labelStatusShort[$status] : '';
1531
1532 switch ($status) {
1533 case self::STATUS_NOT_READ: // Not read
1534 $statusType = 'status0';
1535 break;
1536 case self::STATUS_READ: // Read
1537 $statusType = 'status1';
1538 break;
1539 case self::STATUS_ASSIGNED: // Assigned
1540 $statusType = 'status2';
1541 break;
1542 case self::STATUS_IN_PROGRESS: // In progress
1543 $statusType = 'status4';
1544 break;
1545 case self::STATUS_WAITING: // Waiting/pending/suspended
1546 $statusType = 'status7';
1547 break;
1548 case self::STATUS_NEED_MORE_INFO: // Waiting more information from the requester
1549 $statusType = 'status3';
1550 break;
1551 case self::STATUS_CANCELED: // Canceled
1552 $statusType = 'status9';
1553 break;
1554 case self::STATUS_CLOSED: // Closed
1555 $statusType = 'status6';
1556 break;
1557 default:
1558 $labelStatus = 'Unknown';
1559 $labelStatusShort = 'Unknown';
1560 $statusType = 'status0';
1561 $mode = 0;
1562 }
1563
1564 $parameters = array(
1565 'status' => $status,
1566 'mode' => $mode,
1567 );
1568
1569 // Note that $action and $object may have been modified by hook
1570 $reshook = $hookmanager->executeHooks('LibStatut', $parameters, $this);
1571
1572 if ($reshook > 0) {
1573 return $hookmanager->resPrint;
1574 }
1575
1576 $params = array();
1577 if ($notooltip) {
1578 $params = array('tooltip' => 'no');
1579 }
1580
1581 $labelStatus = $langs->transnoentitiesnoconv($labelStatus);
1582 $labelStatusShort = $langs->transnoentitiesnoconv($labelStatusShort);
1583
1584 if ($status == self::STATUS_IN_PROGRESS && $progress > 0) {
1585 $labelStatus .= ' ('.round($progress).'%)';
1586 $labelStatusShort .= ' ('.round($progress).'%)';
1587 }
1588
1589 return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode, '', $params);
1590 }
1591
1598 public function getTooltipContentArray($params)
1599 {
1600 global $langs;
1601
1602 $langs->load('ticket');
1603 $nofetch = !empty($params['nofetch']);
1604
1605 $datas = array();
1606 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Ticket").'</u>';
1607 $datas['picto'] .= ' '.$this->getLibStatut(4);
1608 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1609 $datas['track_id'] = '<br><b>'.$langs->trans('TicketTrackId').':</b> '.$this->track_id;
1610 $datas['subject'] = '<br><b>'.$langs->trans('Subject').':</b> '.$this->subject;
1611 if ($this->date_creation) {
1612 $datas['date_creation'] = '<br><b>'.$langs->trans('DateCreation').':</b> '.dol_print_date($this->date_creation, 'dayhour');
1613 }
1614 if ($this->date_modification) {
1615 $datas['date_modification'] = '<br><b>'.$langs->trans('DateModification').':</b> '.dol_print_date($this->date_modification, 'dayhour');
1616 }
1617 // show categories for this record only in ajax to not overload lists
1618 if (isModEnabled('category') && !$nofetch) {
1619 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
1620 $form = new Form($this->db);
1621 $datas['categories'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_TICKET, 1);
1622 }
1623
1624 return $datas;
1625 }
1626
1637 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
1638 {
1639 global $action, $conf, $hookmanager, $langs;
1640
1641 if (!empty($conf->dol_no_mouse_hover)) {
1642 $notooltip = 1; // Force disable tooltips
1643 }
1644
1645 $result = '';
1646
1647 $params = [
1648 'id' => $this->id,
1649 'objecttype' => $this->element,
1650 'option' => $option,
1651 'nofetch' => 1,
1652 ];
1653 $classfortooltip = 'classfortooltip';
1654 $dataparams = '';
1655 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1656 $classfortooltip = 'classforajaxtooltip';
1657 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1658 $label = '';
1659 } else {
1660 $label = implode($this->getTooltipContentArray($params));
1661 }
1662
1663 $url = DOL_URL_ROOT.'/ticket/card.php?id='.$this->id;
1664
1665 if ($option != 'nolink') {
1666 // Add param to save lastsearch_values or not
1667 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1668 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1669 $add_save_lastsearch_values = 1;
1670 }
1671 if ($add_save_lastsearch_values) {
1672 $url .= '&save_lastsearch_values=1';
1673 }
1674 }
1675
1676 $linkclose = '';
1677 if (empty($notooltip)) {
1678 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1679 $label = $langs->trans("ShowTicket");
1680 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1681 }
1682 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
1683 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
1684 } else {
1685 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1686 }
1687
1688 $linkstart = '<a href="'.$url.'"';
1689 $linkstart .= $linkclose.'>';
1690 $linkend = '</a>';
1691
1692 $result .= $linkstart;
1693 if ($withpicto) {
1694 $result .= img_object(($notooltip ? '' : $label), ($this->picto ?: 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
1695 }
1696 if ($withpicto != 2) {
1697 $result .= $this->ref;
1698 }
1699 $result .= $linkend;
1700 //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
1701
1702 $hookmanager->initHooks(array('ticketdao'));
1703 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1704 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1705 if ($reshook > 0) {
1706 $result = $hookmanager->resPrint;
1707 } else {
1708 $result .= $hookmanager->resPrint;
1709 }
1710
1711 return $result;
1712 }
1713
1714
1722 public function markAsRead($user, $notrigger = 0)
1723 {
1724 global $langs;
1725
1726 $error = 0;
1727
1728 if ($this->status != self::STATUS_CANCELED) { // no closed
1729 $this->oldcopy = dol_clone($this, 2);
1730
1731 $this->db->begin();
1732
1733 $this->status = Ticket::STATUS_READ;
1734
1735 $sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
1736 $sql .= " SET fk_statut = ".((int) $this->status) .", date_read = '".$this->db->idate(dol_now())."'";
1737 $sql .= " WHERE rowid = ".((int) $this->id);
1738
1739 dol_syslog(get_class($this)."::markAsRead");
1740 $resql = $this->db->query($sql);
1741 if ($resql) {
1742 $this->context['actionmsg'] = $langs->trans('TicketLogMesgReadBy', $this->ref, $user->getFullName($langs));
1743 $this->context['actionmsg2'] = $langs->trans('TicketLogMesgReadBy', $this->ref, $user->getFullName($langs));
1744
1745 if (!$notrigger) {
1746 // Call trigger
1747 $result = $this->call_trigger('TICKET_MODIFY', $user);
1748 if ($result < 0) {
1749 $error++;
1750 }
1751 // End call triggers
1752 }
1753
1754 if (!$error) {
1755 $this->db->commit();
1756 return 1;
1757 } else {
1758 $this->status = $this->oldcopy->status;
1759
1760 $this->db->rollback();
1761
1762 $this->error = implode(',', $this->errors);
1763
1764 dol_syslog(get_class($this)."::markAsRead ".$this->error, LOG_ERR);
1765 return -1;
1766 }
1767 } else {
1768 $this->status = $this->oldcopy->status;
1769
1770 $this->db->rollback();
1771 $this->error = $this->db->lasterror();
1772 dol_syslog(get_class($this)."::markAsRead ".$this->error, LOG_ERR);
1773 return -1;
1774 }
1775 }
1776
1777 return 0;
1778 }
1779
1788 public function assignUser($user, $id_assign_user, $notrigger = 0)
1789 {
1790 $error = 0;
1791
1792 $this->oldcopy = dol_clone($this, 2);
1793
1794 $this->db->begin();
1795
1796 $sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
1797 if ($id_assign_user > 0) {
1798 $sql .= " SET fk_user_assign=".((int) $id_assign_user).", fk_statut = ".Ticket::STATUS_ASSIGNED;
1799 } else {
1800 $sql .= " SET fk_user_assign=null, fk_statut = ".Ticket::STATUS_READ;
1801 }
1802 $sql .= " WHERE rowid = ".((int) $this->id);
1803
1804 dol_syslog(get_class($this)."::assignUser sql=".$sql);
1805 $resql = $this->db->query($sql);
1806 if ($resql) {
1807 $this->fk_user_assign = $id_assign_user; // May be used by trigger
1808
1809 if (!$notrigger) {
1810 // Call trigger
1811 $result = $this->call_trigger('TICKET_ASSIGNED', $user);
1812 if ($result < 0) {
1813 $error++;
1814 }
1815 // End call triggers
1816 }
1817
1818 if (!$error) {
1819 $this->db->commit();
1820 return 1;
1821 } else {
1822 $this->db->rollback();
1823 $this->error = implode(',', $this->errors);
1824 dol_syslog(get_class($this)."::assignUser ".$this->error, LOG_ERR);
1825 return -1;
1826 }
1827 } else {
1828 $this->db->rollback();
1829 $this->error = $this->db->lasterror();
1830 dol_syslog(get_class($this)."::assignUser ".$this->error, LOG_ERR);
1831 return -1;
1832 }
1833 }
1834
1847 public function createTicketMessage($user, $notrigger = 0, $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array(), $send_email = false, $public_area = 0)
1848 {
1849 global $conf;
1850 $error = 0;
1851
1852 $now = dol_now();
1853
1854 // Clean parameters
1855 if (isset($this->track_id)) {
1856 $this->track_id = trim($this->track_id);
1857 }
1858
1859 if (isset($this->message)) {
1860 $this->message = trim($this->message);
1861 }
1862
1863 $this->db->begin();
1864
1865 // Insert entry into agenda with code 'TICKET_MSG'
1866 include_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
1867 $actioncomm = new ActionComm($this->db);
1868 $actioncomm->type_code = 'AC_OTH_AUTO'; // This is not an entry that must appears into manual calendar but only into CRM calendar
1869 $actioncomm->code = 'TICKET_MSG';
1870 if ($this->private) {
1871 $actioncomm->code = 'TICKET_MSG_PRIVATE';
1872 }
1873 if ($send_email) {
1874 $actioncomm->code .= '_SENTBYMAIL';
1875 }
1876 if ((empty($user->id) || $user->id == 0) && isset($_SESSION['email_customer'])) {
1877 $actioncomm->email_from = $_SESSION['email_customer'];
1878 }
1879 $actioncomm->socid = $this->socid;
1880 $actioncomm->label = $this->subject;
1881 $actioncomm->note_private = $this->message;
1882 $actioncomm->userassigned = array($user->id => array('id' => $user->id,'transparency' => 0));
1883 $actioncomm->userownerid = $user->id;
1884 $actioncomm->datep = $now;
1885 $actioncomm->percentage = -1; // percentage is not relevant for punctual events
1886 $actioncomm->elementtype = 'ticket';
1887 $actioncomm->fk_element = $this->id;
1888 $actioncomm->elementid = $this->id;
1889 $actioncomm->elementtype = 'ticket';
1890 $actioncomm->fk_project = $this->fk_project;
1891
1892 // Add first contact id found in database from submitter email entered into public interface
1893 // 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
1894 // email decided by the submiter allows anybody to get information on any contact (customer or supplier) in Dolibarr database.
1895 // He can even check if contact exists by trying any email if this feature is enabled.
1896 if ($public_area && !empty($this->origin_email) && getDolGlobalString('TICKET_ASSIGN_CONTACT_TO_MESSAGE')) {
1897 $contacts = $this->searchContactByEmail($this->origin_email);
1898 if (!empty($contacts)) {
1899 // Ensure that contact is active and select first active contact
1900 foreach ($contacts as $contact) {
1901 if ((int) $contact->status == 1) {
1902 $actioncomm->contact_id = $contact->id;
1903 break;
1904 }
1905 }
1906 }
1907 }
1908
1909 $attachedfiles = array();
1910 $attachedfiles['paths'] = $filename_list;
1911 $attachedfiles['names'] = $mimefilename_list;
1912 $attachedfiles['mimes'] = $mimetype_list;
1913 if (is_array($attachedfiles) && count($attachedfiles) > 0) {
1914 $actioncomm->attachedfiles = $attachedfiles;
1915 }
1916
1917 //if (!empty($mimefilename_list) && is_array($mimefilename_list)) {
1918 // $actioncomm->note_private = dol_concatdesc($actioncomm->note_private, "\n".$langs->transnoentities("AttachedFiles").': '.implode(';', $mimefilename_list));
1919 //}
1920 $actionid = $actioncomm->create($user);
1921 if ($actionid <= 0) {
1922 $error++;
1923 $this->error = $actioncomm->error;
1924 $this->errors = $actioncomm->errors;
1925 }
1926
1927 if ($actionid > 0) {
1928 if (is_array($attachedfiles) && array_key_exists('paths', $attachedfiles) && count($attachedfiles['paths']) > 0) {
1929 // If there is some files, we must now link them to the event, so we can show them per event.
1930 foreach ($attachedfiles['paths'] as $key => $filespath) {
1931 // Disabled the move into another directory, Files for a ticket should be stored into ticket directory. It generates too much troubles.
1932 $destdir = $conf->ticket->dir_output.'/'.$this->ref;
1933 //$destfile = $destdir.'/'.$attachedfiles['names'][$key];
1934 //if (dol_mkdir($destdir) >= 0) {
1935 //require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1936 //dol_move($filespath, $destfile); // Disabled, a file for a ticket should be stored into ticket directory. It generates big trouble.
1937 if (in_array($actioncomm->code, array('TICKET_MSG', 'TICKET_MSG_SENTBYMAIL', 'TICKET_MSG_PRIVATE'))) {
1938 $ecmfile = new EcmFiles($this->db);
1939 $destdir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $destdir);
1940 $destdir = preg_replace('/[\\/]$/', '', $destdir);
1941 $destdir = preg_replace('/^[\\/]/', '', $destdir);
1942
1943 $result = $ecmfile->fetch(0, '', $destdir.'/'.$attachedfiles['names'][$key]);
1944
1945 // We also store the ID of event.
1946 $ecmfile->agenda_id = $actionid;
1947
1948 if ($result > 0) {
1949 $result = $ecmfile->update($user);
1950 if ($result < 0) {
1951 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
1952 }
1953 }
1954 }
1955 //}
1956 }
1957 }
1958 }
1959
1960 // Commit or rollback
1961 if ($error) {
1962 $this->db->rollback();
1963 return -1 * $error;
1964 } else {
1965 $this->db->commit();
1966 return $actionid;
1967 }
1968 }
1969
1975 public function loadCacheMsgsTicket()
1976 {
1977 if (!empty($this->cache_msgs_ticket) && is_array($this->cache_msgs_ticket) && count($this->cache_msgs_ticket)) {
1978 return 0;
1979 }
1980
1981 // Cache already loaded
1982
1983 $sql = "SELECT id as rowid, fk_user_author, email_from, datec, datep, label, note as message, code";
1984 $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm";
1985 $sql .= " WHERE fk_element = ".(int) $this->id;
1986 $sql .= " AND elementtype = 'ticket'";
1987 $sql .= " ORDER BY datep DESC";
1988
1989 dol_syslog(get_class($this)."::load_cache_actions_ticket", LOG_DEBUG);
1990 $resql = $this->db->query($sql);
1991 if ($resql) {
1992 $num = $this->db->num_rows($resql);
1993 $i = 0;
1994 while ($i < $num) {
1995 $obj = $this->db->fetch_object($resql);
1996 $this->cache_msgs_ticket[$i]['id'] = $obj->rowid;
1997 $this->cache_msgs_ticket[$i]['fk_user_author'] = $obj->fk_user_author;
1998 if (in_array($obj->code, array('TICKET_MSG', 'AC_TICKET_CREATE')) && empty($obj->fk_user_author)) {
1999 $this->cache_msgs_ticket[$i]['fk_contact_author'] = $obj->email_from;
2000 }
2001 $this->cache_msgs_ticket[$i]['datec'] = $this->db->jdate($obj->datec);
2002 $this->cache_msgs_ticket[$i]['datep'] = $this->db->jdate($obj->datep);
2003 $this->cache_msgs_ticket[$i]['subject'] = $obj->label;
2004 $this->cache_msgs_ticket[$i]['message'] = $obj->message;
2005 $this->cache_msgs_ticket[$i]['private'] = (preg_match('/^TICKET_MSG_PRIVATE/', $obj->code) ? 1 : 0);
2006 $i++;
2007 }
2008 return $num;
2009 } else {
2010 $this->error = "Error ".$this->db->lasterror();
2011 dol_syslog(get_class($this)."::load_cache_actions_ticket ".$this->error, LOG_ERR);
2012 return -1;
2013 }
2014 }
2015
2023 public function close(User $user, $mode = 0)
2024 {
2025
2026 if ($this->status != Ticket::STATUS_CLOSED && $this->status != Ticket::STATUS_CANCELED) { // not closed
2027 $this->db->begin();
2028
2029 $this->oldcopy = dol_clone($this);
2030 $this->status = ($mode ? Ticket::STATUS_CANCELED : Ticket::STATUS_CLOSED);
2031
2032 $sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
2033 $sql .= " SET fk_statut = ".((int) $this->status).", progress=100, date_close='".$this->db->idate(dol_now())."'";
2034 $sql .= " WHERE rowid = ".((int) $this->id);
2035
2036 dol_syslog(get_class($this)."::close mode=".$mode);
2037 $resql = $this->db->query($sql);
2038 if ($resql) {
2039 $error = 0;
2040
2041 // Valid and close fichinter linked
2042 if (isModEnabled('intervention') && getDolGlobalString('WORKFLOW_TICKET_CLOSE_INTERVENTION')) {
2043 dol_syslog("We have closed the ticket, so we close all linked interventions");
2044 $this->fetchObjectLinked($this->id, $this->element, null, 'fichinter');
2045 if ($this->linkedObjectsIds) {
2046 foreach ($this->linkedObjectsIds['fichinter'] as $fichinter_id) {
2047 $fichinter = new Fichinter($this->db);
2048 $fichinter->fetch($fichinter_id);
2049 if ($fichinter->statut == 0) {
2050 $result = $fichinter->setValid($user);
2051 if (!$result) {
2052 $this->errors[] = $fichinter->error;
2053 $error++;
2054 }
2055 }
2056 if ($fichinter->statut < 3) {
2057 $result = $fichinter->setStatut(3);
2058 if (!$result) {
2059 $this->errors[] = $fichinter->error;
2060 $error++;
2061 }
2062 }
2063 }
2064 }
2065 }
2066
2067 // Call trigger
2068 $result = $this->call_trigger('TICKET_CLOSE', $user);
2069 if ($result < 0) {
2070 $error++;
2071 }
2072 // End call triggers
2073
2074 if (!$error) {
2075 $this->db->commit();
2076 return 1;
2077 } else {
2078 $this->db->rollback();
2079 $this->error = implode(',', $this->errors);
2080 dol_syslog(get_class($this)."::close ".$this->error, LOG_ERR);
2081 return -1;
2082 }
2083 } else {
2084 $this->db->rollback();
2085 $this->error = $this->db->lasterror();
2086 dol_syslog(get_class($this)."::close ".$this->error, LOG_ERR);
2087 return -1;
2088 }
2089 }
2090
2091 return 0;
2092 }
2093
2103 public function searchSocidByEmail($email, $type = 0, $filters = array(), $clause = 'AND')
2104 {
2105 $thirdparties = array();
2106 $exact = 0;
2107
2108 // Generation requete recherche
2109 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe";
2110 $sql .= " WHERE entity IN (".getEntity('ticket', 1).")";
2111 if (!empty($type)) {
2112 if ($type == 1 || $type == 2) {
2113 $sql .= " AND client = ".((int) $type);
2114 } elseif ($type == 3) {
2115 $sql .= " AND fournisseur = 1";
2116 }
2117 }
2118 if (!empty($email)) {
2119 if (empty($exact)) {
2120 $regs = array();
2121 if (preg_match('/^([\*])?[^*]+([\*])?$/', $email, $regs) && count($regs) > 1) {
2122 $email = str_replace('*', '%', $email);
2123 } else {
2124 $email = '%'.$email.'%';
2125 }
2126 }
2127 $sql .= " AND ";
2128 if (is_array($filters) && !empty($filters)) {
2129 $sql .= "(";
2130 }
2131
2132 $sql .= "email LIKE '".$this->db->escape($email)."'";
2133 }
2134 if (is_array($filters) && !empty($filters)) {
2135 foreach ($filters as $field => $value) {
2136 $sql .= " ".$clause." ".$this->db->sanitize($field)." LIKE '".$this->db->escape($value)."'";
2137 }
2138 if (!empty($email)) {
2139 $sql .= ")";
2140 }
2141 }
2142
2143 $res = $this->db->query($sql);
2144 if ($res) {
2145 while ($rec = $this->db->fetch_array($res)) {
2146 $soc = new Societe($this->db);
2147 $soc->fetch($rec['rowid']);
2148 $thirdparties[] = $soc;
2149 }
2150
2151 return $thirdparties;
2152 } else {
2153 $this->error = $this->db->error().' sql='.$sql;
2154 dol_syslog(get_class($this)."::searchSocidByEmail ".$this->error, LOG_ERR);
2155 return -1;
2156 }
2157 }
2158
2167 public function searchContactByEmail($email, $socid = 0, $case = '')
2168 {
2169 $contacts = array();
2170
2171 // Forge the search SQL
2172 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople";
2173 $sql .= " WHERE entity IN (".getEntity('contact').")";
2174 if (!empty($socid)) {
2175 $sql .= " AND fk_soc = ".((int) $socid);
2176 }
2177 if (!empty($email)) {
2178 $sql .= " AND ";
2179 if (!$case) {
2180 $sql .= "email = '".$this->db->escape($email)."'";
2181 } else {
2182 $sql .= "email LIKE BINARY '".$this->db->escape($this->db->escapeforlike($email))."'";
2183 }
2184 }
2185
2186 $res = $this->db->query($sql);
2187 if ($res) {
2188 while ($rec = $this->db->fetch_object($res)) {
2189 include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
2190 $contactstatic = new Contact($this->db);
2191 $contactstatic->fetch($rec->rowid);
2192 $contacts[] = $contactstatic;
2193 }
2194
2195 return $contacts;
2196 } else {
2197 $this->error = $this->db->error().' sql='.$sql;
2198 dol_syslog(get_class($this)."::searchContactByEmail ".$this->error, LOG_ERR);
2199 return -1;
2200 }
2201 }
2202
2209 public function setCustomer($id)
2210 {
2211 if ($this->id) {
2212 $sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
2213 $sql .= " SET fk_soc = ".($id > 0 ? (int) $id : "null");
2214 $sql .= " WHERE rowid = ".((int) $this->id);
2215 dol_syslog(get_class($this).'::setCustomer sql='.$sql);
2216 $resql = $this->db->query($sql);
2217 if ($resql) {
2218 return 1;
2219 } else {
2220 return -1;
2221 }
2222 } else {
2223 return -1;
2224 }
2225 }
2226
2233 public function setProgression($percent)
2234 {
2235 if ($this->id) {
2236 $sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
2237 $sql .= " SET progress = ".($percent > 0 ? (float) $percent : "null");
2238 $sql .= " WHERE rowid = ".((int) $this->id);
2239 dol_syslog(get_class($this).'::set_progression sql='.$sql);
2240 $resql = $this->db->query($sql);
2241 if ($resql) {
2242 return 1;
2243 } else {
2244 return -1;
2245 }
2246 } else {
2247 return -1;
2248 }
2249 }
2250
2257 public function setContract($contractid)
2258 {
2259 if ($this->id) {
2260 $sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
2261 $sql .= " SET fk_contract = ".($contractid > 0 ? (int) $contractid : "null");
2262 $sql .= " WHERE rowid = ".((int) $this->id);
2263 dol_syslog(get_class($this).'::setContract sql='.$sql);
2264 $resql = $this->db->query($sql);
2265 if ($resql) {
2266 return 1;
2267 } else {
2268 return -1;
2269 }
2270 } else {
2271 return -1;
2272 }
2273 }
2274
2275 /* gestion des contacts d'un ticket */
2276
2283 {
2284 return $this->getIdContact('internal', 'SUPPORTTEC');
2285 }
2286
2293 public function getInfosTicketInternalContact($status = -1)
2294 {
2295 return $this->listeContact(-1, 'internal', 0, '', $status);
2296 }
2297
2304 {
2305 return $this->getIdContact('external', 'SUPPORTCLI');
2306 }
2307
2314 public function getInfosTicketExternalContact($status = -1)
2315 {
2316 return $this->listeContact(-1, 'external', 0, '', $status);
2317 }
2318
2325 {
2326 return $this->getIdContact('internal', 'CONTRIBUTOR');
2327 }
2328
2335 {
2336 return $this->getIdContact('external', 'CONTRIBUTOR');
2337 }
2338
2344 public function getTicketAllContacts()
2345 {
2346 $array_contact = $this->getIdTicketInternalContact();
2347
2348 $array_contact = array_merge($array_contact, $this->getIdTicketCustomerContact());
2349
2350 $array_contact = array_merge($array_contact, $this->getIdTicketInternalInvolvedContact());
2351
2352 $array_contact = array_merge($array_contact, $this->getIdTicketCustomerInvolvedContact());
2353
2354 return $array_contact;
2355 }
2356
2363 {
2364 $array_contact = array();
2365
2366 $array_contact = array_merge($array_contact, $this->getIdTicketCustomerContact());
2367
2368 $array_contact = array_merge($array_contact, $this->getIdTicketCustomerInvolvedContact());
2369
2370 return $array_contact;
2371 }
2372
2373
2385 public function listeContact($statusoflink = -1, $source = 'external', $list = 0, $code = '', $status = -1)
2386 {
2387 global $langs;
2388
2389 $tab = array();
2390
2391 $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
2392 if ($source == 'internal') {
2393 $sql .= ", '-1' as socid, t.statut as statuscontact";
2394 }
2395
2396 if ($source == 'external' || $source == 'thirdparty') {
2397 $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
2398 }
2399
2400 $sql .= ", t.civility, t.lastname as lastname, t.firstname, t.email";
2401 if ($source == 'internal') {
2402 $sql .= ", t.office_phone as phone, t.user_mobile as phone_mobile";
2403 }
2404
2405 if ($source == 'external' || $source == 'thirdparty') {
2406 $sql .= ", t.phone as phone, t.phone_mobile as phone_mobile, t.phone_perso as phone_perso";
2407 }
2408
2409 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_contact_label";
2410 $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
2411 $sql .= ", ".MAIN_DB_PREFIX."element_contact ec";
2412 if ($source == 'internal') {
2413 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
2414 }
2415
2416 if ($source == 'external' || $source == 'thirdparty') {
2417 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
2418 }
2419
2420 $sql .= " WHERE ec.element_id = ".((int) $this->id);
2421 $sql .= " AND ec.fk_c_type_contact=tc.rowid";
2422 $sql .= " AND tc.element='".$this->db->escape($this->element)."'";
2423 if ($source == 'internal') {
2424 $sql .= " AND tc.source = 'internal'";
2425 if ($status >= 0) {
2426 $sql .= " AND t.statut = ".((int) $status);
2427 }
2428 }
2429
2430 if ($source == 'external' || $source == 'thirdparty') {
2431 $sql .= " AND tc.source = 'external'";
2432 if ($status >= 0) {
2433 $sql .= " AND t.statut = ".((int) $status);
2434 }
2435 }
2436
2437 if (!empty($code)) {
2438 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
2439 }
2440
2441 $sql .= " AND tc.active=1";
2442 if ($statusoflink >= 0) {
2443 $sql .= " AND ec.statut = ".((int) $statusoflink);
2444 }
2445
2446 $sql .= " ORDER BY t.lastname ASC";
2447
2448 $resql = $this->db->query($sql);
2449 if ($resql) {
2450 $num = $this->db->num_rows($resql);
2451 $i = 0;
2452 while ($i < $num) {
2453 $obj = $this->db->fetch_object($resql);
2454
2455 if (!$list) {
2456 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
2457 $labelType = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_contact_label);
2458 $tab[$i] = array(
2459 'source' => $obj->source,
2460 'socid' => (int) $obj->socid,
2461 'id' => (int) $obj->id,
2462 'nom' => $obj->lastname, // For backward compatibility
2463 'civility' => $obj->civility,
2464 'lastname' => $obj->lastname,
2465 'firstname' => $obj->firstname,
2466 'email' => $obj->email,
2467 'rowid' => (int) $obj->rowid,
2468 'code' => $obj->code,
2469 'libelle' => $labelType, // deprecated, replaced with labeltype
2470 'labeltype' => $labelType,
2471 'status' => $obj->statuslink,
2472 'statuscontact' => (int) $obj->statuscontact,
2473 'fk_c_type_contact' => (int) $obj->fk_c_type_contact,
2474 'phone' => $obj->phone,
2475 'phone_mobile' => $obj->phone_mobile);
2476 if ($source == 'external') {
2477 $tab[$i]['phone_perso'] = $obj->phone_perso;
2478 }
2479 } else {
2480 $tab[$i] = $obj->id;
2481 }
2482
2483 $i++;
2484 }
2485
2486 return $tab;
2487 } else {
2488 $this->error = $this->db->error();
2489 dol_print_error($this->db);
2490 return -1;
2491 }
2492 }
2493
2500 public function getDefaultRef($thirdparty = null)
2501 {
2502 global $conf;
2503
2504 $defaultref = '';
2505 $modele = getDolGlobalString('TICKET_ADDON', 'mod_ticket_simple');
2506
2507 // Search template files
2508 $file = '';
2509 $classname = '';
2510 $reldir = '';
2511 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
2512 foreach ($dirmodels as $reldir) {
2513 $file = dol_buildpath($reldir."core/modules/ticket/".$modele.'.php', 0);
2514 if (file_exists($file)) {
2515 $classname = $modele;
2516 break;
2517 }
2518 }
2519
2520 if ($classname !== '') {
2521 $result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php');
2522 $modTicket = new $classname();
2523 '@phan-var-force ModeleNumRefTicket $modTicket';
2524
2525 $defaultref = $modTicket->getNextValue($thirdparty, $this);
2526 }
2527
2528 if (is_numeric($defaultref) && $defaultref <= 0) {
2529 $defaultref = '';
2530 }
2531
2532 return $defaultref;
2533 }
2534
2535
2536 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2543 public function is_photo_available($sdir)
2544 {
2545 // phpcs:enable
2546 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2547
2548 $dir = $sdir.'/';
2549
2550 $dir_osencoded = dol_osencode($dir);
2551 if (file_exists($dir_osencoded)) {
2552 $handle = opendir($dir_osencoded);
2553 if (is_resource($handle)) {
2554 while (($file = readdir($handle)) !== false) {
2555 if (!utf8_check($file)) {
2556 $file = mb_convert_encoding($file, 'UTF-8', 'ISO-8859-1'); // To be sure data is stored in UTF8 in memory
2557 }
2558 if (dol_is_file($dir.$file)) {
2559 return true;
2560 }
2561 }
2562 }
2563 }
2564 return false;
2565 }
2566
2567
2576 public function copyFilesForTicket($forcetrackid = null)
2577 {
2578 global $conf;
2579
2580 // Create form object
2581 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
2582 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2583 include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
2584
2585 $maxwidthsmall = 270;
2586 $maxheightsmall = 150;
2587 $maxwidthmini = 128;
2588 $maxheightmini = 72;
2589
2590 $formmail = new FormMail($this->db);
2591 $formmail->trackid = (is_null($forcetrackid) ? 'tic'.$this->id : '');
2592 $attachedfiles = $formmail->get_attached_files();
2593
2594 $filepath = $attachedfiles['paths']; // path is for example user->dir_temp.'/'.$user->id.'/'...
2595 $filename = $attachedfiles['names'];
2596 $mimetype = $attachedfiles['mimes'];
2597
2598 // Copy files into ticket directory
2599 $destdir = $conf->ticket->dir_output.'/'.$this->ref;
2600
2601 if (!dol_is_dir($destdir)) {
2602 dol_mkdir($destdir);
2603 }
2604
2605 $listofpaths = array();
2606 $listofnames = array();
2607 foreach ($filename as $i => $val) {
2608 $destfile = $destdir.'/'.$filename[$i];
2609 // If destination file already exists, we add a suffix to avoid to overwrite
2610 if (is_file($destfile)) {
2611 $pathinfo = pathinfo($filename[$i]);
2612 $now = dol_now();
2613 $destfile = $destdir.'/'.$pathinfo['filename'].' - '.dol_print_date($now, 'dayhourlog').'.'.$pathinfo['extension'];
2614 }
2615
2616 $moreinfo = array(
2617 'description' => 'File saved by copyFilesForTicket',
2618 'src_object_type' => $this->element,
2619 'src_object_id' => $this->id,
2620 'gen_or_uploaded' => 'uploaded'
2621 );
2622
2623 $res = dol_move($filepath[$i], $destfile, '0', 1, 0, 1, $moreinfo);
2624
2625 if (!$res) {
2626 // Move has failed
2627 $this->error = "Failed to move file ".dirbasename($filepath[$i])." into ".dirbasename($destfile);
2628 return -1;
2629 } else {
2630 // If file is an image, we create thumbs
2631 if (image_format_supported($destfile) == 1) {
2632 // Create small thumbs for image (Ratio is near 16/9)
2633 // Used on logon for example
2634 $imgThumbSmall = vignette($destfile, $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs");
2635 // Create mini thumbs for image (Ratio is near 16/9)
2636 // Used on menu or for setup page for example
2637 $imgThumbMini = vignette($destfile, $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs");
2638 }
2639 }
2640
2641 // Clear variables into session
2642 $formmail->remove_attached_files($i);
2643
2644 // Fill array with new names
2645 $listofpaths[$i] = $destfile;
2646 $listofnames[$i] = basename($destfile);
2647 }
2648
2649 return array('listofpaths' => $listofpaths, 'listofnames' => $listofnames, 'listofmimes' => $mimetype);
2650 }
2651
2662 public function setCategories($categories)
2663 {
2664 // Handle single category
2665 if (!is_array($categories)) {
2666 $categories = array($categories);
2667 }
2668
2669 // Get current categories
2670 include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2671 $c = new Categorie($this->db);
2672 $existing = $c->containing($this->id, Categorie::TYPE_TICKET, 'id');
2673
2674 // Diff
2675 if (is_array($existing)) {
2676 $to_del = array_diff($existing, $categories);
2677 $to_add = array_diff($categories, $existing);
2678 } else {
2679 $to_del = array(); // Nothing to delete
2680 $to_add = $categories;
2681 }
2682
2683 // Process
2684 foreach ($to_del as $del) {
2685 if ($c->fetch($del) > 0) {
2686 $c->del_type($this, Categorie::TYPE_TICKET);
2687 }
2688 }
2689 foreach ($to_add as $add) {
2690 if ($c->fetch($add) > 0) {
2691 $c->add_type($this, Categorie::TYPE_TICKET);
2692 }
2693 }
2694
2695 return 1;
2696 }
2697
2710 public function newMessage($user, &$action, $private = 1, $public_area = 0)
2711 {
2712 global $mysoc, $langs;
2713
2714 $error = 0;
2715
2716 $object = new Ticket($this->db);
2717
2718 $ret = $object->fetch(0, '', GETPOST('track_id', 'alpha'));
2719
2720 $object->socid = $object->fk_soc;
2721 $object->fetch_thirdparty();
2722 $object->fetchProject();
2723
2724 if ($ret < 0) {
2725 $error++;
2726 array_push($this->errors, $langs->trans("ErrorTicketIsNotValid"));
2727 $action = '';
2728 }
2729
2730 if (!GETPOST("message")) {
2731 $error++;
2732 array_push($this->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("Message")));
2733 $action = 'add_message';
2734 }
2735
2736 if (!$error) {
2737 $object->subject = GETPOST('subject', 'alphanohtml');
2738 $object->message = GETPOST("message", "restricthtml");
2739 $object->private = GETPOST("private_message", "alpha");
2740
2741 $send_email = (bool) GETPOSTINT('send_email');
2742
2743 // Copy attached files (saved into $_SESSION) as linked files to ticket. Return array with final name used.
2744 $resarray = $object->copyFilesForTicket();
2745 if (is_numeric($resarray) && $resarray == -1) {
2746 setEventMessages($object->error, $object->errors, 'errors');
2747 return -1;
2748 }
2749
2750 $listofpaths = $resarray['listofpaths'];
2751 $listofnames = $resarray['listofnames'];
2752 $listofmimes = $resarray['listofmimes'];
2753
2754 // Add the ticket message in database (even if email is requested, we store a simple record
2755 // like a simple private message, with no information about emails) because
2756 // information about emails sent will be fill later after email sending.
2757 $id = $object->createTicketMessage($user, 0, $listofpaths, $listofmimes, $listofnames, $send_email, $public_area);
2758
2759 if ($id <= 0) {
2760 $error++;
2761 $this->error = $object->error;
2762 $this->errors = $object->errors;
2763 $action = 'add_message';
2764 }
2765
2766 if (!$error && $id > 0) {
2767 setEventMessages($langs->trans('TicketMessageSuccessfullyAdded'), null, 'mesgs');
2768
2769 // Now send emails
2770 if (!empty($public_area)) {
2771 /*
2772 * Message created from the Public interface
2773 *
2774 * Send emails to assigned users (public area notification)
2775 */
2776 if (getDolGlobalString('TICKET_PUBLIC_NOTIFICATION_NEW_MESSAGE_ENABLED')) {
2777 // Retrieve internal contact datas
2778 $internal_contacts = $object->getInfosTicketInternalContact(1);
2779
2780 $assigned_user_dont_have_email = '';
2781
2782 $sendto = array();
2783
2784 if ($this->fk_user_assign > 0) {
2785 $assigned_user = new User($this->db);
2786 $assigned_user->fetch($this->fk_user_assign);
2787 if (!empty($assigned_user->email)) {
2788 $sendto[$assigned_user->email] = $assigned_user->getFullName($langs)." <".$assigned_user->email.">";
2789 } else {
2790 $assigned_user_dont_have_email = $assigned_user->getFullName($langs);
2791 }
2792 } else {
2793 $assigned_user = null;
2794 }
2795
2796 // Build array to display recipient list
2797 foreach ($internal_contacts as $key => $info_sendto) {
2798 // Avoid duplicate notifications
2799 if ($info_sendto['id'] == $user->id) {
2800 continue;
2801 }
2802
2803 // We check if the email address is not the assignee's address to prevent notification from being sent twice
2804 if (!empty($info_sendto['email']) && ($assigned_user === null || $assigned_user->email != $info_sendto['email'])) {
2805 $sendto[] = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'])." <".$info_sendto['email'].">";
2806 }
2807 }
2808
2809 if (empty($sendto)) {
2810 if (getDolGlobalString('TICKET_PUBLIC_NOTIFICATION_NEW_MESSAGE_DEFAULT_EMAIL')) {
2811 $sendto[getDolGlobalString('TICKET_PUBLIC_NOTIFICATION_NEW_MESSAGE_DEFAULT_EMAIL')] = getDolGlobalString('TICKET_PUBLIC_NOTIFICATION_NEW_MESSAGE_DEFAULT_EMAIL');
2812 } elseif (getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO')) {
2813 $sendto[getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO')] = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO');
2814 }
2815 }
2816
2817 // Add global email address recipient
2818 if (getDolGlobalString('TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS') && !array_key_exists(getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO'), $sendto)) {
2819 if (getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO')) {
2820 $sendto[getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO')] = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO');
2821 }
2822 }
2823
2824 if (!empty($sendto)) {
2825 $appli = getDolGlobalString('MAIN_APPLICATION_TITLE', $mysoc->name);
2826
2827 $subject = '['.$appli.'- ticket #'.$object->track_id.'] '.$this->subject;
2828
2829 // Message send
2830 $message = getDolGlobalString('TICKET_MESSAGE_MAIL_INTRO', $langs->trans('TicketMessageMailIntroText'));
2831 $message .= '<br><br>';
2832 $messagePost = GETPOST('message', 'restricthtml');
2833 if (!dol_textishtml($messagePost)) {
2834 $messagePost = dol_nl2br($messagePost);
2835 }
2836 $message .= $messagePost;
2837
2838 // Customer company infos
2839 $message .= '<br><br>';
2840 $message .= "==============================================";
2841 $message .= !empty($object->thirdparty->name) ? '<br>'.$langs->trans('ThirdParty')." : ".$object->thirdparty->name : '';
2842 $message .= !empty($object->thirdparty->town) ? '<br>'.$langs->trans('Town')." : ".$object->thirdparty->town : '';
2843 $message .= !empty($object->thirdparty->phone) ? '<br>'.$langs->trans('Phone')." : ".$object->thirdparty->phone : '';
2844
2845 // Email send to
2846 $message .= '<br><br>';
2847 if (!empty($assigned_user_dont_have_email)) {
2848 $message .= '<br>'.$langs->trans('NoEMail').' : '.$assigned_user_dont_have_email;
2849 }
2850 foreach ($sendto as $val) {
2851 $message .= '<br>'.$langs->trans('TicketNotificationRecipient').' : '.$val;
2852 }
2853
2854 // URL ticket
2855 $url_internal_ticket = dol_buildpath('/ticket/card.php', 2).'?track_id='.$object->track_id;
2856 $message .= '<br><br>';
2857 $message .= $langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal').' : <a href="'.$url_internal_ticket.'">'.$object->track_id.'</a>';
2858
2859 $from = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_FROM');
2860
2861 $replyto = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_REPLYTO');
2862
2863 // don't try to send email if no recipient
2864 $this->sendTicketMessageByEmail($subject, $message, 0, $sendto, $listofpaths, $listofmimes, $listofnames, array(), $from, $replyto);
2865 }
2866 }
2867 } else {
2868 /*
2869 * Message created from the Backoffice / Private area
2870 *
2871 * 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)
2872 */
2873 if ((int) $send_email > 0) {
2874 // Retrieve internal contact datas
2875 $internal_contacts = $object->getInfosTicketInternalContact(1);
2876
2877 $sendto = array();
2878 if (is_array($internal_contacts) && count($internal_contacts) > 0) {
2879 // Set default subject
2880 $appli = getDolGlobalString('MAIN_APPLICATION_TITLE', $mysoc->name);
2881
2882 $subject = GETPOST('subject', 'alphanohtml') ? GETPOST('subject', 'alphanohtml') : '['.$appli.' - '.$langs->trans("Ticket").' #'.$object->track_id.'] '.$langs->trans('TicketNewMessage');
2883
2884 $message_intro = $langs->trans('TicketNotificationEmailBody', "#".$object->id);
2885 $message_signature = GETPOST('mail_signature') ? GETPOST('mail_signature') : getDolGlobalString('TICKET_MESSAGE_MAIL_SIGNATURE');
2886
2887 $message = getDolGlobalString('TICKET_MESSAGE_MAIL_INTRO', $langs->trans('TicketMessageMailIntroText'));
2888 $message .= '<br><br>';
2889 $messagePost = GETPOST('message', 'restricthtml');
2890 if (!dol_textishtml($messagePost)) {
2891 $messagePost = dol_nl2br($messagePost);
2892 }
2893 $message .= $messagePost;
2894
2895 // Data about customer
2896 $message .= '<br><br>';
2897 $message .= "==============================================<br>";
2898 $message .= !empty($object->thirdparty->name) ? $langs->trans('ThirdParty')." : ".$object->thirdparty->name : '';
2899 $message .= !empty($object->thirdparty->town) ? '<br>'.$langs->trans('Town')." : ".$object->thirdparty->town : '';
2900 $message .= !empty($object->thirdparty->phone) ? '<br>'.$langs->trans('Phone')." : ".$object->thirdparty->phone : '';
2901
2902 // Build array to display recipient list
2903 foreach ($internal_contacts as $key => $info_sendto) {
2904 // Check if recipient email is current user, if yes, we avoid to send email to him.
2905 if ($info_sendto['id'] == $user->id) {
2906 dol_syslog("We cancel sending email to internal user ".$info_sendto['email']." because it is current user", LOG_DEBUG);
2907 continue;
2908 }
2909
2910 if ($info_sendto['email'] != '') {
2911 $email = $info_sendto['email'];
2912 if ($email != null) {
2913 $sendto[$email] = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'])." <".$info_sendto['email'].">";
2914 }
2915
2916 // Contact type
2917 $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], -1).' ('.strtolower((string) $info_sendto['libelle']).')';
2918 $message .= (!empty($recipient) ? '<br>'.$langs->trans('TicketNotificationRecipient').' : '.$recipient.'<br>' : '');
2919 }
2920 }
2921 $message .= '<br>';
2922 // URL ticket
2923 $url_internal_ticket = dol_buildpath('/ticket/card.php', 2).'?track_id='.$object->track_id;
2924
2925 // Add html link on url
2926 $message .= '<br>'.$langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal').' : <a href="'.$url_internal_ticket.'">'.$object->track_id.'</a><br>';
2927
2928 // Add global email address recipient
2929 if (getDolGlobalString('TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS') && !array_key_exists(getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO'), $sendto)) {
2930 if (getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO')) {
2931 $sendto[getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO')] = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO');
2932 }
2933 }
2934
2935 $sendtocc = array();
2936 if (getDolGlobalString("TICKET_SEND_INTERNAL_CC")) {
2937 $sendtocc = explode(',', getDolGlobalString("TICKET_SEND_INTERNAL_CC"));
2938 }
2939
2940 $from = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_FROM');
2941
2942 $replyto = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_REPLYTO');
2943
2944 // don't try to send email if no recipient
2945 if (!empty($sendto)) {
2946 $this->sendTicketMessageByEmail($subject, $message, 0, $sendto, $listofpaths, $listofmimes, $listofnames, $sendtocc, $from, $replyto);
2947 }
2948 }
2949
2950 /*
2951 * Send emails for externals users if not private (linked contacts)
2952 */
2953 if (empty($object->private)) {
2954 // Retrieve email of all contacts (external)
2955 $external_contacts = $object->getInfosTicketExternalContact(1);
2956
2957 // If no contact, get email from thirdparty
2958 if (is_array($external_contacts) && count($external_contacts) === 0) {
2959 if (!empty($object->fk_soc)) {
2960 $object->fetch_thirdparty($object->fk_soc);
2961 $array_company = array(array('id' => -1, 'firstname' => '', 'lastname' => $object->thirdparty->name, 'email' => $object->thirdparty->email, 'libelle' => $langs->transnoentities('Customer'), 'socid' => $object->thirdparty->id));
2962 $external_contacts = array_merge($external_contacts, $array_company);
2963 } elseif (empty($object->fk_soc) && !empty($object->origin_replyto)) {
2964 $array_external = array(array('id' => -1, 'firstname' => '', 'lastname' => $object->origin_replyto, 'email' => $object->origin_replyto, 'libelle' => $langs->transnoentities('Customer'), 'socid' => 0));
2965 $external_contacts = array_merge($external_contacts, $array_external);
2966 } elseif (empty($object->fk_soc) && !empty($object->origin_email)) {
2967 $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)
2968 $external_contacts = array_merge($external_contacts, $array_external);
2969 }
2970 }
2971
2972 $sendto = array();
2973 if (is_array($external_contacts) && count($external_contacts) > 0) {
2974 // Get default subject for email to external contacts
2975 $appli = getDolGlobalString('MAIN_APPLICATION_TITLE', $mysoc->name);
2976
2977 $subject = GETPOST('subject') ? GETPOST('subject') : '['.$appli.' - '.$langs->trans("Ticket").' #'.$object->track_id.'] '.$langs->trans('TicketNewMessage');
2978
2979 $message_intro = GETPOST('mail_intro') ? GETPOST('mail_intro', 'restricthtml') : getDolGlobalString('TICKET_MESSAGE_MAIL_INTRO');
2980 $message_signature = GETPOST('mail_signature') ? GETPOST('mail_signature', 'restricthtml') : getDolGlobalString('TICKET_MESSAGE_MAIL_SIGNATURE');
2981 if (!dol_textishtml($message_intro)) {
2982 $message_intro = dol_nl2br($message_intro);
2983 }
2984 if (!dol_textishtml($message_signature)) {
2985 $message_signature = dol_nl2br($message_signature);
2986 }
2987
2988 // We put intro after
2989 $messagePost = GETPOST('message', 'restricthtml');
2990 if (!dol_textishtml($messagePost)) {
2991 $messagePost = dol_nl2br($messagePost);
2992 }
2993 $message = $messagePost;
2994 $message .= '<br><br>';
2995
2996 foreach ($external_contacts as $key => $info_sendto) {
2997 // Check if recipient email is current user, if yes, we avoid to send email to him.
2998 if ($info_sendto['id'] == $user->contact_id) {
2999 continue;
3000 }
3001
3002 if ($info_sendto['email'] != '' && $info_sendto['email'] != $object->origin_email) {
3003 $email = $info_sendto['email'];
3004 if ($email != null) {
3005 $sendto[$email] = trim($info_sendto['firstname']." ".$info_sendto['lastname'])." <".$info_sendto['email'].">";
3006 }
3007
3008 $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], -1).' ('.strtolower((string) $info_sendto['libelle']).')';
3009 $message .= (!empty($recipient) ? '<br>'.$langs->trans('TicketNotificationRecipient').' : '.$recipient.'<br>' : '');
3010 }
3011 }
3012
3013 // If public interface is not enable, use link to internal page into mail
3014 $url_public_ticket = (getDolGlobalInt('TICKET_ENABLE_PUBLIC_INTERFACE') ?
3015 (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);
3016
3017 if (getDolGlobalInt('TICKET_INCLUDE_LINK_TO_PUBLIC_INTERFACE_IN_MESSAGE')) {
3018 $message .= '<br>' . $langs->trans('TicketNewEmailBodyInfosTrackUrlCustomer') . ' : <a href="' . $url_public_ticket . '">' . $object->track_id . '</a><br>';
3019 }
3020
3021 // Build final message
3022 $message = $message_intro.'<br><br>'.$message;
3023
3024 // Add signature
3025 $message .= '<br>'.$message_signature;
3026
3027 if (!empty($object->origin_replyto)) {
3028 $sendto[$object->origin_replyto] = $object->origin_replyto;
3029 } elseif (!empty($object->origin_email)) {
3030 $sendto[$object->origin_email] = $object->origin_email;
3031 }
3032
3033 if ($object->fk_soc > 0 && !array_key_exists($object->origin_replyto, $sendto) && !array_key_exists($object->origin_email, $sendto)) {
3034 $object->socid = $object->fk_soc;
3035 $object->fetch_thirdparty();
3036 if (!empty($object->thirdparty->email)) {
3037 $sendto[$object->thirdparty->email] = $object->thirdparty->email;
3038 }
3039 }
3040
3041 // Add global email address recipient
3042 if (getDolGlobalString('TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS') && !array_key_exists(getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO'), $sendto)) {
3043 if (getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO')) {
3044 $sendto[getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO')] = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_TO');
3045 }
3046 }
3047
3048 $sendtocc = array();
3049 if (getDolGlobalString("TICKET_SEND_INTERNAL_CC")) {
3050 $sendtocc = explode(',', getDolGlobalString("TICKET_SEND_INTERNAL_CC"));
3051 }
3052
3053 // Don't try to send email when no recipient
3054 if (!empty($sendto)) {
3055 $from = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_FROM');
3056
3057 $replyto = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_REPLYTO');
3058
3059 $result = $this->sendTicketMessageByEmail($subject, $message, 0, $sendto, $listofpaths, $listofmimes, $listofnames, $sendtocc, $from, $replyto);
3060 if ($result) {
3061 // update last_msg_sent date of ticket (for last message sent to external users)
3062 $this->date_last_msg_sent = dol_now();
3063 $this->update($user, 1); // disable trigger when updating date_last_msg_sent. sendTicketMessageByEmail already create an event in actioncomm table.
3064
3065 // update event actioncomm $id
3066 //print 'update actioncomm id='.$id.' with sendto='.json_encode($sendto)." sendtocc=".json_encode($sendtocc)." email_msgid=".json_encode($this->email_msgid);
3067 $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm";
3068 $sql .= " SET email_msgid = '".$this->db->escape($this->email_msgid)."',";
3069 $sql .= " email_subject = '".$this->db->escape($subject)."',";
3070 $sql .= " email_from = '".$this->db->escape($from)."',";
3071 $sql .= " email_to = '".$this->db->escape(implode(',', $sendto))."',";
3072 $sql .= " email_tocc = '".$this->db->escape(implode(',', $sendtocc))."',";
3073 $sql .= " reply_to = '".$this->db->escape($replyto)."'";
3074 $sql .= " WHERE id = ".((int) $id);
3075
3076 $resql = $this->db->query($sql);
3077 }
3078 }
3079 }
3080 }
3081 }
3082 }
3083
3084 // Set status back to "In progress" if not set yet, but only if internal user and not a private message
3085 // Or set status to "In progress" if the client has answered and if the ticket has started
3086 // So we are sure to leave the STATUS_DRAFT, STATUS_NEED_INFO.
3087 // Except if TICKET_SET_STATUS_ON_ANSWER has been defined
3088 if ((getDolGlobalInt('TICKET_SET_STATUS_ON_ANSWER', -1) < 0
3089 && ($object->status < self::STATUS_IN_PROGRESS && !$user->socid && !$private))
3090 || ($object->status > self::STATUS_IN_PROGRESS && $public_area)) {
3091 // Set status
3092 $object->setStatut($object::STATUS_IN_PROGRESS, null, '', 'TICKET_MODIFY');
3093 } elseif (getDolGlobalInt('TICKET_SET_STATUS_ON_ANSWER', -1) >= 0 && empty($user->socid) && empty($private)) {
3094 // Set status
3095 $object->setStatut(getDolGlobalInt('TICKET_SET_STATUS_ON_ANSWER'), null, '', 'TICKET_MODIFY');
3096 }
3097
3098 return 1;
3099 } else {
3100 setEventMessages($object->error, $object->errors, 'errors');
3101 return -1;
3102 }
3103 } else {
3104 setEventMessages($this->error, $this->errors, 'errors');
3105 return -1;
3106 }
3107 }
3108
3109
3125 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(), $from = '', $replyto = '')
3126 {
3127 global $conf, $langs, $user;
3128
3129 if (getDolGlobalString('TICKET_DISABLE_ALL_MAILS')) {
3130 dol_syslog(get_class($this).'::sendTicketMessageByEmail: Emails are disable into ticket setup by option TICKET_DISABLE_ALL_MAILS', LOG_WARNING);
3131 return false;
3132 }
3133
3134 $langs->load("mails");
3135
3136 include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3137 //$contactstatic = new Contact($this->db);
3138
3139 // If no receiver defined, load all ticket linked contacts
3140 if (!is_array($array_receiver) || !count($array_receiver) > 0) {
3141 $array_receiver = $this->getInfosTicketInternalContact(1);
3142 $array_receiver = array_merge($array_receiver, $this->getInfosTicketExternalContact(1));
3143 }
3144
3145 dol_syslog("sendTicketMessageByEmail array_receiver=".json_encode($array_receiver), LOG_DEBUG);
3146 dol_syslog("sendTicketMessageByEmail array_receiver_cc=".json_encode($array_receiver_cc), LOG_DEBUG);
3147
3148 $sendtocc = '';
3149 if ($send_internal_cc) {
3150 $sendtocc = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_FROM');
3151 }
3152 if (!empty($array_receiver_cc) && is_array($array_receiver_cc)) {
3153 $sendtocc .= ($sendtocc ? ',' : '').implode(',', $array_receiver_cc);
3154 }
3155
3156 if (empty($from)) {
3157 $from = getDolGlobalString('TICKET_NOTIFICATION_EMAIL_FROM');
3158 }
3159
3160 $is_sent = false;
3161 $this->email_msgids = array();
3162
3163 if (is_array($array_receiver) && count($array_receiver) > 0) {
3164 //foreach ($array_receiver as $key => $receiver) {
3165 $deliveryreceipt = 0;
3166 $filepath = $filename_list;
3167 $filename = $mimefilename_list;
3168 $mimetype = $mimetype_list;
3169
3170 // Send email
3171
3172 $old_MAIN_MAIL_AUTOCOPY_TO = getDolGlobalString('MAIN_MAIL_AUTOCOPY_TO');
3173 if (getDolGlobalString('TICKET_DISABLE_MAIL_AUTOCOPY_TO')) {
3174 $conf->global->MAIN_MAIL_AUTOCOPY_TO = '';
3175 }
3176
3177 $upload_dir_tmp = $conf->user->dir_output."/".$user->id.'/temp';
3178
3179 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
3180 $trackid = "tic".$this->id;
3181
3182 $moreinheader = 'X-Dolibarr-Info: sendTicketMessageByEmail'."\r\n";
3183 if (!empty($this->email_msgid)) {
3184 // We must also add 1 entry In-Reply-To: <$this->email_msgid> with Message-ID we respond from (See RFC5322).
3185 $moreinheader .= 'In-Reply-To: <'.$this->email_msgid.'>'."\r\n";
3186 // TODO We should now be able to give the in_reply_to as a dedicated parameter of new CMailFile() instead of into $moreinheader.
3187 }
3188
3189 // We should add here also a header 'References:'
3190 // According to RFC5322, we should add here all the References fields of the initial message concatenated with
3191 // the Message-ID of the message we respond from (but each ID must be once).
3192 $references = '';
3193 if (!empty($this->origin_references)) { // $this->origin_references should be '<'.$this->origin_references.'>'
3194 $references .= (empty($references) ? '' : ' ').$this->origin_references;
3195 }
3196 if (!empty($this->email_msgid) && !preg_match('/'.preg_quote($this->email_msgid, '/').'/', $references)) {
3197 $references .= (empty($references) ? '' : ' ').'<'.$this->email_msgid.'>';
3198 }
3199 if ($references) {
3200 $moreinheader .= 'References: '.$references."\r\n";
3201 // TODO We should now be able to give the references as a dedicated parameter of new CMailFile() instead of into $moreinheader.
3202 }
3203
3204 $receiverstring = '';
3205 foreach ($array_receiver as $key => $receiver) {
3206 $receiverstring .= ($receiverstring ? ',' : '').$receiver;
3207 }
3208
3209 $sendcontext = 'ticket';
3210
3211 // Send email
3212 $mailfile = new CMailFile($subject, $receiverstring, $from, $message, $filepath, $mimetype, $filename, $sendtocc, '', $deliveryreceipt, -1, '', '', $trackid, $moreinheader, $sendcontext, $replyto, $upload_dir_tmp);
3213
3214
3215 if ($mailfile->error) {
3216 setEventMessages($mailfile->error, null, 'errors');
3217 } else {
3218 $result = $mailfile->sendfile();
3219
3220 if ($result) {
3221 setEventMessages($langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($from, 2), $mailfile->getValidAddress($receiverstring, 2)), null, 'mesgs');
3222 $is_sent = true;
3223
3224 $this->email_msgid = $mailfile->msgid;
3225 } else {
3226 $langs->load("other");
3227 if ($mailfile->error) {
3228 setEventMessages($langs->trans('ErrorFailedToSendMail', $from, $receiverstring), null, 'errors');
3229 dol_syslog($langs->trans('ErrorFailedToSendMail', $from, $receiverstring).' : '.$mailfile->error);
3230 } elseif (getDolGlobalString('MAIN_DISABLE_ALL_MAILS')) {
3231 setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'errors');
3232 } else {
3233 setEventMessages($langs->trans('ErrorFailedToSendMail', $from, $receiverstring), null, 'errors');
3234 dol_syslog('ErrorFailedToSendMail (no error details) from='.$from.' to='.$receiverstring, LOG_WARNING);
3235 }
3236 }
3237 }
3238
3239 if (getDolGlobalString('TICKET_DISABLE_MAIL_AUTOCOPY_TO')) {
3240 $conf->global->MAIN_MAIL_AUTOCOPY_TO = $old_MAIN_MAIL_AUTOCOPY_TO;
3241 }
3242 //}
3243 } else {
3244 $langs->load("other");
3245 setEventMessages($langs->trans('ErrorMailRecipientIsEmptyForSendTicketMessage'), null, 'warnings');
3246 }
3247
3248 return $is_sent;
3249 }
3250
3251 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3259 public function load_board($user, $mode)
3260 {
3261 // phpcs:enable
3262 global $user, $langs;
3263
3264 $now = dol_now();
3265 $delay_warning = 0;
3266
3267 $clause = " WHERE";
3268
3269 $sql = "SELECT p.rowid, p.ref, p.datec as datec";
3270 $sql .= " FROM ".MAIN_DB_PREFIX."ticket as p";
3271 if (empty($user->socid) && isModEnabled('societe') && !$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
3272 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc";
3273 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
3274 $clause = " AND";
3275 }
3276 $sql .= $clause." p.entity IN (".getEntity('ticket').")";
3277 if ($mode == 'opened') {
3278 $sql .= " AND p.fk_statut NOT IN (".Ticket::STATUS_CLOSED.", ".Ticket::STATUS_CANCELED.")";
3279 }
3280 if ($user->socid) {
3281 $sql .= " AND p.fk_soc = ".((int) $user->socid);
3282 }
3283
3284 $resql = $this->db->query($sql);
3285 if ($resql) {
3286 $label = $labelShort = '';
3287 $status = '';
3288 if ($mode == 'opened') {
3289 $status = 'openall';
3290 //$delay_warning = $conf->ticket->warning_delay;
3291 $delay_warning = 0;
3292 $label = $langs->trans("MenuListNonClosed");
3293 $labelShort = $langs->trans("MenuListNonClosed");
3294 }
3295
3296 $response = new WorkboardResponse();
3297 //$response->warning_delay = $delay_warning / 60 / 60 / 24;
3298 $response->label = $label;
3299 $response->labelShort = $labelShort;
3300 $response->url = DOL_URL_ROOT.'/ticket/list.php?search_fk_statut[]='.$status;
3301 $response->img = img_object('', "ticket");
3302
3303 // This assignment in condition is not a bug. It allows walking the results.
3304 while ($obj = $this->db->fetch_object($resql)) {
3305 $response->nbtodo++;
3306 if ($mode == 'opened') {
3307 $datelimit = (int) $this->db->jdate($obj->datec) + (int) $delay_warning;
3308 if ($datelimit < $now) {
3309 //$response->nbtodolate++;
3310 }
3311 }
3312 }
3313 return $response;
3314 } else {
3315 $this->error = $this->db->lasterror();
3316 return -1;
3317 }
3318 }
3319
3325 public function loadStateBoard()
3326 {
3327 global $user;
3328
3329 $this->nb = array();
3330 $clause = "WHERE";
3331
3332 $sql = "SELECT count(p.rowid) as nb";
3333 $sql .= " FROM ".MAIN_DB_PREFIX."ticket as p";
3334 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
3335 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
3336 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3337 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
3338 $clause = "AND";
3339 }
3340 $sql .= " ".$clause." p.entity IN (".getEntity('ticket').")";
3341
3342 $resql = $this->db->query($sql);
3343 if ($resql) {
3344 // This assignment in condition is not a bug. It allows walking the results.
3345 while ($obj = $this->db->fetch_object($resql)) {
3346 $this->nb["ticket"] = $obj->nb;
3347 }
3348 $this->db->free($resql);
3349 return 1;
3350 } else {
3351 dol_print_error($this->db);
3352 $this->error = $this->db->lasterror();
3353 return -1;
3354 }
3355 }
3356
3365 public static function replaceThirdparty($db, $origin_id, $dest_id)
3366 {
3367 $tables = array('ticket');
3368
3369 return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
3370 }
3371
3379 public function getKanbanView($option = '', $arraydata = null)
3380 {
3381 global $langs;
3382
3383 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3384
3385 $return = '<div class="box-flex-item box-flex-grow-zero">';
3386 $return .= '<div class="info-box info-box-sm">';
3387 $return .= '<span class="info-box-icon bg-infobox-action">';
3388 $return .= img_picto('', $this->picto);
3389 $return .= '</span>';
3390 $return .= '<div class="info-box-content">';
3391 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).'</span>';
3392 if ($selected >= 0) {
3393 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3394 }
3395 if (!empty($arraydata['user_assignment'])) {
3396 $return .= '<br><span class="info-box-label" title="'.dol_escape_htmltag($langs->trans("AssignedTo")).'">'.$arraydata['user_assignment'].'</span>';
3397 }
3398 if (property_exists($this, 'type_code') && !empty($this->type_code)) {
3399 $return .= '<br>';
3400 $return .= '<div class="tdoverflowmax125 inline-block">'.$langs->getLabelFromKey($this->db, 'TicketTypeShort'.$this->type_code, 'c_ticket_type', 'code', 'label', $this->type_code).'</div>';
3401 }
3402 if (method_exists($this, 'getLibStatut')) {
3403 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
3404 }
3405 $return .= '</div>';
3406 $return .= '</div>';
3407 $return .= '</div>';
3408
3409 return $return;
3410 }
3411
3423 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3424 {
3425 global $langs;
3426
3427 $langs->load("ticket");
3428 $outputlangs->load("ticket");
3429
3430 if (!dol_strlen($modele)) {
3431 $modele = 'generic_ticket_odt';
3432
3433 if (!empty($this->model_pdf)) {
3434 $modele = $this->model_pdf;
3435 } elseif (getDolGlobalString('TICKET_ADDON_PDF')) {
3436 $modele = getDolGlobalString('TICKET_ADDON_PDF');
3437 }
3438 }
3439
3440 $modelpath = "core/modules/ticket/doc/";
3441
3442 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3443 }
3444}
$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:331
$object ref
Definition info.php:90
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Class to manage categories.
Parent class of all other business classes (invoices, contracts, proposals, orders,...
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 permettant la generation du formulaire html d'envoi de mail unitaire Usage: $formail = new Form...
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.
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.
sendTicketMessageByEmail($subject, $message, $send_internal_cc=0, $array_receiver=array(), $filename_list=array(), $mimetype_list=array(), $mimefilename_list=array(), $array_receiver_cc=array(), $from='', $replyto='')
Send ticket by email to linked contacts.
setProgression($percent)
Define progression of current ticket.
searchSocidByEmail($email, $type=0, $filters=array(), $clause='AND')
Search and fetch thirparties by email.
loadCacheSeveritiesTickets()
Charge dans cache la liste des sévérité de tickets (paramétrable dans dictionnaire)
$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.
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.
getTicketAllCustomerContacts()
Return id of all contacts for ticket.
createTicketMessage($user, $notrigger=0, $filename_list=array(), $mimetype_list=array(), $mimefilename_list=array(), $send_email=false, $public_area=0)
Add message into database.
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:171
global $mysoc
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.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
setEntity($currentobject)
Set entity id to use when to create an object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
isDolTms($timestamp)
isDolTms check if a timestamp is valid.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_nl2br($stringtoencode, $nl2brmode=0, $forxml=false)
Replace CRLF in string with a HTML BR tag.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
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.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_textishtml($msg, $option=0)
Return if a text is a html content.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
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).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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.