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) ---Put here your own copyright and developer email---
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
19use Luracast\Restler\RestException;
20
21dol_include_once('/mymodule/class/myobject.class.php');
22
23
24
38{
42 public $myobject;
43
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
73 public function get($id)
74 {
75 if (!DolibarrApiAccess::$user->hasRight('mymodule', 'myobject', 'read')) {
76 throw new RestException(403);
77 }
78 if (!DolibarrApi::_checkAccessToResource('myobject', $id, 'mymodule_myobject')) {
79 throw new RestException(403, 'Access to instance id='.$id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
80 }
81
82 $result = $this->myobject->fetch($id);
83 if (!$result) {
84 throw new RestException(404, 'MyObject not found');
85 }
86
87 return $this->_cleanObjectDatas($this->myobject);
88 }
89
90
109 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '')
110 {
111 $obj_ret = array();
112 $tmpobject = new MyObject($this->db);
113
114 if (!DolibarrApiAccess::$user->hasRight('mymodule', 'myobject', 'read')) {
115 throw new RestException(403);
116 }
117
118 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : 0;
119
120 $restrictonsocid = 0; // Set to 1 if there is a field socid in table of object
121
122 // If the internal user must only see his customers, force searching by him
123 $search_sale = 0;
124 if ($restrictonsocid && !DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socid) {
125 $search_sale = DolibarrApiAccess::$user->id;
126 }
127 if (!isModEnabled('societe')) {
128 $search_sale = 0; // If module thirdparty not enabled, sale representative is something that does not exists
129 }
130
131 $sql = "SELECT t.rowid";
132 $sql .= " FROM ".MAIN_DB_PREFIX.$tmpobject->table_element." AS t";
133 $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
134 $sql .= " WHERE 1 = 1";
135 if ($tmpobject->ismultientitymanaged) {
136 $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')';
137 }
138 if ($restrictonsocid && $socid) {
139 $sql .= " AND t.fk_soc = ".((int) $socid);
140 }
141 // Search on sale representative
142 if ($search_sale && $search_sale != '-1') {
143 if ($search_sale == -2) {
144 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
145 } elseif ($search_sale > 0) {
146 $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).")";
147 }
148 }
149 if ($sqlfilters) {
150 $errormessage = '';
151 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
152 if ($errormessage) {
153 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
154 }
155 }
156
157 $sql .= $this->db->order($sortfield, $sortorder);
158 if ($limit) {
159 if ($page < 0) {
160 $page = 0;
161 }
162 $offset = $limit * $page;
163
164 $sql .= $this->db->plimit($limit + 1, $offset);
165 }
166
167 $result = $this->db->query($sql);
168 $i = 0;
169 if ($result) {
170 $num = $this->db->num_rows($result);
171 while ($i < $num) {
172 $obj = $this->db->fetch_object($result);
173 $tmp_object = new MyObject($this->db);
174 if ($tmp_object->fetch($obj->rowid)) {
175 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($tmp_object), $properties);
176 }
177 $i++;
178 }
179 } else {
180 throw new RestException(503, 'Error when retrieving myobject list: '.$this->db->lasterror());
181 }
182
183 return $obj_ret;
184 }
185
197 public function post($request_data = null)
198 {
199 if (!DolibarrApiAccess::$user->hasRight('mymodule', 'myobject', 'write')) {
200 throw new RestException(403);
201 }
202
203 // Check mandatory fields
204 $result = $this->_validateMyObject($request_data);
205
206 foreach ($request_data as $field => $value) {
207 if ($field === 'caller') {
208 // 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
209 $this->myobject->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
210 continue;
211 }
212
213 if ($field == 'array_options' && is_array($value)) {
214 foreach ($value as $index => $val) {
215 $this->myobject->array_options[$index] = $this->_checkValForAPI('extrafields', $val, $this->myobject);
216 }
217 continue;
218 }
219
220 $this->myobject->$field = $this->_checkValForAPI($field, $value, $this->myobject);
221 }
222
223 // Clean data
224 // $this->myobject->abc = sanitizeVal($this->myobject->abc, 'alphanohtml');
225
226 if ($this->myobject->create(DolibarrApiAccess::$user)<0) {
227 throw new RestException(500, "Error creating MyObject", array_merge(array($this->myobject->error), $this->myobject->errors));
228 }
229 return $this->myobject->id;
230 }
231
245 public function put($id, $request_data = null)
246 {
247 if (!DolibarrApiAccess::$user->hasRight('mymodule', 'myobject', 'write')) {
248 throw new RestException(403);
249 }
250 if (!DolibarrApi::_checkAccessToResource('myobject', $id, 'mymodule_myobject')) {
251 throw new RestException(403, 'Access to instance id='.$this->myobject->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
252 }
253
254 $result = $this->myobject->fetch($id);
255 if (!$result) {
256 throw new RestException(404, 'MyObject not found');
257 }
258
259 foreach ($request_data as $field => $value) {
260 if ($field == 'id') {
261 continue;
262 }
263 if ($field === 'caller') {
264 // 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
265 $this->myobject->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
266 continue;
267 }
268
269 if ($field == 'array_options' && is_array($value)) {
270 foreach ($value as $index => $val) {
271 $this->myobject->array_options[$index] = $this->_checkValForAPI('extrafields', $val, $this->myobject);
272 }
273 continue;
274 }
275
276 $this->myobject->$field = $this->_checkValForAPI($field, $value, $this->myobject);
277 }
278
279 // Clean data
280 // $this->myobject->abc = sanitizeVal($this->myobject->abc, 'alphanohtml');
281
282 if ($this->myobject->update(DolibarrApiAccess::$user, false) > 0) {
283 return $this->get($id);
284 } else {
285 throw new RestException(500, $this->myobject->error);
286 }
287 }
288
302 public function delete($id)
303 {
304 if (!DolibarrApiAccess::$user->hasRight('mymodule', 'myobject', 'delete')) {
305 throw new RestException(403);
306 }
307 if (!DolibarrApi::_checkAccessToResource('myobject', $id, 'mymodule_myobject')) {
308 throw new RestException(403, 'Access to instance id='.$this->myobject->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
309 }
310
311 $result = $this->myobject->fetch($id);
312 if (!$result) {
313 throw new RestException(404, 'MyObject not found');
314 }
315
316 if ($this->myobject->delete(DolibarrApiAccess::$user) == 0) {
317 throw new RestException(409, 'Error when deleting MyObject : '.$this->myobject->error);
318 } elseif ($this->myobject->delete(DolibarrApiAccess::$user) < 0) {
319 throw new RestException(500, 'Error when deleting MyObject : '.$this->myobject->error);
320 }
321
322 return array(
323 'success' => array(
324 'code' => 200,
325 'message' => 'MyObject deleted'
326 )
327 );
328 }
329
330
339 private function _validateMyObject($data)
340 {
341 $myobject = array();
342 foreach ($this->myobject->fields as $field => $propfield) {
343 if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) {
344 continue; // Not a mandatory field
345 }
346 if (!isset($data[$field])) {
347 throw new RestException(400, "$field field missing");
348 }
349 $myobject[$field] = $data[$field];
350 }
351 return $myobject;
352 }
353
354 /* END MODULEBUILDER API MYOBJECT */
355
356
357
358 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
365 protected function _cleanObjectDatas($object)
366 {
367 // phpcs:enable
368 $object = parent::_cleanObjectDatas($object);
369
370 unset($object->rowid);
371 unset($object->canvas);
372
373 // If object has lines, remove $db property
374 if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
375 $nboflines = count($object->lines);
376 for ($i = 0; $i < $nboflines; $i++) {
377 $this->_cleanObjectDatas($object->lines[$i]);
378
379 unset($object->lines[$i]->lines);
380 unset($object->lines[$i]->note);
381 }
382 }
383
384 return $object;
385 }
386}
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 create or update object.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $sqlfilters='', $properties='')
List myobjects.
_cleanObjectDatas($object)
Clean sensible object datas.
__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.