dolibarr 21.0.0-alpha
api_webhook.class.php
1<?php
2/* Copyright (C) 2024 Florian Charlaix <fcharlaix@easya.solutions>
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
18use Luracast\Restler\RestException;
19
27class Webhook extends DolibarrApi
28{
33 public static $FIELDS = array(
34 'url',
35 'trigger_codes'
36 );
37
41 public $target;
42
46 public function __construct()
47 {
48 global $db;
49 $this->db = $db;
50
51 require_once DOL_DOCUMENT_ROOT.'/webhook/class/target.class.php';
52
53 $this->target = new Target($this->db);
54 }
55
66 public function get($id)
67 {
68 return $this->_fetch($id);
69 }
70
85 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
86 {
87 $obj_ret = array();
88
89 if (!DolibarrApiAccess::$user->hasRight('webhook', 'webhook_target', 'read')) {
90 throw new RestException(403);
91 }
92
93 $sql = "SELECT t.rowid";
94 $sql .= " FROM ".MAIN_DB_PREFIX."webhook_target as t";
95
96 // Add sql filters
97 if ($sqlfilters) {
98 $errormessage = '';
99 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
100 if ($errormessage) {
101 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
102 }
103 }
104
105 //this query will return total target with the filters given
106 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
107
108 $sql .= $this->db->order($sortfield, $sortorder);
109 if ($limit) {
110 if ($page < 0) {
111 $page = 0;
112 }
113 $offset = $limit * $page;
114
115 $sql .= $this->db->plimit($limit + 1, $offset);
116 }
117
118 $result = $this->db->query($sql);
119 if ($result) {
120 $num = $this->db->num_rows($result);
121 $min = min($num, ($limit <= 0 ? $num : $limit));
122 $i = 0;
123 while ($i < $min) {
124 $obj = $this->db->fetch_object($result);
125 $target_static = new Target($this->db);
126 if ($target_static->fetch($obj->rowid)) {
127 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($target_static), $properties);
128 }
129 $i++;
130 }
131 } else {
132 throw new RestException(503, 'Error when retrieve targets : '.$this->db->lasterror());
133 }
134 if (!count($obj_ret)) {
135 throw new RestException(404, 'Targets not found');
136 }
137
138 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
139 if ($pagination_data) {
140 $totalsResult = $this->db->query($sqlTotals);
141 $total = $this->db->fetch_object($totalsResult)->total;
142
143 $tmp = $obj_ret;
144 $obj_ret = [];
145
146 $obj_ret['data'] = $tmp;
147 $obj_ret['pagination'] = [
148 'total' => (int) $total,
149 'page' => $page, //count starts from 0
150 'page_count' => ceil((int) $total / $limit),
151 'limit' => $limit
152 ];
153 }
154
155 return $obj_ret;
156 }
157
164 public function post($request_data = null)
165 {
166 if (!DolibarrApiAccess::$user->hasRight('webhook', 'webhook_target', 'write')) {
167 throw new RestException(403);
168 }
169 // Check mandatory fields
170 $this->_validate($request_data);
171
172 foreach ($request_data as $field => $value) {
173 $this->target->$field = $this->_checkValForAPI($field, $value, $this->target);
174 }
175
176 if (!array_key_exists('status', $request_data)) {
177 $this->target->status = 1;
178 }
179
180 if ($this->target->create(DolibarrApiAccess::$user) < 0) {
181 throw new RestException(500, 'Error creating target', array_merge(array($this->target->error), $this->target->errors));
182 }
183
184 return $this->target->id;
185 }
186
198 public function put($id, $request_data = null)
199 {
200 if (!DolibarrApiAccess::$user->hasRight('webhook', 'webhook_target', 'write')) {
201 throw new RestException(403);
202 }
203
204 $result = $this->target->fetch($id);
205 if (!$result) {
206 throw new RestException(404, 'Target not found');
207 }
208
209 foreach ($request_data as $field => $value) {
210 if ($field == 'id') {
211 continue;
212 }
213 $this->target->$field = $this->_checkValForAPI($field, $value, $this->target);
214 }
215
216 if ($this->target->update(DolibarrApiAccess::$user, 1) > 0) {
217 return $this->get($id);
218 } else {
219 throw new RestException(500, $this->target->error);
220 }
221 }
222
229 public function delete($id)
230 {
231 if (!DolibarrApiAccess::$user->hasRight('webhook', 'webhook_target', 'delete')) {
232 throw new RestException(403);
233 }
234
235 $result = $this->target->fetch($id);
236 if (!$result) {
237 throw new RestException(404, 'Target not found');
238 }
239
240 $res = $this->target->delete(DolibarrApiAccess::$user);
241 if ($res < 0) {
242 throw new RestException(500, "Can't delete target, error occurs");
243 }
244
245 return array(
246 'success' => array(
247 'code' => 200,
248 'message' => 'Target deleted'
249 )
250 );
251 }
252
260 public function listOfTriggers()
261 {
262 if (!DolibarrApiAccess::$user->hasRight('webhook', 'webhook_target', 'read')) {
263 throw new RestException(403);
264 }
265
266 $triggers = array();
267
268 $sql = "SELECT c.code, c.label FROM ".MAIN_DB_PREFIX."c_action_trigger as c ORDER BY c.rang ASC";
269 $resql = $this->db->query($sql);
270 if ($resql) {
271 $num = $this->db->num_rows($resql);
272 $i = 0;
273 while ($i < $num) {
274 $obj = $this->db->fetch_object($resql);
275 $triggers[$obj->code] = $obj->label;
276 $i++;
277 }
278 } else {
279 throw new RestException(500, "Can't get list of triggers");
280 }
281
282 return $triggers;
283 }
284
293 private function _validate($data)
294 {
295 $target = array();
296 foreach (self::$FIELDS as $field) {
297 if (!isset($data[$field])) {
298 throw new RestException(400, "$field field missing");
299 }
300 $target[$field] = $data[$field];
301 }
302 return $target;
303 }
304
305 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
312 protected function _cleanObjectDatas($object)
313 {
314 // phpcs:enable
315 $object = parent::_cleanObjectDatas($object);
316
317 unset($object->rowid);
318 unset($object->array_options);
319 unset($object->array_languages);
320 unset($object->contacts_ids);
321 unset($object->linkedObjectsIds);
322 unset($object->canvas);
323 unset($object->fk_project);
324 unset($object->contact_id);
325 unset($object->user);
326 unset($object->origin_type);
327 unset($object->origin_id);
328 unset($object->ref_ext);
329 unset($object->statut);
330 unset($object->country_id);
331 unset($object->country_code);
332 unset($object->state_id);
333 unset($object->region_id);
334 unset($object->barcode_type);
335 unset($object->barcode_type_coder);
336 unset($object->mode_reglement_id);
337 unset($object->cond_reglement_id);
338 unset($object->demand_reason_id);
339 unset($object->transport_mode_id);
340 unset($object->shipping_method_id);
341 unset($object->shipping_method);
342 unset($object->fk_multicurrency);
343 unset($object->multicurrency_code);
344 unset($object->multicurrency_tx);
345 unset($object->multicurrency_total_ht);
346 unset($object->multicurrency_total_tva);
347 unset($object->multicurrency_total_ttc);
348 unset($object->multicurrency_total_localtax1);
349 unset($object->multicurrency_total_localtax2);
350 unset($object->last_main_doc);
351 unset($object->fk_account);
352 unset($object->total_ht);
353 unset($object->total_tva);
354 unset($object->total_localtax1);
355 unset($object->total_localtax2);
356 unset($object->total_ttc);
357 unset($object->lines);
358 unset($object->actiontypecode);
359 unset($object->name);
360 unset($object->lastname);
361 unset($object->firstname);
362 unset($object->civility_id);
363 unset($object->date_validation);
364 unset($object->date_modification);
365 unset($object->date_cloture);
366 unset($object->user_author);
367 unset($object->user_creation);
368 unset($object->user_creation_id);
369 unset($object->user_valid);
370 unset($object->user_validation);
371 unset($object->user_validation_id);
372 unset($object->user_closing_id);
373 unset($object->user_modification);
374 unset($object->user_modification_id);
375 unset($object->specimen);
376 unset($object->extraparams);
377 unset($object->product);
378 unset($object->cond_reglement_supplier_id);
379 unset($object->deposit_percent);
380 unset($object->retained_warranty_fk_cond_reglement);
381 unset($object->warehouse_id);
382 unset($object->module);
383
384 return $object;
385 }
386
398 private function _fetch($rowid, $ref = '')
399 {
400 if (!DolibarrApiAccess::$user->hasRight('webhook', 'webhook_target', 'read')) {
401 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login.'. No read permission on target.');
402 }
403
404 if ($rowid === 0) {
405 $result = $this->target->initAsSpecimen();
406 } else {
407 $result = $this->target->fetch($rowid, $ref);
408 }
409
410 if (!$result) {
411 throw new RestException(404, 'Target not found');
412 }
413
414 return $this->_cleanObjectDatas($this->target);
415 }
416}
$id
Definition account.php:39
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
Class for API REST v1.
Definition api.class.php:30
_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:82
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