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