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