dolibarr 22.0.5
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
50 public function __construct()
51 {
52 global $db;
53 $this->db = $db;
54 $this->myobject = new MyObject($this->db);
55 }
56
57
58 /* BEGIN MODULEBUILDER API MYOBJECT */
59
77 public function get($id)
78 {
79 if (!DolibarrApiAccess::$user->hasRight('mymodule', 'myobject', 'read')) {
80 throw new RestException(403);
81 }
82 if (!DolibarrApi::_checkAccessToResource('myobject', $id, 'mymodule_myobject')) {
83 throw new RestException(403, 'Access to instance id='.$id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
84 }
85
86 $result = $this->myobject->fetch($id);
87 if (!$result) {
88 throw new RestException(404, 'MyObject not found');
89 }
90
91 return $this->_cleanObjectDatas($this->myobject);
92 }
93
94
115 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '')
116 {
117 $obj_ret = array();
118 $tmpobject = new MyObject($this->db);
119
120 if (!DolibarrApiAccess::$user->hasRight('mymodule', 'myobject', 'read')) {
121 throw new RestException(403);
122 }
123
124 $socid = DolibarrApiAccess::$user->socid ?: 0;
125
126 $restrictonsocid = 0; // Set to 1 if there is a field socid in table of object
127
128 // If the internal user must only see his customers, force searching by him
129 $search_sale = 0;
130 if ($restrictonsocid && !DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socid) {
131 $search_sale = DolibarrApiAccess::$user->id;
132 }
133 if (!isModEnabled('societe')) {
134 $search_sale = 0; // If module thirdparty not enabled, sale representative is something that does not exists
135 }
136
137 $sql = "SELECT t.rowid";
138 $sql .= " FROM ".$this->db->prefix().$tmpobject->table_element." AS t";
139 $sql .= " LEFT JOIN ".$this->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
140 $sql .= " WHERE 1 = 1";
141 if ($tmpobject->ismultientitymanaged) {
142 $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')';
143 }
144 if ($restrictonsocid && $socid) {
145 $sql .= " AND t.fk_soc = ".((int) $socid);
146 }
147 // Search on sale representative
148 if ($search_sale && $search_sale != '-1') {
149 if ($search_sale == -2) {
150 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".$this->db->prefix()."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
151 } elseif ($search_sale > 0) {
152 $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".$this->db->prefix()."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc AND sc.fk_user = ".((int) $search_sale).")";
153 }
154 }
155 if ($sqlfilters) {
156 $errormessage = '';
157 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
158 if ($errormessage) {
159 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
160 }
161 }
162
163 $sql .= $this->db->order($sortfield, $sortorder);
164 if ($limit) {
165 if ($page < 0) {
166 $page = 0;
167 }
168 $offset = $limit * $page;
169
170 $sql .= $this->db->plimit($limit + 1, $offset);
171 }
172
173 $result = $this->db->query($sql);
174 $i = 0;
175 if ($result) {
176 $num = $this->db->num_rows($result);
177 while ($i < $num) {
178 $obj = $this->db->fetch_object($result);
179 $tmp_object = new MyObject($this->db);
180 if ($tmp_object->fetch($obj->rowid)) {
181 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($tmp_object), $properties);
182 }
183 $i++;
184 }
185 } else {
186 throw new RestException(503, 'Error when retrieving myobject list: '.$this->db->lasterror());
187 }
188
189 return $obj_ret;
190 }
191
205 public function post($request_data = null)
206 {
207 if (!DolibarrApiAccess::$user->hasRight('mymodule', 'myobject', 'write')) {
208 throw new RestException(403);
209 }
210
211 // Check mandatory fields
212 $result = $this->_validateMyObject($request_data);
213
214 foreach ($request_data as $field => $value) {
215 if ($field === 'caller') {
216 // 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
217 $this->myobject->context['caller'] = sanitizeVal((string) $request_data['caller'], 'aZ09');
218 continue;
219 }
220
221 if ($field == 'array_options' && is_array($value)) {
222 foreach ($value as $index => $val) {
223 $this->myobject->array_options[$index] = $this->_checkValForAPI('extrafields', $val, $this->myobject);
224 }
225 continue;
226 }
227
228 $this->myobject->$field = $this->_checkValForAPI((string) $field, $value, $this->myobject);
229 }
230
231 // Clean data
232 // $this->myobject->abc = sanitizeVal($this->myobject->abc, 'alphanohtml');
233
234 if ($this->myobject->create(DolibarrApiAccess::$user) < 0) {
235 throw new RestException(500, "Error creating MyObject", array_merge(array($this->myobject->error), $this->myobject->errors));
236 }
237 return $this->myobject->id;
238 }
239
257 public function put($id, $request_data = null)
258 {
259 if (!DolibarrApiAccess::$user->hasRight('mymodule', 'myobject', 'write')) {
260 throw new RestException(403);
261 }
262 if (!DolibarrApi::_checkAccessToResource('myobject', $id, 'mymodule_myobject')) {
263 throw new RestException(403, 'Access to instance id='.$this->myobject->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
264 }
265
266 $result = $this->myobject->fetch($id);
267 if (!$result) {
268 throw new RestException(404, 'MyObject not found');
269 }
270
271 foreach ($request_data as $field => $value) {
272 if ($field == 'id') {
273 continue;
274 }
275 if ($field === 'caller') {
276 // 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
277 $this->myobject->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
278 continue;
279 }
280
281 if ($field == 'array_options' && is_array($value)) {
282 foreach ($value as $index => $val) {
283 $this->myobject->array_options[$index] = $this->_checkValForAPI('extrafields', $val, $this->myobject);
284 }
285 continue;
286 }
287
288 if ($field == 'array_options' && is_array($value)) {
289 foreach ($value as $index => $val) {
290 $this->myobject->array_options[$index] = $this->_checkValForAPI($field, $val, $this->myobject);
291 }
292 continue;
293 }
294
295 $this->myobject->$field = $this->_checkValForAPI($field, $value, $this->myobject);
296 }
297
298 // Clean data
299 // $this->myobject->abc = sanitizeVal($this->myobject->abc, 'alphanohtml');
300
301 if ($this->myobject->update(DolibarrApiAccess::$user, 0) > 0) {
302 return $this->get($id);
303 } else {
304 throw new RestException(500, $this->myobject->error);
305 }
306 }
307
323 public function delete($id)
324 {
325 if (!DolibarrApiAccess::$user->hasRight('mymodule', 'myobject', 'delete')) {
326 throw new RestException(403);
327 }
328 if (!DolibarrApi::_checkAccessToResource('myobject', $id, 'mymodule_myobject')) {
329 throw new RestException(403, 'Access to instance id='.$this->myobject->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
330 }
331
332 $result = $this->myobject->fetch($id);
333 if (!$result) {
334 throw new RestException(404, 'MyObject not found');
335 }
336
337 if ($this->myobject->delete(DolibarrApiAccess::$user) == 0) {
338 throw new RestException(409, 'Error when deleting MyObject : '.$this->myobject->error);
339 } elseif ($this->myobject->delete(DolibarrApiAccess::$user) < 0) {
340 throw new RestException(500, 'Error when deleting MyObject : '.$this->myobject->error);
341 }
342
343 return array(
344 'success' => array(
345 'code' => 200,
346 'message' => 'MyObject deleted'
347 )
348 );
349 }
350
351
364 private function _validateMyObject($data)
365 {
366 if (!is_array($data)) {
367 $data = array();
368 }
369 $myobject = array();
370 foreach ($this->myobject->fields as $field => $propfield) {
371 if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) {
372 continue; // Not a mandatory field
373 }
374 if (!isset($data[$field])) {
375 throw new RestException(400, "$field field missing");
376 }
377 $myobject[$field] = $data[$field];
378 }
379 return $myobject;
380 }
381
382 /* END MODULEBUILDER API MYOBJECT */
383
384
385
386 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
397 protected function _cleanObjectDatas($object)
398 {
399 // phpcs:enable
400 $object = parent::_cleanObjectDatas($object);
401
402 unset($object->rowid);
403 unset($object->canvas);
404
405 // If object has lines, remove $db property
406 if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
407 $nboflines = count($object->lines);
408 for ($i = 0; $i < $nboflines; $i++) {
409 $this->_cleanObjectDatas($object->lines[$i]);
410
411 unset($object->lines[$i]->lines);
412 unset($object->lines[$i]->note);
413 }
414 }
415
416 return $object;
417 }
418}
$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.
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
_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.