dolibarr 24.0.2
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 * Copyright (C) 2025 Frédéric France <frederic.france@free.fr>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22use Luracast\Restler\RestException;
23
24require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
25
26
36{
40 public static $FIELDS = array(
41 'userownerid',
42 'type_code'
43 );
44
48 public $actioncomm;
49
50
54 public function __construct()
55 {
56 global $db, $conf;
57 $this->db = $db;
58 $this->actioncomm = new ActionComm($this->db);
59 }
60
73 public function get($id)
74 {
75 if (!DolibarrApiAccess::$user->hasRight('agenda', 'myactions', 'read')) {
76 throw new RestException(403, "Insufficient rights to read an event");
77 }
78 if ($id === 0) {
79 $result = $this->actioncomm->initAsSpecimen();
80 } else {
81 $result = $this->actioncomm->fetch($id);
82 if ($result) {
83 $this->actioncomm->fetch_optionals();
84 $this->actioncomm->fetchObjectLinked();
85 }
86 }
87 if (!$result) {
88 throw new RestException(404, 'Agenda Events not found');
89 }
90
91 if (!DolibarrApiAccess::$user->hasRight('agenda', 'allactions', 'read') && $this->actioncomm->userownerid != DolibarrApiAccess::$user->id) {
92 throw new RestException(403, 'Insufficient rights to read event of this owner id. Your id is '.DolibarrApiAccess::$user->id);
93 }
94
95 if (!DolibarrApi::_checkAccessToResource('agenda', $this->actioncomm->id, 'actioncomm', '', 'fk_soc', 'id')) {
96 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
97 }
98 return $this->_cleanObjectDatas($this->actioncomm);
99 }
100
123 public function index($sortfield = "t.id", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = '', $sqlfilters = '', $properties = '', $pagination_data = false)
124 {
125 global $db, $conf;
126
127 $obj_ret = array();
128
129 if (!DolibarrApiAccess::$user->hasRight('agenda', 'myactions', 'read')) {
130 throw new RestException(403, "Insufficient rights to read events");
131 }
132
133 // case of external user
134 $socid = DolibarrApiAccess::$user->socid ?: 0;
135
136 // If the internal user must only see his customers, force searching by him
137 $search_sale = 0;
138 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socid) {
139 $search_sale = DolibarrApiAccess::$user->id;
140 }
141 if (!isModEnabled('societe')) {
142 $search_sale = 0; // If module thirdparty not enabled, sale representative is something that does not exists
143 }
144
145 $sql = "SELECT t.id";
146 $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm AS t";
147 $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
148 $sql .= ' WHERE t.entity IN ('.getEntity('agenda').')';
149 if ($user_ids) {
150 $sql .= " AND t.fk_user_action IN (".$this->db->sanitize($user_ids).")";
151 }
152 // $user_ids is provided by the caller, so it can not be the only owner filter. A user without the
153 // "read all actions" right must never see the events of somebody else, whatever it asks for.
154 if (!DolibarrApiAccess::$user->hasRight('agenda', 'allactions', 'read')) {
155 $childids = DolibarrApiAccess::$user->getAllChildIds(1);
156 $sql .= " AND t.fk_user_action IN (".$this->db->sanitize(implode(',', $childids)).")";
157 }
158 if ($socid > 0) {
159 $sql .= " AND t.fk_soc = ".((int) $socid);
160 }
161 // Search on sale representative
162 if ($search_sale && $search_sale != '-1') {
163 if ($search_sale == -2) {
164 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
165 } elseif ($search_sale > 0) {
166 $sql .= " AND (t.fk_soc IS NULL OR 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)."))";
167 }
168 }
169 // Add sql filters
170 if ($sqlfilters) {
171 $errormessage = '';
172 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
173 if ($errormessage) {
174 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
175 }
176 }
177
178 //this query will return total orders with the filters given
179 $sqlTotals = str_replace('SELECT t.id', 'SELECT count(t.id) as total', $sql);
180
181 $sql .= $this->db->order($sortfield, $sortorder);
182 if ($limit) {
183 if ($page < 0) {
184 $page = 0;
185 }
186 $offset = $limit * $page;
187
188 $sql .= $this->db->plimit($limit + 1, $offset);
189 }
190
191 $result = $this->db->query($sql);
192
193 if ($result) {
194 $i = 0;
195 $num = $this->db->num_rows($result);
196 $min = min($num, ($limit <= 0 ? $num : $limit));
197 while ($i < $min) {
198 $obj = $this->db->fetch_object($result);
199 $actioncomm_static = new ActionComm($this->db);
200 if ($actioncomm_static->fetch($obj->id)) {
201 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($actioncomm_static), $properties);
202 }
203 $i++;
204 }
205 } else {
206 throw new RestException(503, 'Error when retrieve Agenda Event list : '.$this->db->lasterror());
207 }
208
209 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
210 if ($pagination_data) {
211 $totalsResult = $this->db->query($sqlTotals);
212 $total = $this->db->fetch_object($totalsResult)->total;
213
214 $tmp = $obj_ret;
215 $obj_ret = [];
216
217 $obj_ret['data'] = $tmp;
218 $obj_ret['pagination'] = [
219 'total' => (int) $total,
220 'page' => $page, //count starts from 0
221 'page_count' => (int) ceil((int) $total / $limit),
222 'limit' => $limit
223 ];
224 }
225
226 return $obj_ret;
227 }
228
241 public function post($request_data = null)
242 {
243 if (!DolibarrApiAccess::$user->hasRight('agenda', 'myactions', 'create')) {
244 throw new RestException(403, "Insufficient rights to create your Agenda Event");
245 }
246 if (!DolibarrApiAccess::$user->hasRight('agenda', 'allactions', 'create') && DolibarrApiAccess::$user->id != $request_data['userownerid']) {
247 throw new RestException(403, "Insufficient rights to create an Agenda Event for owner id ".$request_data['userownerid'].' Your id is '.DolibarrApiAccess::$user->id);
248 }
249
250 // Check mandatory fields
251 $result = $this->_validate($request_data);
252
253 foreach ($request_data as $field => $value) {
254 if ($field === 'caller') {
255 // 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
256 $this->actioncomm->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
257 continue;
258 }
259
260 $this->actioncomm->$field = $this->_checkValForAPI($field, $value, $this->actioncomm);
261 }
262 /*if (isset($request_data["lines"])) {
263 $lines = array();
264 foreach ($request_data["lines"] as $line) {
265 array_push($lines, (object) $line);
266 }
267 $this->expensereport->lines = $lines;
268 }*/
269
270 if ($this->actioncomm->create(DolibarrApiAccess::$user) < 0) {
271 throw new RestException(500, "Error creating event", array_merge(array($this->actioncomm->error), $this->actioncomm->errors));
272 }
273
274 return $this->actioncomm->id;
275 }
276
277
291 public function put($id, $request_data = null)
292 {
293 if (!DolibarrApiAccess::$user->hasRight('agenda', 'myactions', 'create')) {
294 throw new RestException(403, "Insufficient rights to create your Agenda Event");
295 }
296 if (!DolibarrApiAccess::$user->hasRight('agenda', 'allactions', 'create') && DolibarrApiAccess::$user->id != $request_data['userownerid']) {
297 throw new RestException(403, "Insufficient rights to create an Agenda Event for owner id ".$request_data['userownerid'].' Your id is '.DolibarrApiAccess::$user->id);
298 }
299
300 $result = $this->actioncomm->fetch($id);
301 if ($result) {
302 $this->actioncomm->fetch_optionals();
303 $this->actioncomm->fetch_userassigned();
304 $this->actioncomm->oldcopy = clone $this->actioncomm; // @phan-suppress-current-line PhanTypeMismatchProperty
305 }
306 if (!$result) {
307 throw new RestException(404, 'actioncomm not found');
308 }
309
310 if (!DolibarrApi::_checkAccessToResource('actioncomm', $this->actioncomm->id, 'actioncomm', '', 'fk_soc', 'id')) {
311 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
312 }
313 // The test above on userownerid looks at the owner posted in the request, not at the owner of the
314 // event being updated, and actioncomm is not in the $checkhierarchy list of checkUserAccessToObject().
315 // So the event of another user must be refused here, the same way get() does it.
316 if (!DolibarrApiAccess::$user->hasRight('agenda', 'allactions', 'read') && $this->actioncomm->userownerid != DolibarrApiAccess::$user->id) {
317 throw new RestException(403, 'Insufficient rights to update event of this owner id. Your id is '.DolibarrApiAccess::$user->id);
318 }
319 foreach ($request_data as $field => $value) {
320 if ($field == 'id') {
321 continue;
322 }
323 if ($field === 'caller') {
324 // 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
325 $this->actioncomm->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
326 continue;
327 }
328
329 if ($field == 'array_options' && is_array($value)) {
330 foreach ($value as $index => $val) {
331 $this->actioncomm->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->actioncomm);
332 }
333 continue;
334 }
335 $this->actioncomm->$field = $this->_checkValForAPI($field, $value, $this->actioncomm);
336 }
337
338 if ($this->actioncomm->update(DolibarrApiAccess::$user, 1) > 0) {
339 return $this->get($id);
340 }
341
342 return false;
343 }
344
358 public function delete($id)
359 {
360 if (!DolibarrApiAccess::$user->hasRight('agenda', 'myactions', 'delete')) {
361 throw new RestException(403, "Insufficient rights to delete your Agenda Event");
362 }
363
364 $result = $this->actioncomm->fetch($id);
365 if ($result) {
366 $this->actioncomm->fetch_optionals();
367 $this->actioncomm->fetch_userassigned();
368 $this->actioncomm->oldcopy = clone $this->actioncomm; // @phan-suppress-current-line PhanTypeMismatchProperty
369 }
370
371 if (!DolibarrApiAccess::$user->hasRight('agenda', 'allactions', 'delete') && DolibarrApiAccess::$user->id != $this->actioncomm->userownerid) {
372 throw new RestException(403, "Insufficient rights to delete an Agenda Event of owner id ".$this->actioncomm->userownerid.' Your id is '.DolibarrApiAccess::$user->id);
373 }
374
375 if (!$result) {
376 throw new RestException(404, 'Agenda Event not found');
377 }
378
379 if (!DolibarrApi::_checkAccessToResource('actioncomm', $this->actioncomm->id, 'actioncomm', '', 'fk_soc', 'id')) {
380 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
381 }
382
383 if (!$this->actioncomm->delete(DolibarrApiAccess::$user)) {
384 throw new RestException(500, 'Error when delete Agenda Event : '.$this->actioncomm->error);
385 }
386
387 return array(
388 'success' => array(
389 'code' => 200,
390 'message' => 'Agenda Event deleted'
391 )
392 );
393 }
394
402 private function _validate($data)
403 {
404 if ($data === null) {
405 $data = array();
406 }
407 $event = array();
408 foreach (AgendaEvents::$FIELDS as $field) {
409 if (!isset($data[$field])) {
410 throw new RestException(400, "$field field missing");
411 }
412 $event[$field] = $data[$field];
413 }
414 return $event;
415 }
416
417 // 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:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
Class to manage agenda events (actions)
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
_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:35
_checkValExtrafieldsForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $parenttableforentity='')
Check access by user to a given resource.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
isModEnabled($module)
Is Dolibarr module enabled.