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