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