Passed
Branch develop (b426bb)
by
unknown
25:54
created

Ticket::load_board()   B

Complexity

Conditions 10

Size

Total Lines 61
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 36
nop 2
dl 0
loc 61
rs 7.6666
c 1
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) 2013-2018 Jean-François Ferry <[email protected]>
3
 * Copyright (C) 2016      Christophe Battarel <[email protected]>
4
 * Copyright (C) 2019       Frédéric France     <[email protected]>
5
 *
6
 * This program is free software; you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18
 */
19
20
/**
21
 *  \file       ticket/class/ticket.class.php
22
 *  \ingroup    ticket
23
 *  \brief      Class file for object ticket
24
 */
25
26
// Put here all includes required by your class file
27
require_once DOL_DOCUMENT_ROOT."/core/class/commonobject.class.php";
28
require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
29
require_once DOL_DOCUMENT_ROOT.'/core/lib/ticket.lib.php';
30
31
32
/**
33
 *    Class to manage ticket
34
 */
35
class Ticket extends CommonObject
36
{
37
	/**
38
	 * @var string ID to identify managed object
39
	 */
40
	public $element = 'ticket';
41
42
	/**
43
	 * @var string Name of table without prefix where object is stored
44
	 */
45
	public $table_element = 'ticket';
46
47
	/**
48
	 * @var string Name of field for link to tickets
49
	 */
50
	public $fk_element = 'fk_ticket';
51
52
	/**
53
	 * @var int  Does ticketcore support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
54
	 */
55
	public $ismultientitymanaged = 1;
56
57
	/**
58
	 * @var int  Does ticketcore support extrafields ? 0=No, 1=Yes
59
	 */
60
	public $isextrafieldmanaged = 1;
61
62
	/**
63
	 * @var string String with name of icon for ticketcore. Must be the part after the 'object_' into object_ticketcore.png
64
	 */
65
	public $picto = 'ticket';
66
67
68
	/**
69
	 * @var string Hash to identify ticket publically
70
	 */
71
	public $track_id;
72
73
	/**
74
	 * @var int Thirdparty ID
75
	 */
76
	public $fk_soc;
77
78
	/**
79
	 * @var int Project ID
80
	 */
81
	public $fk_project;
82
83
	/**
84
	 * @var string Person email who have create ticket
85
	 */
86
	public $origin_email;
87
88
	/**
89
	 * @var int User id who have create ticket
90
	 */
91
	public $fk_user_create;
92
93
	/**
94
	 * @var int User id who have ticket assigned
95
	 */
96
	public $fk_user_assign;
97
98
	/**
99
	 * var string Ticket subject
100
	 */
101
	public $subject;
102
103
	/**
104
	 * @var string Ticket message
105
	 */
106
	public $message;
107
108
	/**
109
	 * @var int  Ticket statut
110
	 */
111
	public $fk_statut;
112
113
	/**
114
	 * @var string State resolution
115
	 */
116
	public $resolution;
117
118
	/**
119
	 * @var int Progress in percent
120
	 */
121
	public $progress;
122
123
	/**
124
	 * @var string Duration for ticket
125
	 */
126
	public $timing;
127
128
	/**
129
	 * @var string Type code
130
	 */
131
	public $type_code;
132
133
	/**
134
	 * @var string Category code
135
	 */
136
	public $category_code;
137
138
	/**
139
	 * @var string Severity code
140
	 */
141
	public $severity_code;
142
143
	/**
144
	 * @var int Création date
145
	 */
146
	public $datec = '';
147
148
	/**
149
	 * @var int Read date
150
	 */
151
	public $date_read = '';
152
153
	/**
154
	 * @var int Close ticket date
155
	 */
156
	public $date_close = '';
157
158
	/**
159
	 * @var array cache_types_tickets
160
	 */
161
	public $cache_types_tickets;
162
163
	/**
164
	 * @var array tickets categories
165
	 */
166
	public $cache_category_tickets;
167
168
	/**
169
	 * @var int Notify tiers at create
170
	 */
171
	public $notify_tiers_at_create;
172
173
	public $lines;
174
175
	/**
176
	 * @var string Regex pour les images
177
	 */
178
	public $regeximgext = '\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff';
179
180
	public $fields = array(
181
		'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'position'=>1, 'visible'=>-2, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id"),
182
		'entity' => array('type'=>'integer', 'label'=>'Entity', 'visible'=>0, 'enabled'=>1, 'position'=>5, 'notnull'=>1, 'index'=>1),
183
		'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object", 'css'=>''),
184
		'track_id' => array('type'=>'varchar(255)', 'label'=>'TicketTrackId', 'visible'=>-2, 'enabled'=>1, 'position'=>11, 'notnull'=>-1, 'searchall'=>1, 'help'=>"Help text"),
185
		'fk_user_create' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Author', 'visible'=>1, 'enabled'=>1, 'position'=>15, 'notnull'=>1, 'css'=>'tdoverflowmax150 maxwidth150onsmartphone'),
186
		'origin_email' => array('type'=>'mail', 'label'=>'OriginEmail', 'visible'=>-2, 'enabled'=>1, 'position'=>16, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object", 'css'=>'tdoverflowmax150'),
187
		'subject' => array('type'=>'varchar(255)', 'label'=>'Subject', 'visible'=>1, 'enabled'=>1, 'position'=>18, 'notnull'=>-1, 'searchall'=>1, 'help'=>"", 'css'=>'maxwidth75'),
188
		'type_code' => array('type'=>'varchar(32)', 'label'=>'Type', 'visible'=>1, 'enabled'=>1, 'position'=>20, 'notnull'=>-1, 'searchall'=>1, 'help'=>"", 'css'=>'maxwidth100'),
189
		'category_code' => array('type'=>'varchar(32)', 'label'=>'TicketGroup', 'visible'=>-1, 'enabled'=>1, 'position'=>21, 'notnull'=>-1, 'help'=>"", 'css'=>'maxwidth100'),
190
		'severity_code' => array('type'=>'varchar(32)', 'label'=>'Severity', 'visible'=>1, 'enabled'=>1, 'position'=>22, 'notnull'=>-1, 'help'=>"", 'css'=>'maxwidth100'),
191
		'fk_soc' => array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'visible'=>1, 'enabled'=>1, 'position'=>50, 'notnull'=>-1, 'index'=>1, 'searchall'=>1, 'help'=>"LinkToThirparty", 'css'=>'tdoverflowmax150 maxwidth150onsmartphone'),
192
		'notify_tiers_at_create' => array('type'=>'integer', 'label'=>'NotifyThirdparty', 'visible'=>-1, 'enabled'=>0, 'position'=>51, 'notnull'=>1, 'index'=>1),
193
		'fk_project' => array('type'=>'integer:Project:projet/class/project.class.php', 'label'=>'Project', 'visible'=>-1, 'enabled'=>1, 'position'=>52, 'notnull'=>-1, 'index'=>1, 'help'=>"LinkToProject"),
194
		'timing' => array('type'=>'varchar(20)', 'label'=>'Timing', 'visible'=>-1, 'enabled'=>1, 'position'=>42, 'notnull'=>-1, 'help'=>""),
195
		'datec' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>1, 'enabled'=>1, 'position'=>500, 'notnull'=>1),
196
		'date_read' => array('type'=>'datetime', 'label'=>'TicketReadOn', 'visible'=>1, 'enabled'=>1, 'position'=>501, 'notnull'=>1),
197
		'fk_user_assign' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'AssignedTo', 'visible'=>1, 'enabled'=>1, 'position'=>505, 'notnull'=>1),
198
		'date_close' => array('type'=>'datetime', 'label'=>'TicketCloseOn', 'visible'=>-1, 'enabled'=>1, 'position'=>510, 'notnull'=>1),
199
		'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-1, 'enabled'=>1, 'position'=>520, 'notnull'=>1),
200
		'message' => array('type'=>'text', 'label'=>'Message', 'visible'=>-2, 'enabled'=>1, 'position'=>540, 'notnull'=>-1,),
201
		'progress' => array('type'=>'varchar(100)', 'label'=>'Progression', 'visible'=>-1, 'enabled'=>1, 'position'=>540, 'notnull'=>-1, 'css'=>'right', 'help'=>"", 'isameasure'=>1),
202
		'resolution' => array('type'=>'integer', 'label'=>'Resolution', 'visible'=>-1, 'enabled'=>1, 'position'=>550, 'notnull'=>1),
203
		'fk_statut' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>600, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array(0 => 'Unread', 1 => 'Read', 3 => 'Answered', 4 => 'Assigned', 5 => 'InProgress', 6 => 'Waiting', 8 => 'Closed', 9 => 'Deleted')),
204
		'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>900),
205
	);
206
207
	/**
208
	 * Status
209
	 */
210
	const STATUS_NOT_READ = 0;
211
	const STATUS_READ = 1;
212
	const STATUS_ASSIGNED = 2;
213
	const STATUS_IN_PROGRESS = 3;
214
	const STATUS_NEED_MORE_INFO = 5;
215
	const STATUS_WAITING = 7;
216
	const STATUS_CLOSED = 8;
217
	const STATUS_CANCELED = 9;
218
219
220
	/**
221
	 *  Constructor
222
	 *
223
	 *  @param DoliDb $db Database handler
224
	 */
225
	public function __construct($db)
226
	{
227
		$this->db = $db;
228
229
		$this->statuts_short = array(self::STATUS_NOT_READ => 'Unread', self::STATUS_READ => 'Read', self::STATUS_ASSIGNED => 'Assigned', self::STATUS_IN_PROGRESS => 'InProgress', self::STATUS_NEED_MORE_INFO => 'NeedMoreInformation', self::STATUS_WAITING => 'Suspended', self::STATUS_CLOSED => 'Closed', self::STATUS_CANCELED => 'Canceled');
230
		$this->statuts       = array(self::STATUS_NOT_READ => 'Unread', self::STATUS_READ => 'Read', self::STATUS_ASSIGNED => 'Assigned', self::STATUS_IN_PROGRESS => 'InProgress', self::STATUS_NEED_MORE_INFO => 'NeedMoreInformation', self::STATUS_WAITING => 'Suspended', self::STATUS_CLOSED => 'Closed', self::STATUS_CANCELED => 'Canceled');
231
	}
232
233
	/**
234
	 *    Check properties of ticket are ok (like ref, track_id, ...).
235
	 *    All properties must be already loaded on object (this->ref, this->track_id, ...).
236
	 *
237
	 *    @return int        0 if OK, <0 if KO
238
	 */
239
	private function verify()
240
	{
241
		$this->errors = array();
242
243
		$result = 0;
244
245
		// Clean parameters
246
		if (isset($this->ref)) {
247
			$this->ref = trim($this->ref);
248
		}
249
250
		if (isset($this->track_id)) {
251
			$this->track_id = trim($this->track_id);
252
		}
253
254
		if (isset($this->fk_soc)) {
255
			$this->fk_soc = (int) $this->fk_soc;
256
		}
257
258
		if (isset($this->fk_project)) {
259
			$this->fk_project = (int) $this->fk_project;
260
		}
261
262
		if (isset($this->origin_email)) {
263
			$this->origin_email = trim($this->origin_email);
264
		}
265
266
		if (isset($this->fk_user_create)) {
267
			$this->fk_user_create = (int) $this->fk_user_create;
268
		}
269
270
		if (isset($this->fk_user_assign)) {
271
			$this->fk_user_assign = (int) $this->fk_user_assign;
272
		}
273
274
		if (isset($this->subject)) {
275
			$this->subject = trim($this->subject);
276
		}
277
278
		if (isset($this->message)) {
279
			$this->message = trim($this->message);
280
		}
281
282
		if (isset($this->fk_statut)) {
283
			$this->fk_statut = (int) $this->fk_statut;
284
		}
285
286
		if (isset($this->resolution)) {
287
			$this->resolution = trim($this->resolution);
288
		}
289
290
		if (isset($this->progress)) {
291
			$this->progress = trim($this->progress);
292
		}
293
294
		if (isset($this->timing)) {
295
			$this->timing = trim($this->timing);
296
		}
297
298
		if (isset($this->type_code)) {
299
			$this->type_code = trim($this->type_code);
300
		}
301
302
		if (isset($this->category_code)) {
303
			$this->category_code = trim($this->category_code);
304
		}
305
306
		if (isset($this->severity_code)) {
307
			$this->severity_code = trim($this->severity_code);
308
		}
309
310
		if (empty($this->ref)) {
311
			$this->errors[] = 'ErrorTicketRefRequired';
312
			dol_syslog(get_class($this)."::create error -1 ref null", LOG_ERR);
313
			$result = -1;
314
		}
315
316
		return $result;
317
	}
318
319
	/**
320
	 *  Create object into database
321
	 *
322
	 *  @param  User $user      User that creates
323
	 *  @param  int  $notrigger 0=launch triggers after, 1=disable triggers
324
	 *  @return int                      <0 if KO, Id of created object if OK
325
	 */
326
	public function create($user, $notrigger = 0)
327
	{
328
		global $conf, $langs;
329
		$error = 0;
330
331
		// Clean parameters
332
		$this->datec = dol_now();
333
		if (empty($this->track_id)) $this->track_id = generate_random_id(16);
334
335
		// Check more parameters
336
		// If error, this->errors[] is filled
337
		$result = $this->verify();
338
339
		if ($result >= 0) {
340
			// Insert request
341
			$sql = "INSERT INTO ".MAIN_DB_PREFIX."ticket(";
342
			$sql .= "ref,";
343
			$sql .= "track_id,";
344
			$sql .= "fk_soc,";
345
			$sql .= "fk_project,";
346
			$sql .= "origin_email,";
347
			$sql .= "fk_user_create,";
348
			$sql .= "fk_user_assign,";
349
			$sql .= "subject,";
350
			$sql .= "message,";
351
			$sql .= "fk_statut,";
352
			$sql .= "resolution,";
353
			$sql .= "progress,";
354
			$sql .= "timing,";
355
			$sql .= "type_code,";
356
			$sql .= "category_code,";
357
			$sql .= "severity_code,";
358
			$sql .= "datec,";
359
			$sql .= "date_read,";
360
			$sql .= "date_close,";
361
			$sql .= "entity,";
362
			$sql .= "notify_tiers_at_create";
363
			$sql .= ") VALUES (";
364
			$sql .= " ".(!isset($this->ref) ? '' : "'".$this->db->escape($this->ref)."'").",";
365
			$sql .= " ".(!isset($this->track_id) ? 'NULL' : "'".$this->db->escape($this->track_id)."'").",";
366
			$sql .= " ".($this->fk_soc > 0 ? $this->db->escape($this->fk_soc) : "null").",";
367
			$sql .= " ".($this->fk_project > 0 ? $this->db->escape($this->fk_project) : "null").",";
368
			$sql .= " ".(!isset($this->origin_email) ? 'NULL' : "'".$this->db->escape($this->origin_email)."'").",";
369
			$sql .= " ".($this->fk_user_create > 0 ? $this->fk_user_create : ($user->id > 0 ? $user->id : 'NULL')).",";
370
			$sql .= " ".($this->fk_user_assign > 0 ? $this->fk_user_assign : 'NULL').",";
371
			$sql .= " ".(!isset($this->subject) ? 'NULL' : "'".$this->db->escape($this->subject)."'").",";
372
			$sql .= " ".(!isset($this->message) ? 'NULL' : "'".$this->db->escape($this->message)."'").",";
373
			$sql .= " ".(!isset($this->fk_statut) ? '0' : "'".$this->db->escape($this->fk_statut)."'").",";
374
			$sql .= " ".(!isset($this->resolution) ? 'NULL' : "'".$this->db->escape($this->resolution)."'").",";
375
			$sql .= " ".(!isset($this->progress) ? '0' : "'".$this->db->escape($this->progress)."'").",";
376
			$sql .= " ".(!isset($this->timing) ? 'NULL' : "'".$this->db->escape($this->timing)."'").",";
377
			$sql .= " ".(!isset($this->type_code) ? 'NULL' : "'".$this->db->escape($this->type_code)."'").",";
378
			$sql .= " ".(!isset($this->category_code) ? 'NULL' : "'".$this->db->escape($this->category_code)."'").",";
379
			$sql .= " ".(!isset($this->severity_code) ? 'NULL' : "'".$this->db->escape($this->severity_code)."'").",";
380
			$sql .= " ".(!isset($this->datec) || dol_strlen($this->datec) == 0 ? 'NULL' : "'".$this->db->idate($this->datec)."'").",";
381
			$sql .= " ".(!isset($this->date_read) || dol_strlen($this->date_read) == 0 ? 'NULL' : "'".$this->db->idate($this->date_read)."'").",";
382
			$sql .= " ".(!isset($this->date_close) || dol_strlen($this->date_close) == 0 ? 'NULL' : "'".$this->db->idate($this->date_close)."'")."";
383
			$sql .= ", ".$conf->entity;
384
			$sql .= ", ".(!isset($this->notify_tiers_at_create) ? '1' : "'".$this->db->escape($this->notify_tiers_at_create)."'");
385
			$sql .= ")";
386
387
			$this->db->begin();
388
389
			dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG);
390
			$resql = $this->db->query($sql);
391
			if (!$resql) {
392
				$error++;
393
				$this->errors[] = "Error ".$this->db->lasterror();
394
			}
395
396
			if (!$error) {
397
				$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."ticket");
398
399
				if (!$notrigger) {
400
					// Call trigger
401
					$result = $this->call_trigger('TICKET_CREATE', $user);
402
					if ($result < 0) {
403
						$error++;
404
					}
405
					// End call triggers
406
				}
407
			}
408
409
			//Update extrafield
410
			if (!$error) {
411
				$result = $this->insertExtraFields();
412
				if ($result < 0) {
413
					$error++;
414
				}
415
			}
416
417
			// Commit or rollback
418
			if ($error) {
419
				foreach ($this->errors as $errmsg) {
420
					dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
421
					$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
422
				}
423
				$this->db->rollback();
424
				return -1 * $error;
425
			} else {
426
				$this->db->commit();
427
				return $this->id;
428
			}
429
		} else {
430
			$this->db->rollback();
431
			dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
432
			return -3;
433
		}
434
	}
435
436
	/**
437
	 *  Load object in memory from the database
438
	 *
439
	 *  @param  int        	$id    		Id object
440
	 *  @param	string		$ref		Ref
441
	 *  @param	string		$track_id	Track id, a hash like ref
442
	 *  @return int              		<0 if KO, >0 if OK
443
	 */
444
	public function fetch($id = '', $ref = '', $track_id = '')
445
	{
446
		global $langs;
447
448
		// Check parameters
449
		if (!$id && !$track_id && !$ref) {
450
			$this->error = 'ErrorWrongParameters';
451
			dol_print_error(get_class($this)."::fetch ".$this->error);
452
			return -1;
453
		}
454
455
		$sql = "SELECT";
456
		$sql .= " t.rowid,";
457
		$sql .= " t.ref,";
458
		$sql .= " t.track_id,";
459
		$sql .= " t.fk_soc,";
460
		$sql .= " t.fk_project,";
461
		$sql .= " t.origin_email,";
462
		$sql .= " t.fk_user_create,";
463
		$sql .= " t.fk_user_assign,";
464
		$sql .= " t.subject,";
465
		$sql .= " t.message,";
466
		$sql .= " t.fk_statut,";
467
		$sql .= " t.resolution,";
468
		$sql .= " t.progress,";
469
		$sql .= " t.timing,";
470
		$sql .= " t.type_code,";
471
		$sql .= " t.category_code,";
472
		$sql .= " t.severity_code,";
473
		$sql .= " t.datec,";
474
		$sql .= " t.date_read,";
475
		$sql .= " t.date_close,";
476
		$sql .= " t.tms";
477
		$sql .= ", type.code as type_code, type.label as type_label, category.code as category_code, category.label as category_label, severity.code as severity_code, severity.label as severity_label";
478
		$sql .= " FROM ".MAIN_DB_PREFIX."ticket as t";
479
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_type as type ON type.code=t.type_code";
480
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_category as category ON category.code=t.category_code";
481
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_severity as severity ON severity.code=t.severity_code";
482
483
		if ($id) {
484
			$sql .= " WHERE t.rowid = ".$this->db->escape($id);
485
		} else {
486
			$sql .= " WHERE t.entity IN (".getEntity($this->element, 1).")";
487
			if ($track_id) {
488
				$sql .= " AND t.track_id = '".$this->db->escape($track_id)."'";
489
			} elseif ($ref) {
490
				$sql .= " AND t.ref = '".$this->db->escape($ref)."'";
491
			}
492
		}
493
494
		dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
495
		$resql = $this->db->query($sql);
496
		if ($resql) {
497
			if ($this->db->num_rows($resql))
498
			{
499
				$obj = $this->db->fetch_object($resql);
500
501
				$this->id = $obj->rowid;
502
				$this->ref = $obj->ref;
503
				$this->track_id = $obj->track_id;
504
				$this->fk_soc = $obj->fk_soc;
505
				$this->socid = $obj->fk_soc; // for fetch_thirdparty() method
506
				$this->fk_project = $obj->fk_project;
507
				$this->origin_email = $obj->origin_email;
508
				$this->fk_user_create = $obj->fk_user_create;
509
				$this->fk_user_assign = $obj->fk_user_assign;
510
				$this->subject = $obj->subject;
511
				$this->message = $obj->message;
512
				$this->fk_statut = $obj->fk_statut;
513
				$this->resolution = $obj->resolution;
514
				$this->progress = $obj->progress;
515
				$this->timing = $obj->timing;
516
517
				$this->type_code = $obj->type_code;
518
				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
519
				$label_type = ($langs->trans("TicketTypeShort".$obj->type_code) != ("TicketTypeShort".$obj->type_code) ? $langs->trans("TicketTypeShort".$obj->type_code) : ($obj->type_label != '-' ? $obj->type_label : ''));
520
				$this->type_label = $label_type;
521
522
				$this->category_code = $obj->category_code;
523
				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
524
				$label_category = ($langs->trans("TicketCategoryShort".$obj->category_code) != ("TicketCategoryShort".$obj->category_code) ? $langs->trans("TicketCategoryShort".$obj->category_code) : ($obj->category_label != '-' ? $obj->category_label : ''));
525
				$this->category_label = $label_category;
526
527
				$this->severity_code = $obj->severity_code;
528
				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
529
				$label_severity = ($langs->trans("TicketSeverityShort".$obj->severity_code) != ("TicketSeverityShort".$obj->severity_code) ? $langs->trans("TicketSeverityShort".$obj->severity_code) : ($obj->severity_label != '-' ? $obj->severity_label : ''));
530
				$this->severity_label = $label_severity;
531
532
				$this->datec = $this->db->jdate($obj->datec);
533
				$this->date_creation = $this->db->jdate($obj->datec);
534
				$this->date_read = $this->db->jdate($obj->date_read);
535
				$this->date_validation = $this->db->jdate($obj->date_read);
536
				$this->date_close = $this->db->jdate($obj->date_close);
537
				$this->tms = $this->db->jdate($obj->tms);
538
				$this->date_modification = $this->db->jdate($obj->tms);
539
540
				$this->fetch_optionals();
541
542
				$this->db->free($resql);
543
				return 1;
544
			}
545
			else
546
			{
547
				return 0;
548
			}
549
		} else {
550
			$this->error = "Error ".$this->db->lasterror();
551
			dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
552
			return -1;
553
		}
554
	}
555
556
	/**
557
	 * Load all objects in memory from database
558
	 *
559
	 * @param  User   $user      User for action
560
	 * @param  string $sortorder Sort order
561
	 * @param  string $sortfield Sort field
562
	 * @param  int    $limit     page number
563
	 * @param  int    $offset    Offset for query
564
	 * @param  int    $arch      archive or not (not used)
565
	 * @param  array  $filter    Filter for query
566
	 *                           output
567
	 * @return int <0 if KO, >0 if OK
568
	 */
569
	public function fetchAll($user, $sortorder = 'ASC', $sortfield = 't.datec', $limit = '', $offset = 0, $arch = '', $filter = '')
570
	{
571
		global $langs;
572
573
		$extrafields = new ExtraFields($this->db);
574
575
		// fetch optionals attributes and labels
576
		$extrafields->fetch_name_optionals_label($this->table_element);
577
578
		$sql = "SELECT";
579
		$sql .= " t.rowid,";
580
		$sql .= " t.ref,";
581
		$sql .= " t.track_id,";
582
		$sql .= " t.fk_soc,";
583
		$sql .= " t.fk_project,";
584
		$sql .= " t.origin_email,";
585
		$sql .= " t.fk_user_create, uc.lastname as user_create_lastname, uc.firstname as user_create_firstname,";
586
		$sql .= " t.fk_user_assign, ua.lastname as user_assign_lastname, ua.firstname as user_assign_firstname,";
587
		$sql .= " t.subject,";
588
		$sql .= " t.message,";
589
		$sql .= " t.fk_statut,";
590
		$sql .= " t.resolution,";
591
		$sql .= " t.progress,";
592
		$sql .= " t.timing,";
593
		$sql .= " t.type_code,";
594
		$sql .= " t.category_code,";
595
		$sql .= " t.severity_code,";
596
		$sql .= " t.datec,";
597
		$sql .= " t.date_read,";
598
		$sql .= " t.date_close,";
599
		$sql .= " t.tms";
600
		$sql .= ", type.label as type_label, category.label as category_label, severity.label as severity_label";
601
		// Add fields for extrafields
602
		foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
603
			$sql .= ($extrafields->attributes[$this->table_element]['type'][$key] != 'separate' ? ",ef.".$key.' as options_'.$key : '');
604
		}
605
		$sql .= " FROM ".MAIN_DB_PREFIX."ticket as t";
606
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_type as type ON type.code=t.type_code";
607
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_category as category ON category.code=t.category_code";
608
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_severity as severity ON severity.code=t.severity_code";
609
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid=t.fk_soc";
610
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as uc ON uc.rowid=t.fk_user_create";
611
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as ua ON ua.rowid=t.fk_user_assign";
612
		if (is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label'])) {
613
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."ticket_extrafields as ef on (t.rowid = ef.fk_object)";
614
		}
615
		if (!$user->rights->societe->client->voir && !$user->socid) {
616
			$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
617
		}
618
619
		$sql .= " WHERE t.entity IN (".getEntity('ticket').")";
620
621
		// Manage filter
622
		if (!empty($filter)) {
623
			foreach ($filter as $key => $value) {
624
				if (strpos($key, 'date')) { // To allow $filter['YEAR(s.dated)']=>$year
625
					$sql .= ' AND '.$key.' = \''.$value.'\'';
626
				} elseif (($key == 't.fk_user_assign') || ($key == 't.type_code') || ($key == 't.category_code') || ($key == 't.severity_code') || ($key == 't.fk_soc')) {
627
					$sql .= " AND ".$key." = '".$this->db->escape($value)."'";
628
				} elseif ($key == 't.fk_statut') {
629
					if (is_array($value) && count($value) > 0) {
630
						$sql .= 'AND '.$key.' IN ('.implode(',', $value).')';
631
					} else {
632
						$sql .= ' AND '.$key.' = '.$this->db->escape($value);
633
					}
634
				} else {
635
					$sql .= ' AND '.$key.' LIKE \'%'.$value.'%\'';
636
				}
637
			}
638
		}
639
		if (!$user->rights->societe->client->voir && !$user->socid) {
640
			$sql .= " AND t.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id;
641
		} elseif ($user->socid) {
642
			$sql .= " AND t.fk_soc = ".$user->socid;
643
		}
644
645
		$sql .= " ORDER BY ".$sortfield.' '.$sortorder;
646
		if (!empty($limit)) {
647
			$sql .= ' '.$this->db->plimit($limit + 1, $offset);
648
		}
649
650
		dol_syslog(get_class($this)."::fetch_all sql=".$sql, LOG_DEBUG);
651
		$resql = $this->db->query($sql);
652
653
		if ($resql) {
654
			$this->lines = array();
655
656
			$num = $this->db->num_rows($resql);
657
			$i = 0;
658
659
			if ($num) {
660
				while ($i < $num) {
661
					$obj = $this->db->fetch_object($resql);
662
663
					$line = new TicketsLine();
664
665
					$line->id = $obj->rowid;
666
					$line->rowid = $obj->rowid;
667
					$line->ref = $obj->ref;
668
					$line->track_id = $obj->track_id;
669
					$line->fk_soc = $obj->fk_soc;
670
					$line->fk_project = $obj->fk_project;
671
					$line->origin_email = $obj->origin_email;
672
673
					$line->fk_user_create = $obj->fk_user_create;
674
					$line->user_create_lastname = $obj->user_create_lastname;
675
					$line->user_create_firstname = $obj->user_create_firstname;
676
677
					$line->fk_user_assign = $obj->fk_user_assign;
678
					$line->user_assign_lastname = $obj->user_assign_lastname;
679
					$line->user_assign_firstname = $obj->user_assign_firstname;
680
681
					$line->subject = $obj->subject;
682
					$line->message = $obj->message;
683
					$line->fk_statut = $obj->fk_statut;
684
					$line->resolution = $obj->resolution;
685
					$line->progress = $obj->progress;
686
					$line->timing = $obj->timing;
687
688
					// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
689
					$label_type = ($langs->trans("TicketTypeShort".$obj->type_code) != ("TicketTypeShort".$obj->type_code) ? $langs->trans("TicketTypeShort".$obj->type_code) : ($obj->type_label != '-' ? $obj->type_label : ''));
690
					$line->type_label = $label_type;
691
692
					$this->category_code = $obj->category_code;
693
					// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
694
					$label_category = ($langs->trans("TicketCategoryShort".$obj->category_code) != ("TicketCategoryShort".$obj->category_code) ? $langs->trans("TicketCategoryShort".$obj->category_code) : ($obj->category_label != '-' ? $obj->category_label : ''));
695
					$line->category_label = $label_category;
696
697
					$this->severity_code = $obj->severity_code;
698
					// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
699
					$label_severity = ($langs->trans("TicketSeverityShort".$obj->severity_code) != ("TicketSeverityShort".$obj->severity_code) ? $langs->trans("TicketSeverityShort".$obj->severity_code) : ($obj->severity_label != '-' ? $obj->severity_label : ''));
700
					$line->severity_label = $label_severity;
701
702
					$line->datec = $this->db->jdate($obj->datec);
703
					$line->date_read = $this->db->jdate($obj->date_read);
704
					$line->date_close = $this->db->jdate($obj->date_close);
705
706
					// Extra fields
707
					if (is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label'])) {
708
						foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
709
							$tmpkey = 'options_'.$key;
710
							$line->{$tmpkey} = $obj->$tmpkey;
711
						}
712
					}
713
714
					$this->lines[$i] = $line;
715
					$i++;
716
				}
717
			}
718
			$this->db->free($resql);
719
			return $num;
720
		} else {
721
			$this->error = "Error ".$this->db->lasterror();
722
			dol_syslog(get_class($this)."::fetch_all ".$this->error, LOG_ERR);
723
			return -1;
724
		}
725
	}
726
727
	/**
728
	 *  Update object into database
729
	 *
730
	 *  @param  User $user      User that modifies
731
	 *  @param  int  $notrigger 0=launch triggers after, 1=disable triggers
732
	 *  @return int                     <0 if KO, >0 if OK
733
	 */
734
	public function update($user = 0, $notrigger = 0)
735
	{
736
		global $conf, $langs, $hookmanager;
737
		$error = 0;
738
739
		// Clean parameters
740
		if (isset($this->ref)) {
741
			$this->ref = trim($this->ref);
742
		}
743
744
		if (isset($this->track_id)) {
745
			$this->track_id = trim($this->track_id);
746
		}
747
748
		if (isset($this->fk_soc)) {
749
			$this->fk_soc = (int) $this->fk_soc;
750
		}
751
752
		if (isset($this->fk_project)) {
753
			$this->fk_project = (int) $this->fk_project;
754
		}
755
756
		if (isset($this->origin_email)) {
757
			$this->origin_email = trim($this->origin_email);
758
		}
759
760
		if (isset($this->fk_user_create)) {
761
			$this->fk_user_create = (int) $this->fk_user_create;
762
		}
763
764
		if (isset($this->fk_user_assign)) {
765
			$this->fk_user_assign = (int) $this->fk_user_assign;
766
		}
767
768
		if (isset($this->subject)) {
769
			$this->subject = trim($this->subject);
770
		}
771
772
		if (isset($this->message)) {
773
			$this->message = trim($this->message);
774
		}
775
776
		if (isset($this->fk_statut)) {
777
			$this->fk_statut = (int) $this->fk_statut;
778
		}
779
780
		if (isset($this->resolution)) {
781
			$this->resolution = trim($this->resolution);
782
		}
783
784
		if (isset($this->progress)) {
785
			$this->progress = trim($this->progress);
786
		}
787
788
		if (isset($this->timing)) {
789
			$this->timing = trim($this->timing);
790
		}
791
792
		if (isset($this->type_code)) {
793
			$this->timing = trim($this->type_code);
794
		}
795
796
		if (isset($this->category_code)) {
797
			$this->timing = trim($this->category_code);
798
		}
799
800
		if (isset($this->severity_code)) {
801
			$this->timing = trim($this->severity_code);
802
		}
803
804
		// Check parameters
805
		// Put here code to add a control on parameters values
806
		// Update request
807
		$sql = "UPDATE ".MAIN_DB_PREFIX."ticket SET";
808
		$sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "").",";
809
		$sql .= " track_id=".(isset($this->track_id) ? "'".$this->db->escape($this->track_id)."'" : "null").",";
810
		$sql .= " fk_soc=".(isset($this->fk_soc) ? "'".$this->db->escape($this->fk_soc)."'" : "null").",";
811
		$sql .= " fk_project=".(isset($this->fk_project) ? "'".$this->db->escape($this->fk_project)."'" : "null").",";
812
		$sql .= " origin_email=".(isset($this->origin_email) ? "'".$this->db->escape($this->origin_email)."'" : "null").",";
813
		$sql .= " fk_user_create=".(isset($this->fk_user_create) ? $this->fk_user_create : "null").",";
814
		$sql .= " fk_user_assign=".(isset($this->fk_user_assign) ? $this->fk_user_assign : "null").",";
815
		$sql .= " subject=".(isset($this->subject) ? "'".$this->db->escape($this->subject)."'" : "null").",";
816
		$sql .= " message=".(isset($this->message) ? "'".$this->db->escape($this->message)."'" : "null").",";
817
		$sql .= " fk_statut=".(isset($this->fk_statut) ? $this->fk_statut : "null").",";
818
		$sql .= " resolution=".(isset($this->resolution) ? $this->resolution : "null").",";
819
		$sql .= " progress=".(isset($this->progress) ? "'".$this->db->escape($this->progress)."'" : "null").",";
820
		$sql .= " timing=".(isset($this->timing) ? "'".$this->db->escape($this->timing)."'" : "null").",";
821
		$sql .= " type_code=".(isset($this->type_code) ? "'".$this->db->escape($this->type_code)."'" : "null").",";
822
		$sql .= " category_code=".(isset($this->category_code) ? "'".$this->db->escape($this->category_code)."'" : "null").",";
823
		$sql .= " severity_code=".(isset($this->severity_code) ? "'".$this->db->escape($this->severity_code)."'" : "null").",";
824
		$sql .= " datec=".(dol_strlen($this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').",";
825
		$sql .= " date_read=".(dol_strlen($this->date_read) != 0 ? "'".$this->db->idate($this->date_read)."'" : 'null').",";
826
		$sql .= " date_close=".(dol_strlen($this->date_close) != 0 ? "'".$this->db->idate($this->date_close)."'" : 'null')."";
827
		$sql .= " WHERE rowid=".$this->id;
828
829
		$this->db->begin();
830
831
		$resql = $this->db->query($sql);
832
		if (!$resql) {
833
			$error++;
834
			$this->errors[] = "Error ".$this->db->lasterror();
835
		}
836
837
		if (!$error) {
838
			// Update extrafields
839
			$result = $this->insertExtraFields();
840
			if ($result < 0) {
841
				$error++;
842
			}
843
		}
844
845
		if (!$error && !$notrigger) {
846
			// Call trigger
847
			$result = $this->call_trigger('TICKET_MODIFY', $user);
848
			if ($result < 0) {
849
				$error++;
850
			}
851
			  // End call triggers
852
		}
853
854
		// Commit or rollback
855
		if ($error) {
856
			foreach ($this->errors as $errmsg) {
857
				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
858
				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
859
			}
860
			$this->db->rollback();
861
			return -1 * $error;
862
		} else {
863
			$this->db->commit();
864
			return 1;
865
		}
866
	}
867
868
	/**
869
	 *  Delete object in database
870
	 *
871
	 *     @param  User $user      User that deletes
872
	 *  @param  int  $notrigger 0=launch triggers after, 1=disable triggers
873
	 *  @return int                     <0 if KO, >0 if OK
874
	 */
875
	public function delete($user, $notrigger = 0)
876
	{
877
		global $conf, $langs;
878
		$error = 0;
879
880
		$this->db->begin();
881
882
		if (!$error) {
883
			if (!$notrigger) {
884
				// Call trigger
885
				$result = $this->call_trigger('TICKET_DELETE', $user);
886
				if ($result < 0) {
887
					$error++;
888
				}
889
				// End call triggers
890
			}
891
		}
892
893
		if (!$error) {
894
			// Delete linked contacts
895
			$res = $this->delete_linked_contact();
896
			if ($res < 0) {
897
				dol_syslog(get_class($this)."::delete error", LOG_ERR);
898
				$error++;
899
			}
900
		}
901
902
		if (!$error) {
903
			// Delete linked object
904
			$res = $this->deleteObjectLinked();
905
			if ($res < 0) $error++;
906
		}
907
908
		// Removed extrafields
909
		if (!$error) {
910
			$result = $this->deleteExtraFields();
911
			if ($result < 0) {
912
				$error++;
913
				dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
914
			}
915
		}
916
917
		if (!$error) {
918
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."ticket";
919
			$sql .= " WHERE rowid=".$this->id;
920
921
			dol_syslog(get_class($this)."::delete sql=".$sql);
922
			$resql = $this->db->query($sql);
923
			if (!$resql) {
924
				$error++;
925
				$this->errors[] = "Error ".$this->db->lasterror();
926
			}
927
		}
928
929
		// Commit or rollback
930
		if ($error) {
931
			foreach ($this->errors as $errmsg) {
932
				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
933
				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
934
			}
935
			$this->db->rollback();
936
			return -1 * $error;
937
		} else {
938
			$this->db->commit();
939
			return 1;
940
		}
941
	}
942
943
	/**
944
	 *     Load an object from its id and create a new one in database
945
	 *
946
	 *     @param   User    $user       User that clone
947
	 *     @param   int     $fromid     Id of object to clone
948
	 *     @return  int                 New id of clone
949
	 */
950
	public function createFromClone(User $user, $fromid)
951
	{
952
		$error = 0;
953
954
		$object = new Ticket($this->db);
955
956
		$this->db->begin();
957
958
		// Load source object
959
		$object->fetch($fromid);
960
		$object->id = 0;
961
		$object->statut = 0;
962
963
		// Clear fields
964
		// ...
965
		// Create clone
966
		$object->context['createfromclone'] = 'createfromclone';
967
		$result = $object->create($user);
968
969
		// Other options
970
		if ($result < 0) {
971
			$this->error = $object->error;
972
			$error++;
973
		}
974
975
		if (!$error) {
976
		}
977
978
		unset($object->context['createfromclone']);
979
980
		// End
981
		if (!$error) {
982
			$this->db->commit();
983
			return $object->id;
984
		} else {
985
			$this->db->rollback();
986
			return -1;
987
		}
988
	}
989
990
	/**
991
	 *     Initialise object with example values
992
	 *     Id must be 0 if object instance is a specimen
993
	 *
994
	 *     @return void
995
	 */
996
	public function initAsSpecimen()
997
	{
998
		$this->id = 0;
999
1000
		$this->ref = 'TI0501-001';
1001
		$this->track_id = 'XXXXaaaa';
1002
		$this->origin_email = '[email protected]';
1003
		$this->fk_project = 1;
1004
		$this->fk_user_create = 1;
1005
		$this->fk_user_assign = 1;
1006
		$this->subject = 'Subject of ticket';
1007
		$this->message = 'Message of ticket';
1008
		$this->fk_statut = 0;
1009
		$this->resolution = '1';
1010
		$this->progress = '10';
1011
		$this->timing = '30';
1012
		$this->type_code = 'TYPECODE';
1013
		$this->category_code = 'CATEGORYCODE';
1014
		$this->severity_code = 'SEVERITYCODE';
1015
		$this->datec = '';
1016
		$this->date_read = '';
1017
		$this->date_close = '';
1018
		$this->tms = '';
1019
	}
1020
1021
	/**
1022
	 * print selected status
1023
	 *
1024
	 * @param string    $selected   selected status
1025
	 * @return void
1026
	 */
1027
	public function printSelectStatus($selected = "")
1028
	{
1029
		print Form::selectarray('search_fk_statut', $this->statuts_short, $selected, $show_empty = 1, $key_in_label = 0, $value_as_key = 0, $option = '', $translate = 1, $maxlen = 0, $disabled = 0, $sort = '', $morecss = '');
1030
	}
1031
1032
1033
	/**
1034
	 *      Charge dans cache la liste des types de tickets (paramétrable dans dictionnaire)
1035
	 *
1036
	 *      @return int             Number of lines loaded, 0 if already loaded, <0 if KO
1037
	 */
1038
	public function loadCacheTypesTickets()
1039
	{
1040
		global $langs;
1041
1042
		if (!empty($this->cache_types_tickets) && count($this->cache_types_tickets)) {
1043
			return 0;
1044
		}
1045
		// Cache deja charge
1046
1047
		$sql = "SELECT rowid, code, label, use_default, pos, description";
1048
		$sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_type";
1049
		$sql .= " WHERE active > 0";
1050
		$sql .= " ORDER BY pos";
1051
		dol_syslog(get_class($this)."::load_cache_type_tickets sql=".$sql, LOG_DEBUG);
1052
		$resql = $this->db->query($sql);
1053
		if ($resql) {
1054
			$num = $this->db->num_rows($resql);
1055
			$i = 0;
1056
			while ($i < $num) {
1057
				$obj = $this->db->fetch_object($resql);
1058
				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
1059
				$label = ($langs->trans("TicketTypeShort".$obj->code) != ("TicketTypeShort".$obj->code) ? $langs->trans("TicketTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
1060
				$this->cache_types_tickets[$obj->rowid]['code'] = $obj->code;
1061
				$this->cache_types_tickets[$obj->rowid]['label'] = $label;
1062
				$this->cache_types_tickets[$obj->rowid]['use_default'] = $obj->use_default;
1063
				$this->cache_types_tickets[$obj->rowid]['pos'] = $obj->pos;
1064
				$i++;
1065
			}
1066
			return $num;
1067
		} else {
1068
			dol_print_error($this->db);
1069
			return -1;
1070
		}
1071
	}
1072
1073
	/**
1074
	 *      Charge dans cache la liste des catégories de tickets (paramétrable dans dictionnaire)
1075
	 *
1076
	 *      @return int             Number of lines loaded, 0 if already loaded, <0 if KO
1077
	 */
1078
	public function loadCacheCategoriesTickets()
1079
	{
1080
		global $langs;
1081
1082
		if (!empty($this->cache_category_ticket) && count($this->cache_category_tickets)) {
0 ignored issues
show
Bug introduced by
The property cache_category_ticket does not exist on Ticket. Did you mean cache_category_tickets?
Loading history...
1083
			return 0;
1084
		}
1085
		// Cache deja charge
1086
1087
		$sql = "SELECT rowid, code, label, use_default, pos, description";
1088
		$sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_category";
1089
		$sql .= " WHERE active > 0";
1090
		$sql .= " ORDER BY pos";
1091
		dol_syslog(get_class($this)."::load_cache_categories_tickets sql=".$sql, LOG_DEBUG);
1092
		$resql = $this->db->query($sql);
1093
		if ($resql) {
1094
			$num = $this->db->num_rows($resql);
1095
			$i = 0;
1096
			while ($i < $num) {
1097
				$obj = $this->db->fetch_object($resql);
1098
				$this->cache_category_tickets[$obj->rowid]['code'] = $obj->code;
1099
				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
1100
				$label = ($langs->trans("TicketCategoryShort".$obj->code) != ("TicketCategoryShort".$obj->code) ? $langs->trans("TicketCategoryShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
1101
				$this->cache_category_tickets[$obj->rowid]['label'] = $label;
1102
				$this->cache_category_tickets[$obj->rowid]['use_default'] = $obj->use_default;
1103
				$this->cache_category_tickets[$obj->rowid]['pos'] = $obj->pos;
1104
				$i++;
1105
			}
1106
			return $num;
1107
		} else {
1108
			dol_print_error($this->db);
1109
			return -1;
1110
		}
1111
	}
1112
1113
	/**
1114
	 *      Charge dans cache la liste des sévérité de tickets (paramétrable dans dictionnaire)
1115
	 *
1116
	 *      @return int             Number of lines loaded, 0 if already loaded, <0 if KO
1117
	 */
1118
	public function loadCacheSeveritiesTickets()
1119
	{
1120
		global $langs;
1121
1122
		if (!empty($this->cache_severity_tickets) && count($this->cache_severity_tickets)) {
1123
			return 0;
1124
		}
1125
		// Cache deja charge
1126
1127
		$sql = "SELECT rowid, code, label, use_default, pos, description";
1128
		$sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_severity";
1129
		$sql .= " WHERE active > 0";
1130
		$sql .= " ORDER BY pos";
1131
		dol_syslog(get_class($this)."::loadCacheSeveritiesTickets sql=".$sql, LOG_DEBUG);
1132
		$resql = $this->db->query($sql);
1133
		if ($resql) {
1134
			$num = $this->db->num_rows($resql);
1135
			$i = 0;
1136
			while ($i < $num) {
1137
				$obj = $this->db->fetch_object($resql);
1138
1139
				$this->cache_severity_tickets[$obj->rowid]['code'] = $obj->code;
1140
				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
1141
				$label = ($langs->trans("TicketSeverityShort".$obj->code) != ("TicketSeverityShort".$obj->code) ? $langs->trans("TicketSeverityShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
1142
				$this->cache_severity_tickets[$obj->rowid]['label'] = $label;
1143
				$this->cache_severity_tickets[$obj->rowid]['use_default'] = $obj->use_default;
1144
				$this->cache_severity_tickets[$obj->rowid]['pos'] = $obj->pos;
1145
				$i++;
1146
			}
1147
			return $num;
1148
		} else {
1149
			dol_print_error($this->db);
1150
			return -1;
1151
		}
1152
	}
1153
1154
1155
	/**
1156
	 * Return status label of object
1157
	 *
1158
	 * @param      int		$mode     0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
1159
	 * @return     string    			  Label
1160
	 */
1161
	public function getLibStatut($mode = 0)
1162
	{
1163
		return $this->libStatut($this->fk_statut, $mode);
1164
	}
1165
1166
1167
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1168
	/**
1169
	 *    Return status label of object
1170
	 *
1171
	 *    @param      string 	$status      Id status
1172
	 *    @param      int		$mode        0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
1173
	 *    @return     string     			 Label
1174
	 */
1175
	public function LibStatut($status, $mode = 0)
1176
	{
1177
		// phpcs:enable
1178
		global $langs;
1179
1180
		$labelStatus = $this->statuts[$status];
1181
		$labelStatusShort = $this->statuts_short[$status];
1182
1183
		if ($status == self::STATUS_NOT_READ) {
1184
			$statusType = 'status0';
1185
		}
1186
		elseif ($status == self::STATUS_READ) {
1187
			$statusType = 'status1';
1188
		}
1189
		elseif ($status == self::STATUS_ASSIGNED) {
1190
			$statusType = 'status3';
1191
		}
1192
		elseif ($status == self::STATUS_IN_PROGRESS) {
1193
			$statusType = 'status4';
1194
		}
1195
		elseif ($status == self::STATUS_WAITING) {
1196
			$statusType = 'status3';
1197
		}
1198
		elseif ($status == self::STATUS_NEED_MORE_INFO) {
1199
			$statusType = 'status9';
1200
		}
1201
		elseif ($status == self::STATUS_CANCELED) {
1202
			$statusType = 'status9';
1203
		}
1204
		elseif ($status == self::STATUS_CLOSED) {
1205
			$statusType = 'status6';
1206
		}
1207
		else {
1208
			$labelStatus = $langs->trans('Unknown');
1209
			$labelStatusShort = $langs->trans('Unknown');
1210
			$statusType = 'status0';
1211
			$mode = 0;
1212
		}
1213
1214
		return dolGetStatus($langs->trans($labelStatus), $langs->trans($labelStatusShort), '', $statusType, $mode);
1215
	}
1216
1217
1218
	/**
1219
	 *  Return a link to the object card (with optionaly the picto)
1220
	 *
1221
	 *	@param	int		$withpicto					Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
1222
	 *	@param	string	$option						On what the link point to ('nolink', ...)
1223
	 *  @param	int  	$notooltip					1=Disable tooltip
1224
	 *  @param  string  $morecss            		Add more css on link
1225
	 *  @param  int     $save_lastsearch_value    	-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1226
	 *	@return	string								String with URL
1227
	 */
1228
	public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
1229
	{
1230
		global $db, $conf, $langs;
1231
		global $dolibarr_main_authentication, $dolibarr_main_demo;
1232
		global $menumanager;
1233
1234
		if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
1235
1236
		$result = '';
1237
		$companylink = '';
1238
1239
		$label = '<u>'.$langs->trans("Ticket").'</u>';
1240
		$label .= '<br>';
1241
		$label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref.'<br>';
1242
		$label .= '<b>'.$langs->trans('TicketTrackId').':</b> '.$this->track_id.'<br>';
1243
		$label .= '<b>'.$langs->trans('Subject').':</b> '.$this->subject;
1244
1245
		$url = dol_buildpath('/ticket/card.php', 1).'?id='.$this->id;
1246
1247
		if ($option != 'nolink')
1248
		{
1249
			// Add param to save lastsearch_values or not
1250
			$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1251
			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
1252
			if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
1253
		}
1254
1255
		$linkclose = '';
1256
		if (empty($notooltip))
1257
		{
1258
			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1259
			{
1260
				$label = $langs->trans("ShowTicket");
1261
				$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1262
			}
1263
			$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
1264
			$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
1265
		}
1266
		else $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1267
1268
		$linkstart = '<a href="'.$url.'"';
1269
		$linkstart .= $linkclose.'>';
1270
		$linkend = '</a>';
1271
1272
		$result .= $linkstart;
1273
		if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1274
		if ($withpicto != 2) $result .= $this->ref;
1275
		$result .= $linkend;
1276
		//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
1277
1278
		return $result;
1279
	}
1280
1281
1282
	/**
1283
	 *    Mark a message as read
1284
	 *
1285
	 *    @param    User		$user			    Object user
1286
	 *    @param	  int			$notrigger		No trigger
1287
	 *    @return   int							      <0 if KO, >0 if OK
1288
	 */
1289
	public function markAsRead($user, $notrigger = 0)
1290
	{
1291
		global $conf, $langs;
1292
1293
		$error = 0;
1294
1295
		if ($this->statut != self::STATUS_CANCELED) { // no closed
1296
			$this->db->begin();
1297
1298
			$sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
1299
			$sql .= " SET fk_statut = ".Ticket::STATUS_READ.", date_read='".$this->db->idate(dol_now())."'";
1300
			$sql .= " WHERE rowid = ".$this->id;
1301
1302
			dol_syslog(get_class($this)."::markAsRead");
1303
			$resql = $this->db->query($sql);
1304
			if ($resql) {
1305
				$this->actionmsg = $langs->trans('TicketLogMesgReadBy', $this->ref, $user->getFullName($langs));
1306
				$this->actionmsg2 = $langs->trans('TicketLogMesgReadBy', $this->ref, $user->getFullName($langs));
1307
1308
				if (!$error && !$notrigger) {
1309
					// Call trigger
1310
					$result = $this->call_trigger('TICKET_MODIFY', $user);
1311
					if ($result < 0) {
1312
						$error++;
1313
					}
1314
					// End call triggers
1315
				}
1316
1317
				if (!$error) {
1318
					$this->db->commit();
1319
					return 1;
1320
				} else {
1321
					$this->db->rollback();
1322
					$this->error = join(',', $this->errors);
1323
					dol_syslog(get_class($this)."::markAsRead ".$this->error, LOG_ERR);
1324
					return -1;
1325
				}
1326
			} else {
1327
				$this->db->rollback();
1328
				$this->error = $this->db->lasterror();
1329
				dol_syslog(get_class($this)."::markAsRead ".$this->error, LOG_ERR);
1330
				return -1;
1331
			}
1332
		}
1333
	}
1334
1335
	/**
1336
	 *    Mark a message as read
1337
	 *
1338
	 *    @param    User	$user				Object user
1339
	 *    @param    int 	$id_assign_user		ID of user assigned
1340
	 *    @param    int 	$notrigger        	Disable trigger
1341
	 *    @return   int							<0 if KO, 0=Nothing done, >0 if OK
1342
	 */
1343
	public function assignUser($user, $id_assign_user, $notrigger = 0)
1344
	{
1345
		global $conf, $langs;
1346
1347
		$error = 0;
1348
		$this->db->begin();
1349
1350
		$this->oldcopy = dol_clone($this);
1351
1352
		$sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
1353
		if ($id_assign_user > 0)
1354
		{
1355
			$sql .= " SET fk_user_assign=".$id_assign_user.", fk_statut = ".Ticket::STATUS_ASSIGNED;
1356
		}
1357
		else
1358
		{
1359
			$sql .= " SET fk_user_assign=null, fk_statut = ".Ticket::STATUS_READ;
1360
		}
1361
		$sql .= " WHERE rowid = ".$this->id;
1362
1363
		dol_syslog(get_class($this)."::assignUser sql=".$sql);
1364
		$resql = $this->db->query($sql);
1365
		if ($resql)
1366
		{
1367
			$this->fk_user_assign = $id_assign_user; // May be used by trigger
1368
1369
			if (!$notrigger) {
1370
				// Call trigger
1371
				$result = $this->call_trigger('TICKET_ASSIGNED', $user);
1372
				if ($result < 0) {
1373
					$error++;
1374
				}
1375
				// End call triggers
1376
			}
1377
1378
			if (!$error) {
1379
				$this->db->commit();
1380
				return 1;
1381
			} else {
1382
				$this->db->rollback();
1383
				$this->error = join(',', $this->errors);
1384
				dol_syslog(get_class($this)."::assignUser ".$this->error, LOG_ERR);
1385
				return -1;
1386
			}
1387
		} else {
1388
			$this->db->rollback();
1389
			$this->error = $this->db->lasterror();
1390
			dol_syslog(get_class($this)."::assignUser ".$this->error, LOG_ERR);
1391
			return -1;
1392
		}
1393
	}
1394
1395
1396
	/**
1397
	 *  Send notification of changes by email
1398
	 *
1399
	 * 	@param  User   $user    		User that create
1400
	 * 	@param  string $message 		Log message
1401
	 * 	@return int                 	<0 if KO, >0 if OK (number of emails sent)
1402
	 */
1403
	private function sendLogByEmail($user, $message)
1404
	{
1405
		global $conf, $langs;
1406
1407
		$nb_sent = 0;
1408
1409
		$langs->load('ticket');
1410
1411
		// Retrieve email of all contacts (internal and external)
1412
		$contacts = $this->listeContact(-1, 'internal');
1413
		$contacts = array_merge($contacts, $this->listeContact(-1, 'external'));
1414
1415
		/* If origin_email and no socid, we add email to the list * */
1416
		if (!empty($this->origin_email) && empty($this->fk_soc)) {
1417
			$array_ext = array(array('firstname' => '', 'lastname' => '', 'email' => $this->origin_email, 'libelle' => $langs->transnoentities('TicketEmailOriginIssuer'), 'socid' => "-1"));
1418
			$contacts = array_merge($contacts, $array_ext);
1419
		}
1420
1421
		if (!empty($this->fk_soc)) {
1422
			$this->fetch_thirdparty($this->fk_soc);
1423
			$array_company = array(array('firstname' => '', 'lastname' => $this->client->name, 'email' => $this->client->email, 'libelle' => $langs->transnoentities('Customer'), 'socid' => $this->client->id));
0 ignored issues
show
Bug Best Practice introduced by
The property client does not exist on Ticket. Did you maybe forget to declare it?
Loading history...
1424
			$contacts = array_merge($contacts, $array_company);
1425
		}
1426
1427
		// foreach contact send email with notification message
1428
		if (count($contacts) > 0) {
1429
			foreach ($contacts as $key => $info_sendto) {
1430
				$message = '';
1431
				$subject = '['.$conf->global->MAIN_INFO_SOCIETE_NOM.'] '.$langs->transnoentities('TicketNotificationEmailSubject', $this->track_id);
1432
				$message .= $langs->transnoentities('TicketNotificationEmailBody', $this->track_id)."\n\n";
1433
				$message .= $langs->transnoentities('Title').' : '.$this->subject."\n";
1434
1435
				$recipient_name = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1');
1436
				$recipient = (!empty($recipient_name) ? $recipient_name : $info_sendto['email']).' ('.strtolower($info_sendto['libelle']).')';
1437
				$message .= $langs->transnoentities('TicketNotificationRecipient').' : '.$recipient."\n";
1438
				$message .= "\n";
1439
				$message .= '* '.$langs->transnoentities('TicketNotificationLogMessage').' *'."\n";
1440
				$message .= dol_html_entity_decode($log_message, ENT_QUOTES)."\n";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $log_message does not exist. Did you maybe mean $message?
Loading history...
1441
1442
				if ($info_sendto['source'] == 'internal') {
1443
					$url_internal_ticket = dol_buildpath('/ticket/card.php', 2).'?track_id='.$this->track_id;
1444
					$message .= "\n".$langs->transnoentities('TicketNotificationEmailBodyInfosTrackUrlinternal').' : '.'<a href="'.$url_internal_ticket.'">'.$this->track_id.'</a>'."\n";
1445
				} else {
1446
					$url_public_ticket = ($conf->global->TICKET_URL_PUBLIC_INTERFACE ? $conf->global->TICKET_URL_PUBLIC_INTERFACE.'/' : dol_buildpath('/public/ticket/view.php', 2)).'?track_id='.$this->track_id;
1447
					$message .= "\n".$langs->transnoentities('TicketNewEmailBodyInfosTrackUrlCustomer').' : '.'<a href="'.$url_public_ticket.'">'.$this->track_id.'</a>'."\n";
1448
				}
1449
1450
				$message .= "\n";
1451
				$message .= $langs->transnoentities('TicketEmailPleaseDoNotReplyToThisEmail')."\n";
1452
1453
				$from = $conf->global->MAIN_INFO_SOCIETE_NOM.'<'.$conf->global->TICKET_NOTIFICATION_EMAIL_FROM.'>';
1454
				$replyto = $from;
1455
1456
				// Init to avoid errors
1457
				$filepath = array();
1458
				$filename = array();
1459
				$mimetype = array();
1460
1461
				$message = dol_nl2br($message);
1462
1463
				if (!empty($conf->global->TICKET_DISABLE_MAIL_AUTOCOPY_TO)) {
1464
					$old_MAIN_MAIL_AUTOCOPY_TO = $conf->global->MAIN_MAIL_AUTOCOPY_TO;
1465
					$conf->global->MAIN_MAIL_AUTOCOPY_TO = '';
1466
				}
1467
				include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1468
				$mailfile = new CMailFile($subject, $info_sendto['email'], $from, $message, $filepath, $mimetype, $filename, $sendtocc, '', $deliveryreceipt, 0);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $sendtocc seems to be never defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable $deliveryreceipt seems to be never defined.
Loading history...
1469
				if ($mailfile->error || $mailfile->errors) {
1470
					setEventMessages($mailfile->error, $mailfile->errors, 'errors');
1471
				} else {
1472
					$result = $mailfile->sendfile();
1473
					if ($result > 0) {
1474
						$nb_sent++;
1475
					}
1476
				}
1477
				if (!empty($conf->global->TICKET_DISABLE_MAIL_AUTOCOPY_TO)) {
1478
					$conf->global->MAIN_MAIL_AUTOCOPY_TO = $old_MAIN_MAIL_AUTOCOPY_TO;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $old_MAIN_MAIL_AUTOCOPY_TO does not seem to be defined for all execution paths leading up to this point.
Loading history...
1479
				}
1480
			}
1481
1482
			setEventMessages($langs->trans('TicketNotificationNumberEmailSent', $nb_sent), null, 'mesgs');
1483
		}
1484
1485
		return $nb_sent;
1486
	}
1487
1488
	/**
1489
	 *      Charge la liste des actions sur le ticket
1490
	 *
1491
	 *      @return int             Number of lines loaded, 0 if already loaded, <0 if KO
1492
	 */
1493
	public function loadCacheLogsTicket()
1494
	{
1495
		global $langs;
1496
1497
		if (is_array($this->cache_logs_ticket) && count($this->cache_logs_ticket)) {
0 ignored issues
show
Bug introduced by
The property cache_logs_ticket does not exist on Ticket. Did you mean cache_msgs_ticket?
Loading history...
1498
			return 0;
1499
		}
1500
		// Cache deja charge
1501
1502
		// TODO Read the table llx_actioncomm
1503
		/*
1504
        $sql = "SELECT rowid, fk_user_create, datec, message";
1505
        $sql .= " FROM " . MAIN_DB_PREFIX . "ticket_logs";
1506
        $sql .= " WHERE fk_track_id ='" . $this->db->escape($this->track_id) . "'";
1507
        $sql .= " ORDER BY datec DESC";
1508
1509
        $resql = $this->db->query($sql);
1510
        if ($resql) {
1511
            $num = $this->db->num_rows($resql);
1512
            $i = 0;
1513
            while ($i < $num) {
1514
                $obj = $this->db->fetch_object($resql);
1515
                $this->cache_logs_ticket[$i]['id'] = $obj->rowid;
1516
                $this->cache_logs_ticket[$i]['fk_user_create'] = $obj->fk_user_create;
1517
                $this->cache_logs_ticket[$i]['datec'] = $this->db->jdate($obj->datec);
1518
                $this->cache_logs_ticket[$i]['message'] = $obj->message;
1519
                $i++;
1520
            }
1521
            return $num;
1522
        } else {
1523
            $this->error = "Error " . $this->db->lasterror();
1524
            dol_syslog(get_class($this) . "::loadCacheLogsTicket " . $this->error, LOG_ERR);
1525
            return -1;
1526
        }*/
1527
1528
		return 0;
1529
	}
1530
1531
	/**
1532
	 * Add message into database
1533
	 *
1534
	 * @param User 	 $user      		  User that creates
1535
	 * @param int  	 $notrigger 		  0=launch triggers after, 1=disable triggers
1536
	 * @param array	 $filename_list       List of files to attach (full path of filename on file system)
1537
	 * @param array	 $mimetype_list       List of MIME type of attached files
1538
	 * @param array	 $mimefilename_list   List of attached file name in message
1539
	 * @return int						  <0 if KO, >0 if OK
1540
	 */
1541
	public function createTicketMessage($user, $notrigger = 0, $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array())
1542
	{
1543
		global $conf, $langs;
1544
		$error = 0;
1545
1546
		$now = dol_now();
1547
1548
		// Clean parameters
1549
		if (isset($this->fk_track_id)) {
1550
			$this->fk_track_id = trim($this->fk_track_id);
1551
		}
1552
1553
		if (isset($this->message)) {
1554
			$this->message = trim($this->message);
1555
		}
1556
1557
		$this->db->begin();
1558
1559
		// Insert entry into agenda with code 'TICKET_MSG'
1560
		include_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
1561
		$actioncomm = new ActionComm($this->db);
1562
		$actioncomm->type_code = 'AC_OTH_AUTO';
1563
		$actioncomm->code = 'TICKET_MSG';
1564
		if ($this->private) {
1565
			$actioncomm->code = 'TICKET_MSG_PRIVATE';
1566
		}
1567
		$actioncomm->socid = $this->socid;
1568
		$actioncomm->label = $this->subject;
1569
		$actioncomm->note_private = $this->message;
1570
		$actioncomm->userassigned = array($user->id);
1571
		$actioncomm->userownerid = $user->id;
1572
		$actioncomm->datep = $now;
1573
		$actioncomm->percentage = 100;
1574
		$actioncomm->elementtype = 'ticket';
1575
		$actioncomm->fk_element = $this->id;
1576
1577
		$attachedfiles = array();
1578
		$attachedfiles['paths'] = $filename_list;
1579
		$attachedfiles['names'] = $mimefilename_list;
1580
		$attachedfiles['mimes'] = $mimetype_list;
1581
		if (is_array($attachedfiles) && count($attachedfiles) > 0) {
1582
			$actioncomm->attachedfiles = $attachedfiles;
0 ignored issues
show
Bug introduced by
The property attachedfiles does not seem to exist on ActionComm.
Loading history...
1583
		}
1584
1585
		if (!empty($mimefilename_list) && is_array($mimefilename_list))
1586
		{
1587
			$actioncomm->note_private = dol_concatdesc($actioncomm->note_private, "\n".$langs->transnoentities("AttachedFiles").': '.join(';', $mimefilename_list));
1588
		}
1589
1590
		$actionid = $actioncomm->create($user);
1591
		if ($actionid <= 0)
1592
		{
1593
			$error++;
1594
			$this->error = $actioncomm->error;
1595
			$this->errors = $actioncomm->errors;
1596
		}
1597
1598
		// Commit or rollback
1599
		if ($error) {
1600
			$this->db->rollback();
1601
			return -1 * $error;
1602
		} else {
1603
			$this->db->commit();
1604
			return 1;
1605
		}
1606
	}
1607
1608
	/**
1609
	 *      Load the list of event on ticket into ->cache_msgs_ticket
1610
	 *
1611
	 *      @return int             Number of lines loaded, 0 if already loaded, <0 if KO
1612
	 */
1613
	public function loadCacheMsgsTicket()
1614
	{
1615
		if (is_array($this->cache_msgs_ticket) && count($this->cache_msgs_ticket)) {
1616
			return 0;
1617
		}
1618
1619
		// Cache already loaded
1620
1621
		$sql = "SELECT id as rowid, fk_user_author, datec, label, note as message, code";
1622
		$sql .= " FROM ".MAIN_DB_PREFIX."actioncomm";
1623
		$sql .= " WHERE fk_element = ".(int) $this->id;
1624
		$sql .= " AND elementtype = 'ticket'";
1625
		$sql .= " ORDER BY datec DESC";
1626
1627
		dol_syslog(get_class($this)."::load_cache_actions_ticket sql=".$sql, LOG_DEBUG);
1628
		$resql = $this->db->query($sql);
1629
		if ($resql) {
1630
			$num = $this->db->num_rows($resql);
1631
			$i = 0;
1632
			while ($i < $num) {
1633
				$obj = $this->db->fetch_object($resql);
1634
				$this->cache_msgs_ticket[$i]['id'] = $obj->rowid;
1635
				$this->cache_msgs_ticket[$i]['fk_user_author'] = $obj->fk_user_author;
1636
				$this->cache_msgs_ticket[$i]['datec'] = $this->db->jdate($obj->datec);
1637
				$this->cache_msgs_ticket[$i]['subject'] = $obj->label;
1638
				$this->cache_msgs_ticket[$i]['message'] = $obj->message;
1639
				$this->cache_msgs_ticket[$i]['private'] = ($obj->code == 'TICKET_MSG_PRIVATE' ? 1 : 0);
1640
				$i++;
1641
			}
1642
			return $num;
1643
		} else {
1644
			$this->error = "Error ".$this->db->lasterror();
1645
			dol_syslog(get_class($this)."::load_cache_actions_ticket ".$this->error, LOG_ERR);
1646
			return -1;
1647
		}
1648
	}
1649
1650
	/**
1651
	 *    Close a ticket
1652
	 *
1653
	 *    @param    User    $user      User that close
1654
	 *    @return   int		           <0 if KO, >0 if OK
1655
	 */
1656
	public function close(User $user)
1657
	{
1658
		global $conf, $langs;
1659
1660
		if ($this->fk_statut != Ticket::STATUS_CLOSED) { // not closed
1661
			$this->db->begin();
1662
1663
			$sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
1664
			$sql .= " SET fk_statut=".Ticket::STATUS_CLOSED.", progress=100, date_close='".$this->db->idate(dol_now())."'";
1665
			$sql .= " WHERE rowid = ".$this->id;
1666
1667
			dol_syslog(get_class($this)."::close sql=".$sql);
1668
			$resql = $this->db->query($sql);
1669
			if ($resql) {
1670
				$error = 0;
1671
1672
				// Valid and close fichinter linked
1673
				$this->fetchObjectLinked($this->id, $this->element, null, 'fichinter');
1674
				if ($this->linkedObjectsIds)
1675
				{
1676
					foreach ($this->linkedObjectsIds['fichinter'] as $fichinter_id) {
1677
						$fichinter = new Fichinter($this->db);
1678
						$fichinter->fetch($fichinter_id);
1679
						if ($fichinter->statut == 0) {
1680
							$result = $fichinter->setValid($user);
1681
							if (!$result) {
1682
								$this->errors[] = $fichinter->error;
1683
								$error++;
1684
							}
1685
						}
1686
						if ($fichinter->statut < 3) {
1687
							$result = $fichinter->setStatut(3);
1688
							if (!$result) {
1689
								$this->errors[] = $fichinter->error;
1690
								$error++;
1691
							}
1692
						}
1693
					}
1694
				}
1695
1696
				// Call trigger
1697
				$result = $this->call_trigger('TICKET_CLOSE', $user);
1698
				if ($result < 0) {
1699
					$error++;
1700
				}
1701
				// End call triggers
1702
1703
				if (!$error) {
1704
					$this->db->commit();
1705
					return 1;
1706
				} else {
1707
					$this->db->rollback();
1708
					$this->error = join(',', $this->errors);
1709
					dol_syslog(get_class($this)."::close ".$this->error, LOG_ERR);
1710
					return -1;
1711
				}
1712
			} else {
1713
				$this->db->rollback();
1714
				$this->error = $this->db->lasterror();
1715
				dol_syslog(get_class($this)."::close ".$this->error, LOG_ERR);
1716
				return -1;
1717
			}
1718
		}
1719
	}
1720
1721
	/**
1722
	 *     Search and fetch thirparties by email
1723
	 *
1724
	 *     @param  string $email   		Email
1725
	 *     @param  int    $type    		Type of thirdparties (0=any, 1=customer, 2=prospect, 3=supplier)
1726
	 *     @param  array  $filters 		Array of couple field name/value to filter the companies with the same name
1727
	 *     @param  string $clause  		Clause for filters
1728
	 *     @return array        		Array of thirdparties object
1729
	 */
1730
	public function searchSocidByEmail($email, $type = '0', $filters = array(), $clause = 'AND')
1731
	{
1732
		$thirdparties = array();
1733
1734
		// Generation requete recherche
1735
		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe";
1736
		$sql .= " WHERE entity IN (".getEntity('ticket', 1).")";
1737
		if (!empty($type)) {
1738
			if ($type == 1 || $type == 2) {
1739
				$sql .= " AND client = ".$type;
1740
			} elseif ($type == 3) {
1741
				$sql .= " AND fournisseur = 1";
1742
			}
1743
		}
1744
		if (!empty($email)) {
1745
			if (!$exact) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $exact seems to be never defined.
Loading history...
1746
				if (preg_match('/^([\*])?[^*]+([\*])?$/', $email, $regs) && count($regs) > 1) {
1747
					$email = str_replace('*', '%', $email);
1748
				} else {
1749
					$email = '%'.$email.'%';
1750
				}
1751
			}
1752
			$sql .= " AND ";
1753
			if (is_array($filters) && !empty($filters)) {
1754
				$sql .= "(";
1755
			}
1756
1757
			if (!$case) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $case seems to be never defined.
Loading history...
1758
				$sql .= "email LIKE '".$this->db->escape($email)."'";
1759
			} else {
1760
				$sql .= "email LIKE BINARY '".$this->db->escape($email)."'";
1761
			}
1762
		}
1763
		if (is_array($filters) && !empty($filters)) {
1764
			foreach ($filters as $field => $value) {
1765
				$sql .= " ".$clause." ".$field." LIKE BINARY '".$this->db->escape($value)."'";
1766
			}
1767
			if (!empty($email)) {
1768
				$sql .= ")";
1769
			}
1770
		}
1771
1772
		$res = $this->db->query($sql);
1773
		if ($res) {
1774
			while ($rec = $this->db->fetch_array($res)) {
1775
				$soc = new Societe($this->db);
1776
				$soc->fetch($rec['rowid']);
1777
				$thirdparties[] = $soc;
1778
			}
1779
1780
			return $thirdparties;
1781
		} else {
1782
			$this->error = $this->db->error().' sql='.$sql;
1783
			dol_syslog(get_class($this)."::searchSocidByEmail ".$this->error, LOG_ERR);
1784
			return -1;
1785
		}
1786
	}
1787
1788
	/**
1789
	 *     Search and fetch contacts by email
1790
	 *
1791
	 *     @param  string $email 	Email
1792
	 *     @param  array  $socid 	Limit to a thirdparty
1793
	 *     @param  string $case  	Respect case
1794
	 *     @return array        	Array of contacts object
1795
	 */
1796
	public function searchContactByEmail($email, $socid = '', $case = '')
1797
	{
1798
		$contacts = array();
1799
1800
		// Generation requete recherche
1801
		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople";
1802
		$sql .= " WHERE entity IN (".getEntity('socpeople').")";
1803
		if (!empty($socid)) {
1804
			$sql .= " AND fk_soc='".$this->db->escape($socid)."'";
1805
		}
1806
1807
		if (!empty($email)) {
1808
			$sql .= " AND ";
1809
1810
			if (!$case) {
1811
				$sql .= "email LIKE '".$this->db->escape($email)."'";
1812
			} else {
1813
				$sql .= "email LIKE BINARY '".$this->db->escape($email)."'";
1814
			}
1815
		}
1816
1817
		$res = $this->db->query($sql);
1818
		if ($res) {
1819
			while ($rec = $this->db->fetch_array($res)) {
1820
				include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1821
				$contactstatic = new Contact($this->db);
1822
				$contactstatic->fetch($rec['rowid']);
1823
				$contacts[] = $contactstatic;
1824
			}
1825
1826
			return $contacts;
1827
		} else {
1828
			$this->error = $this->db->error().' sql='.$sql;
1829
			dol_syslog(get_class($this)."::searchContactByEmail ".$this->error, LOG_ERR);
1830
			return -1;
1831
		}
1832
	}
1833
1834
	/**
1835
	 *    Define parent commany of current ticket
1836
	 *
1837
	 *    @param  int $id Id of thirdparty to set or '' to remove
1838
	 *    @return int             <0 if KO, >0 if OK
1839
	 */
1840
	public function setCustomer($id)
1841
	{
1842
		if ($this->id) {
1843
			$sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
1844
			$sql .= " SET fk_soc = ".($id > 0 ? $id : "null");
1845
			$sql .= " WHERE rowid = ".$this->id;
1846
			dol_syslog(get_class($this).'::setCustomer sql='.$sql);
1847
			$resql = $this->db->query($sql);
1848
			if ($resql) {
1849
				return 1;
1850
			} else {
1851
				return -1;
1852
			}
1853
		} else {
1854
			return -1;
1855
		}
1856
	}
1857
1858
	/**
1859
	 *    Define progression of current ticket
1860
	 *
1861
	 *    @param  int $percent Progression percent
1862
	 *    @return int             <0 if KO, >0 if OK
1863
	 */
1864
	public function setProgression($percent)
1865
	{
1866
		if ($this->id) {
1867
			$sql = "UPDATE ".MAIN_DB_PREFIX."ticket";
1868
			$sql .= " SET progress = ".($percent > 0 ? $percent : "null");
1869
			$sql .= " WHERE rowid = ".$this->id;
1870
			dol_syslog(get_class($this).'::set_progression sql='.$sql);
1871
			$resql = $this->db->query($sql);
1872
			if ($resql) {
1873
				return 1;
1874
			} else {
1875
				return -1;
1876
			}
1877
		} else {
1878
			return -1;
1879
		}
1880
	}
1881
1882
	/**
1883
	 *     Link element with a project
1884
	 * 	   Override core function because of key name 'fk_project' used for this module
1885
	 *
1886
	 *     @param  int $projectid Project id to link element to
1887
	 *     @return int                        <0 if KO, >0 if OK
1888
	 */
1889
	public function setProject($projectid)
1890
	{
1891
		if (!$this->table_element) {
1892
			dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
1893
			return -1;
1894
		}
1895
1896
		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1897
		if ($projectid) {
1898
			$sql .= ' SET fk_project = '.$projectid;
1899
		} else {
1900
			$sql .= ' SET fk_project = NULL';
1901
		}
1902
1903
		$sql .= ' WHERE rowid = '.$this->id;
1904
1905
		dol_syslog(get_class($this)."::setProject sql=".$sql);
1906
		if ($this->db->query($sql)) {
1907
			$this->fk_project = $projectid;
1908
			return 1;
1909
		} else {
1910
			dol_print_error($this->db);
1911
			return -1;
1912
		}
1913
	}
1914
1915
	/**
1916
	 *     Link element with a contract
1917
	 *
1918
	 *     @param  int $contractid Contract id to link element to
1919
	 *     @return int                        <0 if KO, >0 if OK
1920
	 */
1921
	public function setContract($contractid)
1922
	{
1923
		if (!$this->table_element) {
1924
			dol_syslog(get_class($this)."::setContract was called on objet with property table_element not defined", LOG_ERR);
1925
			return -1;
1926
		}
1927
1928
		$result = $this->add_object_linked('contrat', $contractid);
1929
		if ($result) {
1930
			$this->fk_contract = $contractid;
1931
			return 1;
1932
		} else {
1933
			dol_print_error($this->db);
1934
			return -1;
1935
		}
1936
	}
1937
1938
	/* gestion des contacts d'un ticket */
1939
1940
	/**
1941
	 *  Return id des contacts interne de suivi
1942
	 *
1943
	 *  @return array       Liste des id contacts suivi ticket
1944
	 */
1945
	public function getIdTicketInternalContact()
1946
	{
1947
		return $this->getIdContact('internal', 'SUPPORTTEC');
1948
	}
1949
1950
	/**
1951
	 * Retrieve informations about internal contacts
1952
	 *
1953
	 *  @return array       Array with datas : firstname, lastname, socid (-1 for internal users), email, code, libelle, status
1954
	 */
1955
	public function getInfosTicketInternalContact()
1956
	{
1957
		return $this->listeContact(-1, 'internal');
1958
	}
1959
1960
	/**
1961
	 *  Return id des contacts clients pour le suivi ticket
1962
	 *
1963
	 *  @return array       Liste des id contacts suivi ticket
1964
	 */
1965
	public function getIdTicketCustomerContact()
1966
	{
1967
		return $this->getIdContact('external', 'SUPPORTCLI');
1968
	}
1969
1970
	/**
1971
	 * Retrieve informations about external contacts
1972
	 *
1973
	 *  @return array       Array with datas : firstname, lastname, socid (-1 for internal users), email, code, libelle, status
1974
	 */
1975
	public function getInfosTicketExternalContact()
1976
	{
1977
		return $this->listeContact(-1, 'external');
1978
	}
1979
1980
	/**
1981
	 *  Return id des contacts clients des intervenants
1982
	 *
1983
	 *  @return array       Liste des id contacts intervenants
1984
	 */
1985
	public function getIdTicketInternalInvolvedContact()
1986
	{
1987
		return $this->getIdContact('internal', 'CONTRIBUTOR');
1988
	}
1989
1990
	/**
1991
	 *  Return id des contacts clients des intervenants
1992
	 *
1993
	 *  @return array       Liste des id contacts intervenants
1994
	 */
1995
	public function getIdTicketCustomerInvolvedContact()
1996
	{
1997
		return $this->getIdContact('external', 'CONTRIBUTOR');
1998
	}
1999
2000
	/**
2001
	 * Return id of all contacts for ticket
2002
	 *
2003
	 * @return	array		Array of contacts for tickets
2004
	 */
2005
	public function getTicketAllContacts()
2006
	{
2007
		$array_contact = array();
2008
2009
		$array_contact = $this->getIdTicketInternalContact($exclude_self);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $exclude_self seems to be never defined.
Loading history...
2010
2011
		$array_contact = array_merge($array_contact, $this->getIdTicketCustomerContact($exclude_self));
2012
2013
		$array_contact = array_merge($array_contact, $this->getIdTicketInternalInvolvedContact($exclude_self));
2014
		$array_contact = array_merge($array_contact, $this->getIdTicketCustomerInvolvedContact($exclude_self));
2015
2016
		return $array_contact;
2017
	}
2018
2019
	/**
2020
	 * Return id of all contacts for ticket
2021
	 *
2022
	 * @return	array		Array of contacts
2023
	 */
2024
	public function getTicketAllCustomerContacts()
2025
	{
2026
		$array_contact = array();
2027
2028
		$array_contact = array_merge($array_contact, $this->getIdTicketCustomerContact($exclude_self));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $exclude_self seems to be never defined.
Loading history...
2029
		$array_contact = array_merge($array_contact, $this->getIdTicketCustomerInvolvedContact($exclude_self));
2030
2031
		return $array_contact;
2032
	}
2033
2034
	/**
2035
	 * Send message
2036
	 *
2037
	 *  @param  string $subject	  Subject
2038
	 *  @param  string $texte      Message to send
2039
	 *  @return int                <0 if KO, or number of changes if OK
2040
	 */
2041
	public function messageSend($subject, $texte)
2042
	{
2043
		global $conf, $langs, $mysoc, $dolibarr_main_url_root;
2044
2045
		$langs->load("other");
2046
2047
		dol_syslog(get_class($this)."::message_send action=$action, socid=$socid, texte=$texte, objet_type=$objet_type, objet_id=$objet_id, file=$file");
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $file seems to be never defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable $action does not exist. Did you maybe mean $actiondefid?
Loading history...
Comprehensibility Best Practice introduced by
The variable $socid seems to be never defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable $objet_type seems to be never defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable $objet_id seems to be never defined.
Loading history...
2048
2049
		$internal_contacts = $this->getIdContact('internal', 'SUPPORTTEC');
2050
		$external_contacts = $this->getIdContact('external', 'SUPPORTTEC');
2051
2052
		if ($result) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $result seems to be never defined.
Loading history...
2053
			$num = $this->db->num_rows($result);
2054
			$i = 0;
2055
			while ($i < $num) { // For each notification couple defined (third party/actioncode)
2056
				$obj = $this->db->fetch_object($result);
2057
2058
				$sendto = $obj->firstname." ".$obj->lastname." <".$obj->email.">";
2059
				$actiondefid = $obj->adid;
2060
2061
				if (dol_strlen($sendto))
2062
				{
2063
					include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2064
					$application = ($conf->global->MAIN_APPLICATION_TITLE ? $conf->global->MAIN_APPLICATION_TITLE : 'Dolibarr ERP/CRM');
2065
2066
					$subject = '['.$application.'] '.$langs->transnoentitiesnoconv("DolibarrNotification");
2067
2068
					$message = $langs->transnoentities("YouReceiveMailBecauseOfNotification", $application, $mysoc->name)."\n";
2069
					$message .= $langs->transnoentities("YouReceiveMailBecauseOfNotification2", $application, $mysoc->name)."\n";
2070
					$message .= "\n";
2071
					$message .= $texte;
2072
					// Add link
2073
					$link = '';
2074
					switch ($objet_type) {
2075
						case 'ficheinter':
2076
							$link = '/fichinter/card.php?id='.$objet_id;
2077
							break;
2078
						case 'propal':
2079
							$link = '/comm/propal.php?id='.$objet_id;
2080
							break;
2081
						case 'facture':
2082
							$link = '/compta/facture/card.php?facid='.$objet_id;
2083
							break;
2084
						case 'order':
2085
							$link = '/commande/card.php?facid='.$objet_id;
2086
							break;
2087
						case 'order_supplier':
2088
							$link = '/fourn/commande/card.php?facid='.$objet_id;
2089
							break;
2090
					}
2091
					// Define $urlwithroot
2092
					$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2093
					$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2094
					//$urlwithroot=DOL_MAIN_URL_ROOT;                        // This is to use same domain name than current
2095
					if ($link) {
2096
						$message .= "\n".$urlwithroot.$link;
2097
					}
2098
2099
					$filename = basename($file);
2100
2101
					$mimefile = dol_mimetype($file);
2102
2103
					$msgishtml = 0;
2104
2105
					$replyto = $conf->notification->email_from;
2106
2107
					$message = dol_nl2br($message);
2108
2109
					if (!empty($conf->global->TICKET_DISABLE_MAIL_AUTOCOPY_TO)) {
2110
						$old_MAIN_MAIL_AUTOCOPY_TO = $conf->global->MAIN_MAIL_AUTOCOPY_TO;
2111
						$conf->global->MAIN_MAIL_AUTOCOPY_TO = '';
2112
					}
2113
					$mailfile = new CMailFile(
2114
						$subject,
2115
						$sendto,
2116
						$replyto,
2117
						$message,
2118
						array($file),
2119
						array($mimefile),
2120
						array($filename[count($filename) - 1]),
2121
						'',
2122
						'',
2123
						0,
2124
						$msgishtml
2125
					);
2126
2127
					if ($mailfile->sendfile()) {
2128
						$now = dol_now();
2129
						$sendto = htmlentities($sendto);
2130
2131
						$sql = "INSERT INTO ".MAIN_DB_PREFIX."notify (daten, fk_action, fk_contact, objet_type, objet_id, email)";
2132
						$sql .= " VALUES ('".$this->db->idate($now)."', ".$actiondefid.", ".$obj->cid.", '".$this->db->escape($objet_type)."', ".$objet_id.", '".$this->db->escape($obj->email)."')";
2133
						dol_syslog("Notify::send sql=".$sql);
2134
						if (!$this->db->query($sql)) {
2135
							dol_print_error($this->db);
2136
						}
2137
					} else {
2138
						$this->error = $mailfile->error;
2139
						//dol_syslog("Notify::send ".$this->error, LOG_ERR);
2140
					}
2141
					if (!empty($conf->global->TICKET_DISABLE_MAIL_AUTOCOPY_TO)) {
2142
						$conf->global->MAIN_MAIL_AUTOCOPY_TO = $old_MAIN_MAIL_AUTOCOPY_TO;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $old_MAIN_MAIL_AUTOCOPY_TO does not seem to be defined for all execution paths leading up to this point.
Loading history...
2143
					}
2144
				}
2145
				$i++;
2146
			}
2147
			return $i;
2148
		} else {
2149
			$this->error = $this->db->error();
2150
			return -1;
2151
		}
2152
	}
2153
2154
	/**
2155
	 *    Get array of all contacts for a ticket
2156
	 *    Override method of file commonobject.class.php to add phone number
2157
	 *
2158
	 *    @param	int    	$status 	Status of lines to get (-1=all)
2159
	 *    @param	string 	$source 	Source of contact: external or thirdparty (llx_socpeople) or internal (llx_user)
2160
	 *    @param	int    	$list   	0:Return array contains all properties, 1:Return array contains just id
2161
	 *    @param    string  $code       Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
2162
	 *    @return 	array          		Array of contacts
2163
	 */
2164
	public function listeContact($status = -1, $source = 'external', $list = 0, $code = '')
2165
	{
2166
		global $langs;
2167
2168
		$tab = array();
2169
2170
		$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
2171
		if ($source == 'internal') {
2172
			$sql .= ", '-1' as socid, t.statut as statuscontact";
2173
		}
2174
2175
		if ($source == 'external' || $source == 'thirdparty') {
2176
			$sql .= ", t.fk_soc as socid, t.statut as statuscontact";
2177
		}
2178
2179
		$sql .= ", t.civility, t.lastname as lastname, t.firstname, t.email";
2180
		if ($source == 'internal') {
2181
			$sql .= ", t.office_phone as phone, t.user_mobile as phone_mobile";
2182
		}
2183
2184
		if ($source == 'external') {
2185
			$sql .= ", t.phone as phone, t.phone_mobile as phone_mobile, t.phone_perso as phone_perso";
2186
		}
2187
2188
		$sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_contact_label";
2189
		$sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
2190
		$sql .= ", ".MAIN_DB_PREFIX."element_contact ec";
2191
		if ($source == 'internal') {
2192
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
2193
		}
2194
2195
		if ($source == 'external' || $source == 'thirdparty') {
2196
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
2197
		}
2198
2199
		$sql .= " WHERE ec.element_id =".$this->id;
2200
		$sql .= " AND ec.fk_c_type_contact=tc.rowid";
2201
		$sql .= " AND tc.element='".$this->db->escape($this->element)."'";
2202
		if ($source == 'internal') {
2203
			$sql .= " AND tc.source = 'internal'";
2204
		}
2205
2206
		if ($source == 'external' || $source == 'thirdparty') {
2207
			$sql .= " AND tc.source = 'external'";
2208
		}
2209
2210
		$sql .= " AND tc.active=1";
2211
		if ($status >= 0) {
2212
			$sql .= " AND ec.statut = '".$status."'";
2213
		}
2214
2215
		$sql .= " ORDER BY t.lastname ASC";
2216
2217
		$resql = $this->db->query($sql);
2218
		if ($resql) {
2219
			$num = $this->db->num_rows($resql);
2220
			$i = 0;
2221
			while ($i < $num) {
2222
				$obj = $this->db->fetch_object($resql);
2223
2224
				if (!$list) {
2225
					$transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
2226
					$libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_contact_label);
2227
					$tab[$i] = array(
2228
							'source' => $obj->source,
2229
							'socid' => $obj->socid,
2230
							'id' => $obj->id,
2231
							'nom' => $obj->lastname, // For backward compatibility
2232
							'civility' => $obj->civility,
2233
							'lastname' => $obj->lastname,
2234
							'firstname' => $obj->firstname,
2235
							'email' => $obj->email,
2236
							'rowid' => $obj->rowid,
2237
							'code' => $obj->code,
2238
							'libelle' => $libelle_type,
2239
							'status' => $obj->statuslink,
2240
							'statuscontact'=>$obj->statuscontact,
2241
							'fk_c_type_contact' => $obj->fk_c_type_contact,
2242
							'phone' => $obj->phone,
2243
							'phone_mobile' => $obj->phone_mobile);
2244
				} else {
2245
					$tab[$i] = $obj->id;
2246
				}
2247
2248
				$i++;
2249
			}
2250
2251
			return $tab;
2252
		} else {
2253
			$this->error = $this->db->error();
2254
			dol_print_error($this->db);
2255
			return -1;
2256
		}
2257
	}
2258
2259
	/**
2260
	 * Get a default reference.
2261
	 *
2262
	 * @param	Societe		$thirdparty		Thirdparty
2263
	 * @return 	string   					Reference
2264
	 */
2265
	public function getDefaultRef($thirdparty = '')
2266
	{
2267
		global $conf;
2268
2269
		$defaultref = '';
2270
		$modele = empty($conf->global->TICKET_ADDON) ? 'mod_ticket_simple' : $conf->global->TICKET_ADDON;
2271
2272
		// Search template files
2273
		$file = '';
2274
		$classname = '';
2275
		$filefound = 0;
2276
		$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
2277
		foreach ($dirmodels as $reldir) {
2278
			$file = dol_buildpath($reldir."core/modules/ticket/".$modele.'.php', 0);
2279
			if (file_exists($file)) {
2280
				$filefound = 1;
2281
				$classname = $modele;
2282
				break;
2283
			}
2284
		}
2285
2286
		if ($filefound) {
2287
			$result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php');
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $reldir seems to be defined by a foreach iteration on line 2277. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
2288
			$modTicket = new $classname;
2289
2290
			$defaultref = $modTicket->getNextValue($thirdparty, $this);
2291
		}
2292
2293
		if (is_numeric($defaultref) && $defaultref <= 0) {
2294
			$defaultref = '';
2295
		}
2296
2297
		return $defaultref;
2298
	}
2299
2300
2301
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2302
	/**
2303
	 *  Return if at least one photo is available
2304
	 *
2305
	 *  @param      string      $sdir       Directory to scan
2306
	 *  @return     boolean                 True if at least one photo is available, False if not
2307
	 */
2308
	public function is_photo_available($sdir)
2309
	{
2310
		// phpcs:enable
2311
		include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2312
2313
		global $conf;
2314
2315
		$dir = $sdir.'/';
2316
		$nbphoto = 0;
2317
2318
		$dir_osencoded = dol_osencode($dir);
2319
		if (file_exists($dir_osencoded)) {
2320
			$handle = opendir($dir_osencoded);
2321
			if (is_resource($handle)) {
2322
				while (($file = readdir($handle)) !== false) {
2323
					if (!utf8_check($file)) {
2324
						$file = utf8_encode($file);
2325
					}
2326
					// To be sure data is stored in UTF8 in memory
2327
					if (dol_is_file($dir.$file)) {
2328
						return true;
2329
					}
2330
				}
2331
			}
2332
		}
2333
		return false;
2334
	}
2335
2336
2337
	/**
2338
	 * Copy files defined into $_SESSION array into the ticket directory of attached files.
2339
	 * Used for files linked into messages.
2340
	 * Files may be renamed during copy to avoid overwriting existing files.
2341
	 *
2342
	 * @return	array		Array with final path/name/mime of files.
2343
	 */
2344
	public function copyFilesForTicket()
2345
	{
2346
		global $conf;
2347
2348
		// Create form object
2349
		include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
2350
		include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2351
		include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
2352
2353
		$maxwidthsmall = 270;
2354
		$maxheightsmall = 150;
2355
		$maxwidthmini = 128;
2356
		$maxheightmini = 72;
2357
2358
		$formmail = new FormMail($this->db);
2359
2360
		$attachedfiles = $formmail->get_attached_files();
2361
2362
		$filepath = $attachedfiles['paths'];
2363
		$filename = $attachedfiles['names'];
2364
		$mimetype = $attachedfiles['mimes'];
2365
2366
		// Copy files into ticket directory
2367
		$destdir = $conf->ticket->dir_output.'/'.$this->ref;
2368
2369
		if (!dol_is_dir($destdir)) {
2370
			dol_mkdir($destdir);
2371
		}
2372
2373
		$listofpaths = array();
2374
		$listofnames = array();
2375
		foreach ($filename as $i => $val) {
2376
			$destfile = $destdir.'/'.$filename[$i];
2377
			// If destination file already exists, we add a suffix to avoid to overwrite
2378
			if (is_file($destfile))
2379
			{
2380
				$now = dol_now();
2381
				$destfile .= '.'.dol_print_date($now, 'dayhourlog');
2382
			}
2383
2384
			$res = dol_move($filepath[$i], $destfile, 0, 1);
2385
2386
			if (image_format_supported($destfile) == 1) {
2387
				// Create small thumbs for image (Ratio is near 16/9)
2388
				// Used on logon for example
2389
				$imgThumbSmall = vignette($destfile, $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs");
2390
				// Create mini thumbs for image (Ratio is near 16/9)
2391
				// Used on menu or for setup page for example
2392
				$imgThumbMini = vignette($destfile, $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs");
2393
			}
2394
2395
			$formmail->remove_attached_files($i);
2396
2397
			// Fill array with new names
2398
			$listofpaths[$i] = $destfile;
2399
			$listofnames[$i] = basename($destfile);
2400
		}
2401
2402
		return array('listofpaths'=>$listofpaths, 'listofnames'=>$listofnames, 'listofmimes'=>$mimetype);
2403
	}
2404
2405
2406
	/**
2407
	 * Add new message on a ticket (private area). Can also send it be email if GETPOST('send_email', 'int') is set.
2408
	 *
2409
	 * @param   User    $user       User for action
2410
	 * @param   string  $action     Action string
2411
	 * @param   int     $private    1=Message is private. TODO Implement this. What does this means ?
2412
	 * @return  int
2413
	 */
2414
	public function newMessage($user, &$action, $private = 1)
2415
	{
2416
		global $mysoc, $conf, $langs;
2417
2418
		$error = 0;
2419
2420
		$object = new Ticket($this->db);
2421
2422
		$ret = $object->fetch('', '', GETPOST('track_id', 'alpha'));
2423
2424
		$object->socid = $object->fk_soc;
2425
		$object->fetch_thirdparty();
2426
2427
		if ($ret < 0) {
2428
			$error++;
2429
			array_push($this->errors, $langs->trans("ErrorTicketIsNotValid"));
2430
			$action = '';
2431
		}
2432
2433
		if (!GETPOST("message")) {
2434
			$error++;
2435
			array_push($this->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("message")));
2436
			$action = 'add_message';
2437
		}
2438
2439
		if (!$error) {
2440
			$object->subject = GETPOST('subject', 'alphanohtml');
2441
			$object->message = GETPOST("message", "none");
2442
			$object->private = GETPOST("private_message", "alpha");
2443
2444
			$send_email = GETPOST('send_email', 'int');
2445
2446
			// Copy attached files (saved into $_SESSION) as linked files to ticket. Return array with final name used.
2447
			$resarray = $object->copyFilesForTicket();
2448
2449
			$listofpaths = $resarray['listofpaths'];
2450
			$listofnames = $resarray['listofnames'];
2451
			$listofmimes = $resarray['listofmimes'];
2452
2453
			$id = $object->createTicketMessage($user, 0, $listofpaths, $listofmimes, $listofnames);
2454
			if ($id <= 0) {
2455
				$error++;
2456
				$this->errors = $object->error;
0 ignored issues
show
Documentation Bug introduced by
It seems like $object->error of type string is incompatible with the declared type string[] of property $errors.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
2457
				$this->errors = $object->errors;
2458
				$action = 'add_message';
2459
			}
2460
2461
			if (!$error && $id > 0) {
2462
				setEventMessages($langs->trans('TicketMessageSuccessfullyAdded'), null, 'mesgs');
2463
2464
				//var_dump($_SESSION); var_dump($listofpaths);exit;
2465
2466
				/*
2467
                 * Send emails to internal users (linked contacts)
2468
                 */
2469
				if ($send_email > 0) {
2470
					// Retrieve internal contact datas
2471
					$internal_contacts = $object->getInfosTicketInternalContact();
2472
2473
					$sendto = array();
2474
					if (is_array($internal_contacts) && count($internal_contacts) > 0) {
2475
						// altairis: set default subject
2476
						$label_title = empty($conf->global->MAIN_APPLICATION_TITLE) ? $mysoc->name : $conf->global->MAIN_APPLICATION_TITLE;
2477
						$subject = GETPOST('subject', 'nohtml') ? GETPOST('subject', 'nohtml') : '['.$label_title.'- ticket #'.$object->track_id.'] '.$langs->trans('TicketNewMessage');
2478
2479
						$message_intro = $langs->trans('TicketNotificationEmailBody', "#".$object->id);
2480
						$message_signature = GETPOST('mail_signature') ? GETPOST('mail_signature') : $conf->global->TICKET_MESSAGE_MAIL_SIGNATURE;
2481
2482
						$message = $langs->trans('TicketMessageMailIntroText');
2483
						$message .= "\n\n";
2484
						$message .= GETPOST('message', 'restricthtml');
2485
2486
						//  Coordonnées client
2487
						$message .= "\n\n";
2488
						$message .= "==============================================\n";
2489
						$message .= !empty($object->thirdparty->name) ? $langs->trans('Thirdparty')." : ".$object->thirdparty->name : '';
2490
						$message .= !empty($object->thirdparty->town) ? "\n".$langs->trans('Town')." : ".$object->thirdparty->town : '';
2491
						$message .= !empty($object->thirdparty->phone) ? "\n".$langs->trans('Phone')." : ".$object->thirdparty->phone : '';
2492
2493
						// Build array to display recipient list
2494
						foreach ($internal_contacts as $key => $info_sendto) {
2495
							// altairis: avoid duplicate notifications
2496
							if ($info_sendto['id'] == $user->id) {
2497
								continue;
2498
							}
2499
2500
							if ($info_sendto['email'] != '') {
2501
								if (!empty($info_sendto['email'])) $sendto[] = trim($info_sendto['firstname']." ".$info_sendto['lastname'])." <".$info_sendto['email'].">";
2502
2503
								//Contact type
2504
								$recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1').' ('.strtolower($info_sendto['libelle']).')';
2505
								$message .= (!empty($recipient) ? $langs->trans('TicketNotificationRecipient').' : '.$recipient."\n" : '');
2506
							}
2507
						}
2508
						$message .= "\n";
2509
						// URL ticket
2510
						$url_internal_ticket = dol_buildpath('/ticket/card.php', 2).'?track_id='.$object->track_id;
2511
2512
						// altairis: make html link on url
2513
						$message .= "\n".$langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal').' : '.'<a href="'.$url_internal_ticket.'">'.$object->track_id.'</a>'."\n";
2514
2515
						// Add global email address recipient
2516
						if ($conf->global->TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS && !in_array($conf->global->TICKET_NOTIFICATION_EMAIL_TO, $sendto)) {
2517
							if (!empty($conf->global->TICKET_NOTIFICATION_EMAIL_TO)) $sendto[] = $conf->global->TICKET_NOTIFICATION_EMAIL_TO;
2518
						}
2519
2520
						// altairis: dont try to send email if no recipient
2521
						if (!empty($sendto)) {
2522
							$this->sendTicketMessageByEmail($subject, $message, '', $sendto, $listofpaths, $listofmimes, $listofnames);
2523
						}
2524
					}
2525
2526
					/*
2527
                     * Send emails for externals users if not private (linked contacts)
2528
                     */
2529
					if (empty($object->private)) {
2530
						// Retrieve email of all contacts (external)
2531
						$external_contacts = $object->getInfosTicketExternalContact();
2532
2533
						// If no contact, get email from thirdparty
2534
						if (is_array($external_contacts) && count($external_contacts) === 0) {
2535
							if (!empty($object->fk_soc)) {
2536
								$object->fetch_thirdparty($object->fk_soc);
2537
								$array_company = array(array('firstname' => '', 'lastname' => $object->thirdparty->name, 'email' => $object->thirdparty->email, 'libelle' => $langs->transnoentities('Customer'), 'socid' => $object->thirdparty->id));
2538
								$external_contacts = array_merge($external_contacts, $array_company);
2539
							} elseif (empty($object->fk_soc) && !empty($object->origin_email)) {
2540
								$array_external = array(array('firstname' => '', 'lastname' => $object->origin_email, 'email' => $object->thirdparty->email, 'libelle' => $langs->transnoentities('Customer'), 'socid' => $object->thirdparty->id));
2541
								$external_contacts = array_merge($external_contacts, $array_external);
2542
							}
2543
						}
2544
2545
						$sendto = array();
2546
						if (is_array($external_contacts) && count($external_contacts) > 0) {
2547
							// altairis: get default subject for email to external contacts
2548
							$label_title = empty($conf->global->MAIN_APPLICATION_TITLE) ? $mysoc->name : $conf->global->MAIN_APPLICATION_TITLE;
2549
							$subject = GETPOST('subject') ? GETPOST('subject') : '['.$label_title.'- ticket #'.$object->track_id.'] '.$langs->trans('TicketNewMessage');
2550
2551
							$message_intro = GETPOST('mail_intro') ? GETPOST('mail_intro') : $conf->global->TICKET_MESSAGE_MAIL_INTRO;
2552
							$message_signature = GETPOST('mail_signature') ? GETPOST('mail_signature') : $conf->global->TICKET_MESSAGE_MAIL_SIGNATURE;
2553
2554
							// We put intro after
2555
							$message = GETPOST('message');
2556
							$message .= "\n\n";
2557
2558
							foreach ($external_contacts as $key => $info_sendto) {
2559
								// altairis: avoid duplicate emails to external contacts
2560
								if ($info_sendto['id'] == $user->contactid) {
2561
									continue;
2562
								}
2563
2564
								if ($info_sendto['email'] != '' && $info_sendto['email'] != $object->origin_email) {
2565
									if (!empty($info_sendto['email'])) $sendto[] = trim($info_sendto['firstname']." ".$info_sendto['lastname'])." <".$info_sendto['email'].">";
2566
2567
									$recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1').' ('.strtolower($info_sendto['libelle']).')';
2568
									$message .= (!empty($recipient) ? $langs->trans('TicketNotificationRecipient').' : '.$recipient."\n" : '');
2569
								}
2570
							}
2571
2572
							// If public interface is not enable, use link to internal page into mail
2573
							$url_public_ticket = (!empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE) ?
2574
								(!empty($conf->global->TICKET_URL_PUBLIC_INTERFACE) ? $conf->global->TICKET_URL_PUBLIC_INTERFACE.'/view.php' : dol_buildpath('/public/ticket/view.php', 2)) : dol_buildpath('/ticket/card.php', 2)).'?track_id='.$object->track_id;
2575
							$message .= "\n".$langs->trans('TicketNewEmailBodyInfosTrackUrlCustomer').' : '.'<a href="'.$url_public_ticket.'">'.$object->track_id.'</a>'."\n";
2576
2577
							// Build final message
2578
							$message = $message_intro.$message;
2579
2580
							// Add signature
2581
							$message .= '<br>'.$message_signature;
2582
2583
							if (!empty($object->origin_email)) {
2584
								$sendto[] = $object->origin_email;
2585
							}
2586
2587
							if ($object->fk_soc > 0 && !in_array($object->origin_email, $sendto)) {
2588
								$object->socid = $object->fk_soc;
2589
								$object->fetch_thirdparty();
2590
								if (!empty($object->thirdparty->email)) $sendto[] = $object->thirdparty->email;
2591
							}
2592
2593
							// altairis: Add global email address reciepient
2594
							if ($conf->global->TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS && !in_array($conf->global->TICKET_NOTIFICATION_EMAIL_TO, $sendto)) {
2595
								if (!empty($conf->global->TICKET_NOTIFICATION_EMAIL_TO)) $sendto[] = $conf->global->TICKET_NOTIFICATION_EMAIL_TO;
2596
							}
2597
2598
							// altairis: dont try to send email when no recipient
2599
							if (!empty($sendto)) {
2600
								$this->sendTicketMessageByEmail($subject, $message, '', $sendto, $listofpaths, $listofmimes, $listofnames);
2601
							}
2602
						}
2603
					}
2604
				}
2605
2606
				// Set status to "answered" if not set yet, but only if internal user
2607
				if ($object->fk_statut < 3 && !$user->socid)
2608
				{
2609
					$object->setStatut(3);
2610
				}
2611
2612
				return 1;
2613
			} else {
2614
				setEventMessages($object->error, $object->errors, 'errors');
2615
				return -1;
2616
			}
2617
		} else {
2618
			setEventMessages($this->error, $this->errors, 'errors');
2619
			return -1;
2620
		}
2621
	}
2622
2623
2624
	/**
2625
	 * Send ticket by email to linked contacts
2626
	 *
2627
	 * @param string $subject          	  Email subject
2628
	 * @param string $message          	  Email message
2629
	 * @param int    $send_internal_cc 	  Receive a copy on internal email ($conf->global->TICKET_NOTIFICATION_EMAIL_FROM)
2630
	 * @param array  $array_receiver   	  Array of receiver. exemple array('name' => 'John Doe', 'email' => '[email protected]', etc...)
2631
	 * @param array	 $filename_list       List of files to attach (full path of filename on file system)
2632
	 * @param array	 $mimetype_list       List of MIME type of attached files
2633
	 * @param array	 $mimefilename_list   List of attached file name in message
2634
	 * @return void
2635
	 */
2636
	public function sendTicketMessageByEmail($subject, $message, $send_internal_cc = 0, $array_receiver = array(), $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array())
2637
	{
2638
		global $conf, $langs;
2639
2640
		if ($conf->global->TICKET_DISABLE_ALL_MAILS) {
2641
			dol_syslog(get_class($this).'::sendTicketMessageByEmail: Emails are disable into ticket setup by option TICKET_DISABLE_ALL_MAILS', LOG_WARNING);
2642
			return '';
2643
		}
2644
2645
		$langs->load("mails");
2646
2647
		include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
2648
		//$contactstatic = new Contact($this->db);
2649
2650
		// If no receiver defined, load all ticket linked contacts
2651
		if (!is_array($array_receiver) || !count($array_receiver) > 0) {
2652
			$array_receiver = $this->getInfosTicketInternalContact();
2653
			$array_receiver = array_merge($array_receiver, $this->getInfosTicketExternalContact());
2654
		}
2655
2656
		if ($send_internal_cc) {
2657
			$sendtocc = $conf->global->TICKET_NOTIFICATION_EMAIL_FROM;
2658
		}
2659
2660
		$from = $conf->global->TICKET_NOTIFICATION_EMAIL_FROM;
2661
		if (is_array($array_receiver) && count($array_receiver) > 0) {
2662
			foreach ($array_receiver as $key => $receiver)
2663
			{
2664
				$deliveryreceipt = 0;
2665
				$filepath = $filename_list;
2666
				$filename = $mimefilename_list;
2667
				$mimetype = $mimetype_list;
2668
2669
				$message_to_send = dol_nl2br($message);
2670
2671
				// Envoi du mail
2672
				if (!empty($conf->global->TICKET_DISABLE_MAIL_AUTOCOPY_TO)) {
2673
					$old_MAIN_MAIL_AUTOCOPY_TO = $conf->global->MAIN_MAIL_AUTOCOPY_TO;
2674
					$conf->global->MAIN_MAIL_AUTOCOPY_TO = '';
2675
				}
2676
				include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2677
				$trackid = "tic".$this->id;
2678
				$mailfile = new CMailFile($subject, $receiver, $from, $message_to_send, $filepath, $mimetype, $filename, $sendtocc, '', $deliveryreceipt, -1, '', '', $trackid);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $sendtocc does not seem to be defined for all execution paths leading up to this point.
Loading history...
2679
				if ($mailfile->error) {
2680
					setEventMessages($mailfile->error, null, 'errors');
2681
				} else {
2682
					$result = $mailfile->sendfile();
2683
					if ($result) {
2684
						setEventMessages($langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($from, 2), $mailfile->getValidAddress($receiver, 2)), null, 'mesgs');
2685
					} else {
2686
						$langs->load("other");
2687
						if ($mailfile->error) {
2688
							setEventMessages($langs->trans('ErrorFailedToSendMail', $from, $receiver), null, 'errors');
2689
							dol_syslog($langs->trans('ErrorFailedToSendMail', $from, $receiver).' : '.$mailfile->error);
2690
						} else {
2691
							setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'errors');
2692
						}
2693
					}
2694
				}
2695
				if (!empty($conf->global->TICKET_DISABLE_MAIL_AUTOCOPY_TO)) {
2696
					$conf->global->MAIN_MAIL_AUTOCOPY_TO = $old_MAIN_MAIL_AUTOCOPY_TO;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $old_MAIN_MAIL_AUTOCOPY_TO does not seem to be defined for all execution paths leading up to this point.
Loading history...
2697
				}
2698
			}
2699
		} else {
2700
			$langs->load("other");
2701
			setEventMessages($langs->trans('ErrorMailRecipientIsEmptyForSendTicketMessage'), null, 'warnings');
2702
		}
2703
	}
2704
2705
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2706
	/**
2707
	 *      Load indicators for dashboard (this->nbtodo and this->nbtodolate)
2708
	 *
2709
	 *      @param          User	$user   Object user
2710
	 *      @param          int		$mode   "opened" for askprice to close, "signed" for proposal to invoice
2711
	 *      @return         int             <0 if KO, >0 if OK
2712
	 */
2713
	public function load_board($user, $mode)
2714
	{
2715
		// phpcs:enable
2716
		global $conf, $user, $langs;
2717
2718
		$now = dol_now();
2719
2720
		$this->nbtodo = $this->nbtodolate = 0;
2721
		$clause = " WHERE";
2722
2723
		$sql = "SELECT p.rowid, p.ref, p.datec as datec";
2724
		$sql .= " FROM ".MAIN_DB_PREFIX."ticket as p";
2725
		if (!$user->rights->societe->client->voir && !$user->socid)
2726
		{
2727
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc";
2728
			$sql .= " WHERE sc.fk_user = ".$user->id;
2729
			$clause = " AND";
2730
		}
2731
		$sql .= $clause." p.entity IN (".getEntity('ticket').")";
2732
		if ($mode == 'opened') $sql .= " AND p.fk_statut NOT IN (".Ticket::STATUS_CLOSED.", ".Ticket::STATUS_CANCELED.")";
2733
		if ($user->socid) $sql .= " AND p.fk_soc = ".$user->socid;
2734
2735
		$resql = $this->db->query($sql);
2736
		if ($resql)
2737
		{
2738
			$label = $labelShort = '';
2739
			$status = '';
2740
			if ($mode == 'opened') {
2741
				$status = 'openall';
2742
				//$delay_warning = $conf->ticket->warning_delay;
2743
				$delay_warning = 0;
2744
				$label = $langs->trans("MenuListNonClosed");
2745
				$labelShort = $langs->trans("MenuListNonClosed");
2746
			}
2747
2748
			$response = new WorkboardResponse();
2749
			//$response->warning_delay = $delay_warning / 60 / 60 / 24;
2750
			$response->label = $label;
2751
			$response->labelShort = $labelShort;
2752
			$response->url = DOL_URL_ROOT.'/ticket/list.php?search_fk_statut[]='.$status;
2753
			$response->img = img_object('', "ticket");
2754
2755
			// This assignment in condition is not a bug. It allows walking the results.
2756
			while ($obj = $this->db->fetch_object($resql))
2757
			{
2758
				$response->nbtodo++;
2759
				if ($mode == 'opened')
2760
				{
2761
					$datelimit = $this->db->jdate($obj->datefin);
2762
					if ($datelimit < ($now - $delay_warning))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $delay_warning does not seem to be defined for all execution paths leading up to this point.
Loading history...
2763
					{
2764
						//$response->nbtodolate++;
2765
					}
2766
				}
2767
			}
2768
			return $response;
2769
		}
2770
		else
2771
		{
2772
			$this->error = $this->db->lasterror();
2773
			return -1;
2774
		}
2775
	}
2776
2777
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2778
	/**
2779
	 *      Load indicator this->nb of global stats widget
2780
	 *
2781
	 *      @return     int         <0 if ko, >0 if ok
2782
	 */
2783
	public function load_state_board()
2784
	{
2785
		// phpcs:enable
2786
		global $conf, $user;
2787
2788
		$this->nb = array();
2789
		$clause = "WHERE";
2790
2791
		$sql = "SELECT count(p.rowid) as nb";
2792
		$sql .= " FROM ".MAIN_DB_PREFIX."ticket as p";
2793
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
2794
		if (!$user->rights->societe->client->voir && !$user->socid)
2795
		{
2796
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2797
			$sql .= " WHERE sc.fk_user = ".$user->id;
2798
			$clause = "AND";
2799
		}
2800
		$sql .= " ".$clause." p.entity IN (".getEntity('ticket').")";
2801
2802
		$resql = $this->db->query($sql);
2803
		if ($resql)
2804
		{
2805
			// This assignment in condition is not a bug. It allows walking the results.
2806
			while ($obj = $this->db->fetch_object($resql))
2807
			{
2808
				$this->nb["ticket"] = $obj->nb;
2809
			}
2810
			$this->db->free($resql);
2811
			return 1;
2812
		}
2813
		else
2814
		{
2815
			dol_print_error($this->db);
2816
			$this->error = $this->db->lasterror();
2817
			return -1;
2818
		}
2819
	}
2820
}
2821
2822
2823
/**
2824
 * Ticket line Class
2825
 */
2826
class TicketsLine
2827
{
2828
	/**
2829
	 * @var int ID
2830
	 * @deprecated
2831
	 */
2832
	public $rowid;
2833
2834
	/**
2835
	 * @var int ID
2836
	 */
2837
	public $id;
2838
2839
	/**
2840
	 * @var string  $ref    Ticket reference
2841
	 */
2842
	public $ref;
2843
2844
	/**
2845
	 * Hash to identify ticket
2846
	 */
2847
	public $track_id;
2848
2849
	/**
2850
	 * @var int Thirdparty ID
2851
	 */
2852
	public $fk_soc;
2853
2854
	/**
2855
	 * Project ID
2856
	 */
2857
	public $fk_project;
2858
2859
	/**
2860
	 * Person email who have create ticket
2861
	 */
2862
	public $origin_email;
2863
2864
	/**
2865
	 * User id who have create ticket
2866
	 */
2867
	public $fk_user_create;
2868
2869
	/**
2870
	 * User id who have ticket assigned
2871
	 */
2872
	public $fk_user_assign;
2873
2874
	/**
2875
	 * Ticket subject
2876
	 */
2877
	public $subject;
2878
2879
	/**
2880
	 * Ticket message
2881
	 */
2882
	public $message;
2883
2884
	/**
2885
	 * Ticket statut
2886
	 */
2887
	public $fk_statut;
2888
2889
	/**
2890
	 * State resolution
2891
	 */
2892
	public $resolution;
2893
2894
	/**
2895
	 * Progress in percent
2896
	 */
2897
	public $progress;
2898
2899
	/**
2900
	 * Duration for ticket
2901
	 */
2902
	public $timing;
2903
2904
	/**
2905
	 * Type code
2906
	 */
2907
	public $type_code;
2908
2909
	/**
2910
	 * Category code
2911
	 */
2912
	public $category_code;
2913
2914
	/**
2915
	 * Severity code
2916
	 */
2917
	public $severity_code;
2918
2919
	/**
2920
	 * Type label
2921
	 */
2922
	public $type_label;
2923
2924
	/**
2925
	 * Category label
2926
	 */
2927
	public $category_label;
2928
2929
	/**
2930
	 * Severity label
2931
	 */
2932
	public $severity_label;
2933
2934
	/**
2935
	 * Creation date
2936
	 */
2937
	public $datec = '';
2938
2939
	/**
2940
	 * Read date
2941
	 */
2942
	public $date_read = '';
2943
2944
	/**
2945
	 * Close ticket date
2946
	 */
2947
	public $date_close = '';
2948
}
2949