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