dolibarr 22.0.5
api_agendaevents.class.php
1<?php
2/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3 * Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2025 William Mead <william@m34d.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21use Luracast\Restler\RestException;
22
23require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
24
25
35{
39 public static $FIELDS = array(
40 'userownerid',
41 'type_code'
42 );
43
47 public $actioncomm;
48
49
53 public function __construct()
54 {
55 global $db, $conf;
56 $this->db = $db;
57 $this->actioncomm = new ActionComm($this->db);
58 }
59
72 public function get($id)
73 {
74 if (!DolibarrApiAccess::$user->hasRight('agenda', 'myactions', 'read')) {
75 throw new RestException(403, "Insufficient rights to read an event");
76 }
77 if ($id === 0) {
78 $result = $this->actioncomm->initAsSpecimen();
79 } else {
80 $result = $this->actioncomm->fetch($id);
81 if ($result) {
82 $this->actioncomm->fetch_optionals();
83 $this->actioncomm->fetchObjectLinked();
84 }
85 }
86 if (!$result) {
87 throw new RestException(404, 'Agenda Events not found');
88 }
89
90 if (!DolibarrApiAccess::$user->hasRight('agenda', 'allactions', 'read') && $this->actioncomm->userownerid != DolibarrApiAccess::$user->id) {
91 throw new RestException(403, 'Insufficient rights to read event of this owner id. Your id is '.DolibarrApiAccess::$user->id);
92 }
93
94 if (!DolibarrApi::_checkAccessToResource('agenda', $this->actioncomm->id, 'actioncomm', '', 'fk_soc', 'id')) {
95 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
96 }
97 return $this->_cleanObjectDatas($this->actioncomm);
98 }
99
122 public function index($sortfield = "t.id", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = '', $sqlfilters = '', $properties = '', $pagination_data = false)
123 {
124 global $db, $conf;
125
126 $obj_ret = array();
127
128 if (!DolibarrApiAccess::$user->hasRight('agenda', 'myactions', 'read')) {
129 throw new RestException(403, "Insufficient rights to read events");
130 }
131
132 // case of external user
133 $socid = DolibarrApiAccess::$user->socid ?: 0;
134
135 // If the internal user must only see his customers, force searching by him
136 $search_sale = 0;
137 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socid) {
138 $search_sale = DolibarrApiAccess::$user->id;
139 }
140 if (!isModEnabled('societe')) {
141 $search_sale = 0; // If module thirdparty not enabled, sale representative is something that does not exists
142 }
143
144 $sql = "SELECT t.id";
145 $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm AS t";
146 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."actioncomm_extrafields AS ef ON (ef.fk_object = t.id)"; // Modification VMR Global Solutions to include extrafields as search parameters in the API GET call, so we will be able to filter on extrafields
147 $sql .= ' WHERE t.entity IN ('.getEntity('agenda').')';
148 if ($user_ids) {
149 $sql .= " AND t.fk_user_action IN (".$this->db->sanitize($user_ids).")";
150 }
151 // $user_ids is provided by the caller, so it can not be the only owner filter. A user without the
152 // "read all actions" right must never see the events of somebody else, whatever it asks for.
153 if (!DolibarrApiAccess::$user->hasRight('agenda', 'allactions', 'read')) {
154 $childids = DolibarrApiAccess::$user->getAllChildIds(1);
155 $sql .= " AND t.fk_user_action IN (".$this->db->sanitize(implode(',', $childids)).")";
156 }
157 if ($socid > 0) {
158 $sql .= " AND t.fk_soc = ".((int) $socid);
159 }
160 // Search on sale representative
161 if ($search_sale && $search_sale != '-1') {
162 if ($search_sale == -2) {
163 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
164 } elseif ($search_sale > 0) {
165 $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc AND sc.fk_user = ".((int) $search_sale).")";
166 }
167 }
168 // Add sql filters
169 if ($sqlfilters) {
170 $errormessage = '';
171 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
172 if ($errormessage) {
173 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
174 }
175 }
176
177 //this query will return total orders with the filters given
178 $sqlTotals = str_replace('SELECT t.id', 'SELECT count(t.id) as total', $sql);
179
180 $sql .= $this->db->order($sortfield, $sortorder);
181 if ($limit) {
182 if ($page < 0) {
183 $page = 0;
184 }
185 $offset = $limit * $page;
186
187 $sql .= $this->db->plimit($limit + 1, $offset);
188 }
189
190 $result = $this->db->query($sql);
191
192 if ($result) {
193 $i = 0;
194 $num = $this->db->num_rows($result);
195 $min = min($num, ($limit <= 0 ? $num : $limit));
196 while ($i < $min) {
197 $obj = $this->db->fetch_object($result);
198 $actioncomm_static = new ActionComm($this->db);
199 if ($actioncomm_static->fetch($obj->id)) {
200 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($actioncomm_static), $properties);
201 }
202 $i++;
203 }
204 } else {
205 throw new RestException(503, 'Error when retrieve Agenda Event list : '.$this->db->lasterror());
206 }
207
208 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
209 if ($pagination_data) {
210 $totalsResult = $this->db->query($sqlTotals);
211 $total = $this->db->fetch_object($totalsResult)->total;
212
213 $tmp = $obj_ret;
214 $obj_ret = [];
215
216 $obj_ret['data'] = $tmp;
217 $obj_ret['pagination'] = [
218 'total' => (int) $total,
219 'page' => $page, //count starts from 0
220 'page_count' => (int) ceil((int) $total / $limit),
221 'limit' => $limit
222 ];
223 }
224
225 return $obj_ret;
226 }
227
240 public function post($request_data = null)
241 {
242 if (!DolibarrApiAccess::$user->hasRight('agenda', 'myactions', 'create')) {
243 throw new RestException(403, "Insufficient rights to create your Agenda Event");
244 }
245 if (!DolibarrApiAccess::$user->hasRight('agenda', 'allactions', 'create') && DolibarrApiAccess::$user->id != $request_data['userownerid']) {
246 throw new RestException(403, "Insufficient rights to create an Agenda Event for owner id ".$request_data['userownerid'].' Your id is '.DolibarrApiAccess::$user->id);
247 }
248
249 // Check mandatory fields
250 $result = $this->_validate($request_data);
251
252 foreach ($request_data as $field => $value) {
253 if ($field === 'caller') {
254 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
255 $this->actioncomm->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
256 continue;
257 }
258
259 $this->actioncomm->$field = $this->_checkValForAPI($field, $value, $this->actioncomm);
260 }
261 /*if (isset($request_data["lines"])) {
262 $lines = array();
263 foreach ($request_data["lines"] as $line) {
264 array_push($lines, (object) $line);
265 }
266 $this->expensereport->lines = $lines;
267 }*/
268
269 if ($this->actioncomm->create(DolibarrApiAccess::$user) < 0) {
270 throw new RestException(500, "Error creating event", array_merge(array($this->actioncomm->error), $this->actioncomm->errors));
271 }
272
273 return $this->actioncomm->id;
274 }
275
276
290 public function put($id, $request_data = null)
291 {
292 if (!DolibarrApiAccess::$user->hasRight('agenda', 'myactions', 'create')) {
293 throw new RestException(403, "Insufficient rights to create your Agenda Event");
294 }
295 if (!DolibarrApiAccess::$user->hasRight('agenda', 'allactions', 'create') && DolibarrApiAccess::$user->id != $request_data['userownerid']) {
296 throw new RestException(403, "Insufficient rights to create an Agenda Event for owner id ".$request_data['userownerid'].' Your id is '.DolibarrApiAccess::$user->id);
297 }
298
299 $result = $this->actioncomm->fetch($id);
300 if ($result) {
301 $this->actioncomm->fetch_optionals();
302 $this->actioncomm->fetch_userassigned();
303 $this->actioncomm->oldcopy = clone $this->actioncomm; // @phan-suppress-current-line PhanTypeMismatchProperty
304 }
305 if (!$result) {
306 throw new RestException(404, 'actioncomm not found');
307 }
308
309 if (!DolibarrApi::_checkAccessToResource('actioncomm', $this->actioncomm->id, 'actioncomm', '', 'fk_soc', 'id')) {
310 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
311 }
312 // The test above on userownerid looks at the owner posted in the request, not at the owner of the
313 // event being updated, and actioncomm is not in the $checkhierarchy list of checkUserAccessToObject().
314 // So the event of another user must be refused here, the same way get() does it.
315 if (!DolibarrApiAccess::$user->hasRight('agenda', 'allactions', 'read') && $this->actioncomm->userownerid != DolibarrApiAccess::$user->id) {
316 throw new RestException(403, 'Insufficient rights to update event of this owner id. Your id is '.DolibarrApiAccess::$user->id);
317 }
318 foreach ($request_data as $field => $value) {
319 if ($field == 'id') {
320 continue;
321 }
322 if ($field === 'caller') {
323 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
324 $this->actioncomm->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
325 continue;
326 }
327
328 if ($field == 'array_options' && is_array($value)) {
329 foreach ($value as $index => $val) {
330 $this->actioncomm->array_options[$index] = $this->_checkValForAPI($field, $val, $this->actioncomm);
331 }
332 continue;
333 }
334 $this->actioncomm->$field = $this->_checkValForAPI($field, $value, $this->actioncomm);
335 }
336
337 // Returning false sent back an HTTP 200 with a body of false, so a refused update looked like a
338 // success to the caller. update() returns <= 0 on an error, which is an error for the API too.
339 if ($this->actioncomm->update(DolibarrApiAccess::$user, 1) <= 0) {
340 throw new RestException(500, 'Error when updating Agenda Event : '.$this->actioncomm->errorsToString());
341 }
342
343 return $this->get($id);
344 }
345
359 public function delete($id)
360 {
361 if (!DolibarrApiAccess::$user->hasRight('agenda', 'myactions', 'delete')) {
362 throw new RestException(403, "Insufficient rights to delete your Agenda Event");
363 }
364
365 $result = $this->actioncomm->fetch($id);
366 if ($result) {
367 $this->actioncomm->fetch_optionals();
368 $this->actioncomm->fetch_userassigned();
369 $this->actioncomm->oldcopy = clone $this->actioncomm; // @phan-suppress-current-line PhanTypeMismatchProperty
370 }
371
372 if (!DolibarrApiAccess::$user->hasRight('agenda', 'allactions', 'delete') && DolibarrApiAccess::$user->id != $this->actioncomm->userownerid) {
373 throw new RestException(403, "Insufficient rights to delete an Agenda Event of owner id ".$this->actioncomm->userownerid.' Your id is '.DolibarrApiAccess::$user->id);
374 }
375
376 if (!$result) {
377 throw new RestException(404, 'Agenda Event not found');
378 }
379
380 if (!DolibarrApi::_checkAccessToResource('actioncomm', $this->actioncomm->id, 'actioncomm', '', 'fk_soc', 'id')) {
381 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
382 }
383
384 // delete() is documented int<-2,1> and returns -1 or -2 on an error, and !(-1) is false, so a failed
385 // delete went past this test and the API answered 200 "Agenda Event deleted" with the event still there.
386 if ($this->actioncomm->delete(DolibarrApiAccess::$user) <= 0) {
387 throw new RestException(500, 'Error when delete Agenda Event : '.$this->actioncomm->error);
388 }
389
390 return array(
391 'success' => array(
392 'code' => 200,
393 'message' => 'Agenda Event deleted'
394 )
395 );
396 }
397
405 private function _validate($data)
406 {
407 if ($data === null) {
408 $data = array();
409 }
410 $event = array();
411 foreach (AgendaEvents::$FIELDS as $field) {
412 if (!isset($data[$field])) {
413 throw new RestException(400, "$field field missing");
414 }
415 $event[$field] = $data[$field];
416 }
417 return $event;
418 }
419
420 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
427 protected function _cleanObjectDatas($object)
428 {
429 // phpcs:enable
430 $object = parent::_cleanObjectDatas($object);
431
432 unset($object->note); // already in note_private or note_public
433 unset($object->usermod);
434 unset($object->libelle);
435 unset($object->context);
436 unset($object->canvas);
437 unset($object->contact);
438 unset($object->contact_id);
439 unset($object->thirdparty);
440 unset($object->user);
441 unset($object->origin);
442 unset($object->origin_id);
443 unset($object->ref_ext);
444 unset($object->statut);
445 unset($object->state_code);
446 unset($object->state_id);
447 unset($object->state);
448 unset($object->region);
449 unset($object->region_code);
450 unset($object->country);
451 unset($object->country_id);
452 unset($object->country_code);
453 unset($object->barcode_type);
454 unset($object->barcode_type_code);
455 unset($object->barcode_type_label);
456 unset($object->barcode_type_coder);
457 unset($object->mode_reglement_id);
458 unset($object->cond_reglement_id);
459 unset($object->cond_reglement);
460 unset($object->fk_delivery_address);
461 unset($object->shipping_method_id);
462 unset($object->fk_account);
463 unset($object->total_ht);
464 unset($object->total_tva);
465 unset($object->total_localtax1);
466 unset($object->total_localtax2);
467 unset($object->total_ttc);
468 unset($object->fk_incoterms);
469 unset($object->label_incoterms);
470 unset($object->location_incoterms);
471 unset($object->name);
472 unset($object->lastname);
473 unset($object->firstname);
474 unset($object->civility_id);
475 unset($object->contact);
476 unset($object->societe);
477 unset($object->demand_reason_id);
478 unset($object->transport_mode_id);
479 unset($object->region_id);
480 unset($object->actions);
481 unset($object->lines);
482
483 return $object;
484 }
485}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
Class to manage agenda events (actions)
_cleanObjectDatas($object)
Clean sensible object datas.
_validate($data)
Validate fields before create or update object.
__construct()
Constructor.
put($id, $request_data=null)
Update an agenda event.
index($sortfield="t.id", $sortorder='ASC', $limit=100, $page=0, $user_ids='', $sqlfilters='', $properties='', $pagination_data=false)
List agenda events.
post($request_data=null)
Create an agenda event.
Class for API REST v1.
Definition api.class.php:33
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition api.class.php:98
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79