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