dolibarr 22.0.5
api_webhook.class.php
1<?php
2/* Copyright (C) 2024 Florian Charlaix <fcharlaix@easya.solutions>
3 * Copyright (C) 2025 MDW <mdeweerd@users.noreply.github.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
19use Luracast\Restler\RestException;
20
27class Webhook extends DolibarrApi
28{
32 public static $FIELDS = array(
33 'url',
34 'trigger_codes'
35 );
36
40 public $target;
41
45 public function __construct()
46 {
47 global $db;
48 $this->db = $db;
49
50 require_once DOL_DOCUMENT_ROOT.'/webhook/class/target.class.php';
51
52 $this->target = new Target($this->db);
53 }
54
65 public function get($id)
66 {
67 return $this->_fetch($id);
68 }
69
86 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
87 {
88 $obj_ret = array();
89
90 if (!DolibarrApiAccess::$user->hasRight('webhook', 'webhook_target', 'read')) {
91 throw new RestException(403);
92 }
93
94 $sql = "SELECT t.rowid";
95 $sql .= " FROM ".MAIN_DB_PREFIX."webhook_target as t";
96
97 // Add sql filters
98 if ($sqlfilters) {
99 $errormessage = '';
100 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
101 if ($errormessage) {
102 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
103 }
104 }
105
106 //this query will return total target with the filters given
107 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
108
109 $sql .= $this->db->order($sortfield, $sortorder);
110 if ($limit) {
111 if ($page < 0) {
112 $page = 0;
113 }
114 $offset = $limit * $page;
115
116 $sql .= $this->db->plimit($limit + 1, $offset);
117 }
118
119 $result = $this->db->query($sql);
120 if ($result) {
121 $num = $this->db->num_rows($result);
122 $min = min($num, ($limit <= 0 ? $num : $limit));
123 $i = 0;
124 while ($i < $min) {
125 $obj = $this->db->fetch_object($result);
126 $target_static = new Target($this->db);
127 if ($target_static->fetch($obj->rowid)) {
128 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($target_static), $properties);
129 }
130 $i++;
131 }
132 } else {
133 throw new RestException(503, 'Error when retrieve targets : '.$this->db->lasterror());
134 }
135 if (!count($obj_ret)) {
136 throw new RestException(404, 'Targets not found');
137 }
138
139 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
140 if ($pagination_data) {
141 $totalsResult = $this->db->query($sqlTotals);
142 $total = $this->db->fetch_object($totalsResult)->total;
143
144 $tmp = $obj_ret;
145 $obj_ret = [];
146
147 $obj_ret['data'] = $tmp;
148 $obj_ret['pagination'] = [
149 'total' => (int) $total,
150 'page' => $page, //count starts from 0
151 'page_count' => ceil((int) $total / $limit),
152 'limit' => $limit
153 ];
154 }
155
156 return $obj_ret;
157 }
158
167 public function post($request_data = null)
168 {
169 if (!DolibarrApiAccess::$user->hasRight('webhook', 'webhook_target', 'write')) {
170 throw new RestException(403);
171 }
172
173 if (!is_array($request_data)) {
174 $request_data = array();
175 }
176
177 // Check mandatory fields (not using output, only possible exception is important)
178 $this->_validate($request_data);
179
180 foreach ($request_data as $field => $value) {
181 $this->target->$field = $this->_checkValForAPI($field, $value, $this->target);
182 }
183
184 if (!array_key_exists('status', $request_data)) {
185 $this->target->status = 1;
186 }
187
188 if ($this->target->create(DolibarrApiAccess::$user) < 0) {
189 throw new RestException(500, 'Error creating target', array_merge(array($this->target->error), $this->target->errors));
190 }
191
192 return $this->target->id;
193 }
194
208 public function put($id, $request_data = null)
209 {
210 if (!DolibarrApiAccess::$user->hasRight('webhook', 'webhook_target', 'write')) {
211 throw new RestException(403);
212 }
213
214 $result = $this->target->fetch($id);
215 if (!$result) {
216 throw new RestException(404, 'Target not found');
217 }
218
219 foreach ($request_data as $field => $value) {
220 if ($field == 'id') {
221 continue;
222 }
223 $this->target->$field = $this->_checkValForAPI($field, $value, $this->target);
224 }
225
226 if ($this->target->update(DolibarrApiAccess::$user, 1) > 0) {
227 return $this->get($id);
228 } else {
229 throw new RestException(500, $this->target->error);
230 }
231 }
232
241 public function delete($id)
242 {
243 if (!DolibarrApiAccess::$user->hasRight('webhook', 'webhook_target', 'delete')) {
244 throw new RestException(403);
245 }
246
247 $result = $this->target->fetch($id);
248 if (!$result) {
249 throw new RestException(404, 'Target not found');
250 }
251
252 $res = $this->target->delete(DolibarrApiAccess::$user);
253 if ($res < 0) {
254 throw new RestException(500, "Can't delete target, error occurs");
255 }
256
257 return array(
258 'success' => array(
259 'code' => 200,
260 'message' => 'Target deleted'
261 )
262 );
263 }
264
274 public function listOfTriggers()
275 {
276 if (!DolibarrApiAccess::$user->hasRight('webhook', 'webhook_target', 'read')) {
277 throw new RestException(403);
278 }
279
280 $triggers = array();
281
282 $sql = "SELECT c.code, c.label FROM ".MAIN_DB_PREFIX."c_action_trigger as c ORDER BY c.rang ASC";
283 $resql = $this->db->query($sql);
284 if ($resql) {
285 $num = $this->db->num_rows($resql);
286 $i = 0;
287 while ($i < $num) {
288 $obj = $this->db->fetch_object($resql);
289 $triggers[$obj->code] = $obj->label;
290 $i++;
291 }
292 } else {
293 throw new RestException(500, "Can't get list of triggers");
294 }
295
296 return $triggers;
297 }
298
307 private function _validate($data)
308 {
309 if ($data === null) {
310 $data = array();
311 }
312 $target = array();
313 foreach (self::$FIELDS as $field) {
314 if (!isset($data[$field])) {
315 throw new RestException(400, "$field field missing");
316 }
317 $target[$field] = $data[$field];
318 }
319 return $target;
320 }
321
322 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
329 protected function _cleanObjectDatas($object)
330 {
331 // phpcs:enable
332 $object = parent::_cleanObjectDatas($object);
333
334 unset($object->rowid);
335 unset($object->array_options);
336 unset($object->array_languages);
337 unset($object->contacts_ids);
338 unset($object->linkedObjectsIds);
339 unset($object->canvas);
340 unset($object->fk_project);
341 unset($object->contact_id);
342 unset($object->user);
343 unset($object->origin_type);
344 unset($object->origin_id);
345 unset($object->ref_ext);
346 unset($object->statut);
347 unset($object->country_id);
348 unset($object->country_code);
349 unset($object->state_id);
350 unset($object->region_id);
351 unset($object->barcode_type);
352 unset($object->barcode_type_coder);
353 unset($object->mode_reglement_id);
354 unset($object->cond_reglement_id);
355 unset($object->demand_reason_id);
356 unset($object->transport_mode_id);
357 unset($object->shipping_method_id);
358 unset($object->shipping_method);
359 unset($object->fk_multicurrency);
360 unset($object->multicurrency_code);
361 unset($object->multicurrency_tx);
362 unset($object->multicurrency_total_ht);
363 unset($object->multicurrency_total_tva);
364 unset($object->multicurrency_total_ttc);
365 unset($object->multicurrency_total_localtax1);
366 unset($object->multicurrency_total_localtax2);
367 unset($object->last_main_doc);
368 unset($object->fk_account);
369 unset($object->total_ht);
370 unset($object->total_tva);
371 unset($object->total_localtax1);
372 unset($object->total_localtax2);
373 unset($object->total_ttc);
374 unset($object->lines);
375 unset($object->actiontypecode);
376 unset($object->name);
377 unset($object->lastname);
378 unset($object->firstname);
379 unset($object->civility_id);
380 unset($object->date_validation);
381 unset($object->date_modification);
382 unset($object->date_cloture);
383 unset($object->user_author);
384 unset($object->user_creation);
385 unset($object->user_creation_id);
386 unset($object->user_valid);
387 unset($object->user_validation);
388 unset($object->user_validation_id);
389 unset($object->user_closing_id);
390 unset($object->user_modification);
391 unset($object->user_modification_id);
392 unset($object->specimen);
393 unset($object->extraparams);
394 unset($object->product);
395 unset($object->cond_reglement_supplier_id);
396 unset($object->deposit_percent);
397 unset($object->retained_warranty_fk_cond_reglement);
398 unset($object->warehouse_id);
399 unset($object->module);
400
401 return $object;
402 }
403
415 private function _fetch($rowid, $ref = '')
416 {
417 if (!DolibarrApiAccess::$user->hasRight('webhook', 'webhook_target', 'read')) {
418 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login.'. No read permission on target.');
419 }
420
421 if ($rowid === 0) {
422 $result = $this->target->initAsSpecimen();
423 } else {
424 $result = $this->target->fetch($rowid, $ref);
425 }
426
427 if (!$result) {
428 throw new RestException(404, 'Target not found');
429 }
430
431 return $this->_cleanObjectDatas($this->target);
432 }
433}
$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 for API REST v1.
Definition api.class.php:33
_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.
Definition api.class.php:98
Class for Target.
_fetch($rowid, $ref='')
Fetch properties of a target object.
listOfTriggers()
Get the list of all available triggers.
put($id, $request_data=null)
Update target.
post($request_data=null)
Create target object.
_validate($data)
Validate fields before create or update object.
__construct()
Constructor.
_cleanObjectDatas($object)
Clean sensible object datas.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $sqlfilters='', $properties='', $pagination_data=false)
List targets.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria