dolibarr 21.0.0-alpha
api_mymodule.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) ---Replace with your own copyright and developer email---
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20use Luracast\Restler\RestException;
21
22dol_include_once('/mymodule/class/myobject.class.php');
23
24
25
39{
43 public $myobject;
44
51 public function __construct()
52 {
53 global $db;
54 $this->db = $db;
55 $this->myobject = new MyObject($this->db);
56 }
57
58
59 /* BEGIN MODULEBUILDER API MYOBJECT */
60
78 public function get($id)
79 {
80 if (!DolibarrApiAccess::$user->hasRight('mymodule', 'myobject', 'read')) {
81 throw new RestException(403);
82 }
83 if (!DolibarrApi::_checkAccessToResource('myobject', $id, 'mymodule_myobject')) {
84 throw new RestException(403, 'Access to instance id='.$id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
85 }
86
87 $result = $this->myobject->fetch($id);
88 if (!$result) {
89 throw new RestException(404, 'MyObject not found');
90 }
91
92 return $this->_cleanObjectDatas($this->myobject);
93 }
94
95
116 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '')
117 {
118 $obj_ret = array();
119 $tmpobject = new MyObject($this->db);
120
121 if (!DolibarrApiAccess::$user->hasRight('mymodule', 'myobject', 'read')) {
122 throw new RestException(403);
123 }
124
125 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : 0;
126
127 $restrictonsocid = 0; // Set to 1 if there is a field socid in table of object
128
129 // If the internal user must only see his customers, force searching by him
130 $search_sale = 0;
131 if ($restrictonsocid && !DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socid) {
132 $search_sale = DolibarrApiAccess::$user->id;
133 }
134 if (!isModEnabled('societe')) {
135 $search_sale = 0; // If module thirdparty not enabled, sale representative is something that does not exists
136 }
137
138 $sql = "SELECT t.rowid";
139 $sql .= " FROM ".MAIN_DB_PREFIX.$tmpobject->table_element." AS t";
140 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$tmpobject->table_element."_extrafields AS ef ON (ef.fk_object = t.rowid)"; // Modification VMR Global Solutions to include extrafields as search parameters in the API GET call, so we will be able to filter on extrafields
141 $sql .= " WHERE 1 = 1";
142 if ($tmpobject->ismultientitymanaged) {
143 $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')';
144 }
145 if ($restrictonsocid && $socid) {
146 $sql .= " AND t.fk_soc = ".((int) $socid);
147 }
148 // Search on sale representative
149 if ($search_sale && $search_sale != '-1') {
150 if ($search_sale == -2) {
151 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
152 } elseif ($search_sale > 0) {
153 $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).")";
154 }
155 }
156 if ($sqlfilters) {
157 $errormessage = '';
158 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
159 if ($errormessage) {
160 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
161 }
162 }
163
164 $sql .= $this->db->order($sortfield, $sortorder);
165 if ($limit) {
166 if ($page < 0) {
167 $page = 0;
168 }
169 $offset = $limit * $page;
170
171 $sql .= $this->db->plimit($limit + 1, $offset);
172 }
173
174 $result = $this->db->query($sql);
175 $i = 0;
176 if ($result) {
177 $num = $this->db->num_rows($result);
178 while ($i < $num) {
179 $obj = $this->db->fetch_object($result);
180 $tmp_object = new MyObject($this->db);
181 if ($tmp_object->fetch($obj->rowid)) {
182 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($tmp_object), $properties);
183 }
184 $i++;
185 }
186 } else {
187 throw new RestException(503, 'Error when retrieving myobject list: '.$this->db->lasterror());
188 }
189
190 return $obj_ret;
191 }
192
206 public function post($request_data = null)
207 {
208 if (!DolibarrApiAccess::$user->hasRight('mymodule', 'myobject', 'write')) {
209 throw new RestException(403);
210 }
211
212 // Check mandatory fields
213 $result = $this->_validateMyObject($request_data);
214
215 foreach ($request_data as $field => $value) {
216 if ($field === 'caller') {
217 // 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 @phan-suppress-next-line PhanTypeInvalidDimOffset
218 $this->myobject->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
219 continue;
220 }
221
222 if ($field == 'array_options' && is_array($value)) {
223 foreach ($value as $index => $val) {
224 $this->myobject->array_options[$index] = $this->_checkValForAPI('extrafields', $val, $this->myobject);
225 }
226 continue;
227 }
228
229 $this->myobject->$field = $this->_checkValForAPI((string) $field, $value, $this->myobject);
230 }
231
232 // Clean data
233 // $this->myobject->abc = sanitizeVal($this->myobject->abc, 'alphanohtml');
234
235 if ($this->myobject->create(DolibarrApiAccess::$user) < 0) {
236 throw new RestException(500, "Error creating MyObject", array_merge(array($this->myobject->error), $this->myobject->errors));
237 }
238 return $this->myobject->id;
239 }
240
260 public function put($id, $request_data = null)
261 {
262 if (!DolibarrApiAccess::$user->hasRight('mymodule', 'myobject', 'write')) {
263 throw new RestException(403);
264 }
265 if (!DolibarrApi::_checkAccessToResource('myobject', $id, 'mymodule_myobject')) {
266 throw new RestException(403, 'Access to instance id='.$this->myobject->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
267 }
268
269 $result = $this->myobject->fetch($id);
270 if (!$result) {
271 throw new RestException(404, 'MyObject not found');
272 }
273
274 foreach ($request_data as $field => $value) {
275 if ($field == 'id') {
276 continue;
277 }
278 if ($field === 'caller') {
279 // 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
280 $this->myobject->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
281 continue;
282 }
283
284 if ($field == 'array_options' && is_array($value)) {
285 foreach ($value as $index => $val) {
286 $this->myobject->array_options[$index] = $this->_checkValForAPI('extrafields', $val, $this->myobject);
287 }
288 continue;
289 }
290
291 $this->myobject->$field = $this->_checkValForAPI($field, $value, $this->myobject);
292 }
293
294 // Clean data
295 // $this->myobject->abc = sanitizeVal($this->myobject->abc, 'alphanohtml');
296
297 if ($this->myobject->update(DolibarrApiAccess::$user, false) > 0) {
298 return $this->get($id);
299 } else {
300 throw new RestException(500, $this->myobject->error);
301 }
302 }
303
319 public function delete($id)
320 {
321 if (!DolibarrApiAccess::$user->hasRight('mymodule', 'myobject', 'delete')) {
322 throw new RestException(403);
323 }
324 if (!DolibarrApi::_checkAccessToResource('myobject', $id, 'mymodule_myobject')) {
325 throw new RestException(403, 'Access to instance id='.$this->myobject->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
326 }
327
328 $result = $this->myobject->fetch($id);
329 if (!$result) {
330 throw new RestException(404, 'MyObject not found');
331 }
332
333 if ($this->myobject->delete(DolibarrApiAccess::$user) == 0) {
334 throw new RestException(409, 'Error when deleting MyObject : '.$this->myobject->error);
335 } elseif ($this->myobject->delete(DolibarrApiAccess::$user) < 0) {
336 throw new RestException(500, 'Error when deleting MyObject : '.$this->myobject->error);
337 }
338
339 return array(
340 'success' => array(
341 'code' => 200,
342 'message' => 'MyObject deleted'
343 )
344 );
345 }
346
347
360 private function _validateMyObject($data)
361 {
362 $myobject = array();
363 foreach ($this->myobject->fields as $field => $propfield) {
364 if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) {
365 continue; // Not a mandatory field
366 }
367 if (!isset($data[$field])) {
368 throw new RestException(400, "$field field missing");
369 }
370 $myobject[$field] = $data[$field];
371 }
372 return $myobject;
373 }
374
375 /* END MODULEBUILDER API MYOBJECT */
376
377
378
379 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
390 protected function _cleanObjectDatas($object)
391 {
392 // phpcs:enable
393 $object = parent::_cleanObjectDatas($object);
394
395 unset($object->rowid);
396 unset($object->canvas);
397
398 // If object has lines, remove $db property
399 if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
400 $nboflines = count($object->lines);
401 for ($i = 0; $i < $nboflines; $i++) {
402 $this->_cleanObjectDatas($object->lines[$i]);
403
404 unset($object->lines[$i]->lines);
405 unset($object->lines[$i]->note);
406 }
407 }
408
409 return $object;
410 }
411}
$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.
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:82
_validateMyObject($data)
Validate fields before creating or updating object.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $sqlfilters='', $properties='')
List myobjects.
_cleanObjectDatas($object)
Clean sensitive object data fields @phpstan-template T of Object.
__construct()
Constructor.
post($request_data=null)
Create myobject object.
put($id, $request_data=null)
Update myobject.
Class for MyObject.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.