dolibarr 24.0.0-beta
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-2025 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 global $hookmanager;
118
119 $obj_ret = array();
120 $tmpobject = new MyObject($this->db);
121
122 if (!DolibarrApiAccess::$user->hasRight('mymodule', 'myobject', 'read')) {
123 throw new RestException(403);
124 }
125
126 $socid = DolibarrApiAccess::$user->socid ?: 0;
127
128 $restrictonsocid = 0; // Set to 1 if there is a field socid in table of object
129
130 // If the internal user must only see his customers, force searching by him
131 $search_sale = 0;
132 if ($restrictonsocid && !DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socid) {
133 $search_sale = DolibarrApiAccess::$user->id;
134 }
135 if (!isModEnabled('societe')) {
136 $search_sale = 0; // If module thirdparty not enabled, sale representative is something that does not exists
137 }
138
139 $sql = "SELECT t.rowid";
140 $sql .= " FROM ".$this->db->prefix().$tmpobject->table_element." AS t";
141 if (!empty($tmpobject->isextrafieldmanaged) && (int) $tmpobject->isextrafieldmanaged == 1) {
142 $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
143 }
144 if (!empty($tmpobject->ismultientitymanaged) && (int) $tmpobject->ismultientitymanaged == 1) {
145 $sql .= " WHERE t.entity IN (".getEntity($tmpobject->element).")";
146 } elseif (preg_match('/^\w+@\w+$/', (string) $tmpobject->ismultientitymanaged)) {
147 $tmparray = explode('@', (string) $tmpobject->ismultientitymanaged);
148 $sql .= " LEFT JOIN ".$this->db->prefix().$tmparray[1]." as pt ON t.".$tmparray[0]." = pt.rowid";
149 $sql .= " WHERE pt.entity IN (".getEntity($tmpobject->element).")";
150 } else {
151 $sql .= " WHERE 1 = 1";
152 }
153 if ($restrictonsocid && $socid) {
154 $sql .= " AND t.fk_soc = ".((int) $socid);
155 }
156 // Search on sale representative
157 if ($search_sale && $search_sale != '-1') {
158 if ($search_sale == -2) {
159 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".$this->db->prefix()."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
160 } elseif ($search_sale > 0) {
161 $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).")";
162 }
163 }
164 // Add where from hooks and sqlfilters
165 $parameters = array('sqlfilters' => $sqlfilters, 'apiroute' => 'myobject', 'apimethod' => __METHOD__);
166 $action = 'list';
167 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $tmpobject, $action); // Note that $action and $object may have been modified by hook
168 if ($reshook > 0) {
169 $sql = $hookmanager->resPrint;
170 } elseif ($reshook == 0) {
171 $sql .= $hookmanager->resPrint;
172 }
173
174 if ($sqlfilters) {
175 $errormessage = '';
176 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
177 if ($errormessage) {
178 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
179 }
180 }
181
182 $sql .= $this->db->order($sortfield, $sortorder);
183 if ($limit) {
184 if ($page < 0) {
185 $page = 0;
186 }
187 $offset = $limit * $page;
188
189 $sql .= $this->db->plimit($limit + 1, $offset);
190 }
191
192 $result = $this->db->query($sql);
193 $i = 0;
194 if ($result) {
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 $tmp_object = new MyObject($this->db);
200 if ($tmp_object->fetch($obj->rowid)) {
201 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($tmp_object), $properties);
202 }
203 $i++;
204 }
205 } else {
206 throw new RestException(503, 'Error when retrieving myobject list: '.$this->db->lasterror());
207 }
208
209 return $obj_ret;
210 }
211
225 public function post($request_data = null)
226 {
227 if (!DolibarrApiAccess::$user->hasRight('mymodule', 'myobject', 'write')) {
228 throw new RestException(403);
229 }
230
231 // Check mandatory fields
232 $result = $this->_validateMyObject($request_data);
233
234 foreach ($request_data as $field => $value) {
235 if ($field === 'caller') {
236 // 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
237 $this->myobject->context['caller'] = sanitizeVal((string) $request_data['caller'], 'aZ09');
238 continue;
239 }
240
241 if ($field == 'array_options' && is_array($value)) {
242 $this->myobject->fetch_optionals(); // To force the load of the extrafields definition by fetch_name_optionals_label()
243
244 foreach ($value as $index => $val) {
245 $this->myobject->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->myobject);
246 }
247 continue;
248 }
249
250 $this->myobject->$field = $this->_checkValForAPI((string) $field, $value, $this->myobject);
251 }
252
253 // Clean data
254 // $this->myobject->abc = sanitizeVal($this->myobject->abc, 'alphanohtml');
255
256 if ($this->myobject->create(DolibarrApiAccess::$user) < 0) {
257 throw new RestException(500, "Error creating MyObject", array_merge(array($this->myobject->error), $this->myobject->errors));
258 }
259 return $this->myobject->id;
260 }
261
279 public function put($id, $request_data = null)
280 {
281 if (!DolibarrApiAccess::$user->hasRight('mymodule', 'myobject', 'write')) {
282 throw new RestException(403);
283 }
284 if (!DolibarrApi::_checkAccessToResource('myobject', $id, 'mymodule_myobject')) {
285 throw new RestException(403, 'Access to instance id='.$this->myobject->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
286 }
287
288 $result = $this->myobject->fetch($id);
289 if (!$result) {
290 throw new RestException(404, 'MyObject not found');
291 }
292
293 foreach ($request_data as $field => $value) {
294 if ($field == 'id') {
295 continue;
296 }
297 if ($field === 'caller') {
298 // 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
299 $this->myobject->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
300 continue;
301 }
302
303 if ($field == 'array_options' && is_array($value)) {
304 foreach ($value as $index => $val) {
305 $this->myobject->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->myobject);
306 }
307 continue;
308 }
309
310 $this->myobject->$field = $this->_checkValForAPI((string) $field, $value, $this->myobject);
311 }
312
313 // Clean data
314 // $this->myobject->abc = sanitizeVal($this->myobject->abc, 'alphanohtml');
315
316 if ($this->myobject->update(DolibarrApiAccess::$user, 0) > 0) {
317 return $this->get($id);
318 } else {
319 throw new RestException(500, $this->myobject->error);
320 }
321 }
322
338 public function delete($id)
339 {
340 if (!DolibarrApiAccess::$user->hasRight('mymodule', 'myobject', 'delete')) {
341 throw new RestException(403);
342 }
343 if (!DolibarrApi::_checkAccessToResource('myobject', $id, 'mymodule_myobject')) {
344 throw new RestException(403, 'Access to instance id='.$this->myobject->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
345 }
346
347 $result = $this->myobject->fetch($id);
348 if (!$result) {
349 throw new RestException(404, 'MyObject not found');
350 }
351
352 if ($this->myobject->delete(DolibarrApiAccess::$user) == 0) {
353 throw new RestException(409, 'Error when deleting MyObject : '.$this->myobject->error);
354 } elseif ($this->myobject->delete(DolibarrApiAccess::$user) < 0) {
355 throw new RestException(500, 'Error when deleting MyObject : '.$this->myobject->error);
356 }
357
358 return array(
359 'success' => array(
360 'code' => 200,
361 'message' => 'MyObject deleted'
362 )
363 );
364 }
365
366
379 private function _validateMyObject($data)
380 {
381 if (!is_array($data)) {
382 $data = array();
383 }
384 $myobject = array();
385 foreach ($this->myobject->fields as $field => $propfield) {
386 if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) {
387 continue; // Not a mandatory field
388 }
389 if (!isset($data[$field])) {
390 throw new RestException(400, "$field field missing");
391 }
392 $myobject[$field] = $data[$field];
393 }
394 return $myobject;
395 }
396
397 /* END MODULEBUILDER API MYOBJECT */
398
399
400
401 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
412 protected function _cleanObjectDatas($object)
413 {
414 // phpcs:enable
415 $object = parent::_cleanObjectDatas($object);
416
417 unset($object->rowid);
418 unset($object->canvas);
419 //BEGIN MODULEBUILDER LINES
420 // If object has lines, remove $db property
421 if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
422 $nboflines = count($object->lines);
423 for ($i = 0; $i < $nboflines; $i++) {
424 $this->_cleanObjectDatas($object->lines[$i]);
425
426 unset($object->lines[$i]->lines);
427 unset($object->lines[$i]->note);
428 }
429 }
430 //END MODULEBUILDER LINES
431 return $object;
432 }
433}
$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 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.
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.
_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.
__construct()
Constructor.
post($request_data=null)
Create myobject object.
put($id, $request_data=null)
Update myobject.
Class for MyObject.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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.
isModEnabled($module)
Is Dolibarr module enabled.