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