dolibarr  13.0.2
api_tickets.class.php
1 <?php
2 /* Copyright (C) 2016 Jean-François Ferry <hello@librethic.io>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program. If not, see <https://www.gnu.org/licenses/>.
16  */
17 
18  use Luracast\Restler\RestException;
19 
20 require 'ticket.class.php';
21 require_once DOL_DOCUMENT_ROOT.'/core/lib/ticket.lib.php';
22 
23 
30 class Tickets extends DolibarrApi
31 {
35  public static $FIELDS = array(
36  'subject',
37  'message'
38  );
39 
43  public static $FIELDS_MESSAGES = array(
44  'track_id',
45  'message'
46  );
47 
51  public $ticket;
52 
56  public function __construct()
57  {
58  global $db;
59  $this->db = $db;
60  $this->ticket = new Ticket($this->db);
61  }
62 
75  public function get($id)
76  {
77  return $this->getCommon($id, '', '');
78  }
79 
94  public function getByTrackId($track_id)
95  {
96  return $this->getCommon(0, $track_id, '');
97  }
98 
113  public function getByRef($ref)
114  {
115  try {
116  return $this->getCommon(0, '', $ref);
117  } catch (Exception $e)
118  {
119  throw $e;
120  }
121  }
122 
132  private function getCommon($id = 0, $track_id = '', $ref = '')
133  {
134  if (!DolibarrApiAccess::$user->rights->ticket->read) {
135  throw new RestException(403);
136  }
137 
138  // Check parameters
139  if (($id < 0) && !$track_id && !$ref) {
140  throw new RestException(401, 'Wrong parameters');
141  }
142  if ($id == 0) {
143  $result = $this->ticket->initAsSpecimen();
144  } else {
145  $result = $this->ticket->fetch($id, $ref, $track_id);
146  }
147  if (!$result) {
148  throw new RestException(404, 'Ticket not found');
149  }
150 
151  // String for user assigned
152  if ($this->ticket->fk_user_assign > 0) {
153  $userStatic = new User($this->db);
154  $userStatic->fetch($this->ticket->fk_user_assign);
155  $this->ticket->fk_user_assign_string = $userStatic->firstname.' '.$userStatic->lastname;
156  }
157 
158  // Messages of ticket
159  $messages = array();
160  $this->ticket->loadCacheMsgsTicket();
161  if (is_array($this->ticket->cache_msgs_ticket) && count($this->ticket->cache_msgs_ticket) > 0) {
162  $num = count($this->ticket->cache_msgs_ticket);
163  $i = 0;
164  while ($i < $num) {
165  if ($this->ticket->cache_msgs_ticket[$i]['fk_user_author'] > 0) {
166  $user_action = new User($this->db);
167  $user_action->fetch($this->ticket->cache_msgs_ticket[$i]['fk_user_author']);
168  }
169 
170  // Now define messages
171  $messages[] = array(
172  'id' => $this->ticket->cache_msgs_ticket[$i]['id'],
173  'fk_user_action' => $this->ticket->cache_msgs_ticket[$i]['fk_user_author'],
174  'fk_user_action_socid' => $user_action->socid,
175  'fk_user_action_string' => dolGetFirstLastname($user_action->firstname, $user_action->lastname),
176  'message' => $this->ticket->cache_msgs_ticket[$i]['message'],
177  'datec' => $this->ticket->cache_msgs_ticket[$i]['datec'],
178  'private' => $this->ticket->cache_msgs_ticket[$i]['private']
179  );
180  $i++;
181  }
182  $this->ticket->messages = $messages;
183  }
184 
185  // History
186  $history = array();
187  $this->ticket->loadCacheLogsTicket();
188  if (is_array($this->ticket->cache_logs_ticket) && count($this->ticket->cache_logs_ticket) > 0) {
189  $num = count($this->ticket->cache_logs_ticket);
190  $i = 0;
191  while ($i < $num) {
192  if ($this->ticket->cache_logs_ticket[$i]['fk_user_create'] > 0) {
193  $user_action = new User($this->db);
194  $user_action->fetch($this->ticket->cache_logs_ticket[$i]['fk_user_create']);
195  }
196 
197  // Now define messages
198  $history[] = array(
199  'id' => $this->ticket->cache_logs_ticket[$i]['id'],
200  'fk_user_author' => $this->ticket->cache_msgs_ticket[$i]['fk_user_author'],
201  'fk_user_action' => $this->ticket->cache_logs_ticket[$i]['fk_user_create'],
202  'fk_user_action_string' => dolGetFirstLastname($user_action->firstname, $user_action->lastname),
203  'message' => $this->ticket->cache_logs_ticket[$i]['message'],
204  'datec' => $this->ticket->cache_logs_ticket[$i]['datec'],
205  );
206  $i++;
207  }
208  $this->ticket->history = $history;
209  }
210 
211  if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) {
212  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
213  }
214  return $this->_cleanObjectDatas($this->ticket);
215  }
216 
232  public function index($socid = 0, $sortfield = "t.rowid", $sortorder = "ASC", $limit = 100, $page = 0, $sqlfilters = '')
233  {
234  global $db, $conf;
235 
236  $obj_ret = array();
237 
238  if (!$socid && DolibarrApiAccess::$user->socid) {
239  $socid = DolibarrApiAccess::$user->socid;
240  }
241 
242  // If the internal user must only see his customers, force searching by him
243  if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) {
244  $search_sale = DolibarrApiAccess::$user->id;
245  }
246 
247  $sql = "SELECT t.rowid";
248  if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
249  $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
250  }
251  $sql .= " FROM ".MAIN_DB_PREFIX."ticket as t";
252 
253  if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
254  $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
255  }
256 
257  $sql .= ' WHERE t.entity IN ('.getEntity('ticket', 1).')';
258  if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
259  $sql .= " AND t.fk_soc = sc.fk_soc";
260  }
261  if ($socid > 0) {
262  $sql .= " AND t.fk_soc = ".$socid;
263  }
264  if ($search_sale > 0) {
265  $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
266  }
267 
268  // Insert sale filter
269  if ($search_sale > 0) {
270  $sql .= " AND sc.fk_user = ".$search_sale;
271  }
272  // Add sql filters
273  if ($sqlfilters) {
274  if (!DolibarrApi::_checkFilters($sqlfilters)) {
275  throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
276  }
277  $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
278  $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
279  }
280 
281  $sql .= $this->db->order($sortfield, $sortorder);
282 
283  if ($limit) {
284  if ($page < 0) {
285  $page = 0;
286  }
287  $offset = $limit * $page;
288 
289  $sql .= $this->db->plimit($limit, $offset);
290  }
291 
292  $result = $this->db->query($sql);
293  if ($result) {
294  $num = $this->db->num_rows($result);
295  $i = 0;
296  while ($i < $num) {
297  $obj = $this->db->fetch_object($result);
298  $ticket_static = new Ticket($this->db);
299  if ($ticket_static->fetch($obj->rowid)) {
300  if ($ticket_static->fk_user_assign > 0) {
301  $userStatic = new User($this->db);
302  $userStatic->fetch($ticket_static->fk_user_assign);
303  $ticket_static->fk_user_assign_string = $userStatic->firstname.' '.$userStatic->lastname;
304  }
305  $obj_ret[] = $this->_cleanObjectDatas($ticket_static);
306  }
307  $i++;
308  }
309  } else {
310  throw new RestException(503, 'Error when retrieve ticket list');
311  }
312  if (!count($obj_ret)) {
313  throw new RestException(404, 'No ticket found');
314  }
315  return $obj_ret;
316  }
317 
324  public function post($request_data = null)
325  {
326  $ticketstatic = new Ticket($this->db);
327  if (!DolibarrApiAccess::$user->rights->ticket->write) {
328  throw new RestException(401);
329  }
330  // Check mandatory fields
331  $result = $this->_validate($request_data);
332 
333  foreach ($request_data as $field => $value) {
334  $this->ticket->$field = $value;
335  }
336  if (empty($this->ticket->ref)) {
337  $this->ticket->ref = $ticketstatic->getDefaultRef();
338  }
339  if (empty($this->ticket->track_id)) {
340  $this->ticket->track_id = generate_random_id(16);
341  }
342 
343  if ($this->ticket->create(DolibarrApiAccess::$user) < 0) {
344  throw new RestException(500, "Error creating ticket", array_merge(array($this->ticket->error), $this->ticket->errors));
345  }
346 
347  return $this->ticket->id;
348  }
349 
357  public function postNewMessage($request_data = null)
358  {
359  $ticketstatic = new Ticket($this->db);
360  if (!DolibarrApiAccess::$user->rights->ticket->write) {
361  throw new RestException(401);
362  }
363  // Check mandatory fields
364  $result = $this->_validateMessage($request_data);
365 
366  foreach ($request_data as $field => $value) {
367  $this->ticket->$field = $value;
368  }
369  $ticketMessageText = $this->ticket->message;
370  $result = $this->ticket->fetch('', '', $this->ticket->track_id);
371  if (!$result) {
372  throw new RestException(404, 'Ticket not found');
373  }
374  $this->ticket->message = $ticketMessageText;
375  if (!$this->ticket->createTicketMessage(DolibarrApiAccess::$user)) {
376  throw new RestException(500);
377  }
378  return $this->ticket->id;
379  }
380 
389  public function put($id, $request_data = null)
390  {
391  if (!DolibarrApiAccess::$user->rights->ticket->write) {
392  throw new RestException(401);
393  }
394 
395  $result = $this->ticket->fetch($id);
396  if (!$result) {
397  throw new RestException(404, 'Ticket not found');
398  }
399 
400  if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) {
401  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
402  }
403 
404  foreach ($request_data as $field => $value) {
405  $this->ticket->$field = $value;
406  }
407 
408  if ($this->ticket->update($id, DolibarrApiAccess::$user)) {
409  return $this->get($id);
410  }
411 
412  return false;
413  }
414 
422  public function delete($id)
423  {
424  if (!DolibarrApiAccess::$user->rights->ticket->delete) {
425  throw new RestException(401);
426  }
427  $result = $this->ticket->fetch($id);
428  if (!$result) {
429  throw new RestException(404, 'Ticket not found');
430  }
431 
432  if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) {
433  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
434  }
435 
436  if (!$this->ticket->delete($id)) {
437  throw new RestException(500);
438  }
439 
440  return array(
441  'success' => array(
442  'code' => 200,
443  'message' => 'Ticket deleted'
444  )
445  );
446  }
447 
456  private function _validate($data)
457  {
458  $ticket = array();
459  foreach (Tickets::$FIELDS as $field) {
460  if (!isset($data[$field])) {
461  throw new RestException(400, "$field field missing");
462  }
463  $ticket[$field] = $data[$field];
464  }
465  return $ticket;
466  }
467 
476  private function _validateMessage($data)
477  {
478  $ticket = array();
479  foreach (Tickets::$FIELDS_MESSAGES as $field) {
480  if (!isset($data[$field])) {
481  throw new RestException(400, "$field field missing");
482  }
483  $ticket[$field] = $data[$field];
484  }
485  return $ticket;
486  }
487 
488  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
498  protected function _cleanObjectDatas($object)
499  {
500  // phpcs:enable
501  $object = parent::_cleanObjectDatas($object);
502 
503  // Other attributes to clean
504  $attr2clean = array(
505  "contact",
506  "contact_id",
507  "ref_previous",
508  "ref_next",
509  "ref_ext",
510  "table_element_line",
511  "statut",
512  "country",
513  "country_id",
514  "country_code",
515  "barcode_type",
516  "barcode_type_code",
517  "barcode_type_label",
518  "barcode_type_coder",
519  "mode_reglement_id",
520  "cond_reglement_id",
521  "cond_reglement",
522  "fk_delivery_address",
523  "shipping_method_id",
524  "modelpdf",
525  "fk_account",
526  "note_public",
527  "note_private",
528  "note",
529  "total_ht",
530  "total_tva",
531  "total_localtax1",
532  "total_localtax2",
533  "total_ttc",
534  "fk_incoterms",
535  "label_incoterms",
536  "location_incoterms",
537  "name",
538  "lastname",
539  "firstname",
540  "civility_id",
541  "canvas",
542  "cache_msgs_ticket",
543  "cache_logs_ticket",
544  "cache_types_tickets",
545  "cache_category_tickets",
546  "regeximgext",
547  "statuts_short",
548  "statuts"
549  );
550  foreach ($attr2clean as $toclean) {
551  unset($object->$toclean);
552  }
553 
554  // If object has lines, remove $db property
555  if (isset($object->lines) && count($object->lines) > 0) {
556  $nboflines = count($object->lines);
557  for ($i = 0; $i < $nboflines; $i++) {
558  $this->_cleanObjectDatas($object->lines[$i]);
559  }
560  }
561 
562  // If object has linked objects, remove $db property
563  if (isset($object->linkedObjects) && count($object->linkedObjects) > 0) {
564  foreach ($object->linkedObjects as $type_object => $linked_object) {
565  foreach ($linked_object as $object2clean) {
566  $this->_cleanObjectDatas($object2clean);
567  }
568  }
569  }
570  return $object;
571  }
572 }
getCommon($id=0, $track_id= '', $ref= '')
Get properties of a Ticket object Return an array with ticket informations.
_validateMessage($data)
Validate fields before create or update object message.
index($socid=0, $sortfield="t.rowid", $sortorder="ASC", $limit=100, $page=0, $sqlfilters= '')
List tickets.
getByTrackId($track_id)
Get properties of a Ticket object from track id.
postNewMessage($request_data=null)
Create ticket object.
Class to manage Dolibarr users.
Definition: user.class.php:44
$conf db
API class for accounts.
Definition: inc.php:54
Class to manage ticket.
_checkFilters($sqlfilters)
Return if a $sqlfilters parameter is valid.
Definition: api.class.php:278
Class for API REST v1.
Definition: api.class.php:30
_cleanObjectDatas($object)
Clean sensible object datas.
generate_random_id($car=16)
Generate a random id.
Definition: ticket.lib.php:180
__construct()
Constructor.
getByRef($ref)
Get properties of a Ticket object from ref.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename= '', $feature2= '', $dbt_keyfield= 'fk_soc', $dbt_select= 'rowid')
Check user access to a resource.
Definition: api.class.php:252
put($id, $request_data=null)
Update ticket.
_validate($data)
Validate fields before create or update object.
post($request_data=null)
Create ticket object.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.