dolibarr 19.0.4
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 /*begin methods CRUD*/
58
72 public function get($id)
73 {
74 if (!DolibarrApiAccess::$user->rights->mymodule->myobject->read) {
75 throw new RestException(401);
76 }
77
78 $result = $this->myobject->fetch($id);
79 if (!$result) {
80 throw new RestException(404, 'MyObject not found');
81 }
82
83 if (!DolibarrApi::_checkAccessToResource('myobject', $this->myobject->id, 'mymodule_myobject')) {
84 throw new RestException(401, 'Access to instance id='.$this->myobject->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
85 }
86
87 return $this->_cleanObjectDatas($this->myobject);
88 }
89
90
108 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '')
109 {
110 global $db, $conf;
111
112 $obj_ret = array();
113 $tmpobject = new MyObject($this->db);
114
115 if (!DolibarrApiAccess::$user->rights->mymodule->myobject->read) {
116 throw new RestException(401);
117 }
118
119 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
120
121 $restrictonsocid = 0; // Set to 1 if there is a field socid in table of object
122
123 // If the internal user must only see his customers, force searching by him
124 $search_sale = 0;
125 if ($restrictonsocid && !DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) {
126 $search_sale = DolibarrApiAccess::$user->id;
127 }
128
129 $sql = "SELECT t.rowid";
130 if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
131 $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
132 }
133 $sql .= " FROM ".MAIN_DB_PREFIX.$tmpobject->table_element." AS t 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
135 if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
136 $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
137 }
138 $sql .= " WHERE 1 = 1";
139
140 // Example of use $mode
141 //if ($mode == 1) $sql.= " AND s.client IN (1, 3)";
142 //if ($mode == 2) $sql.= " AND s.client IN (2, 3)";
143
144 if ($tmpobject->ismultientitymanaged) {
145 $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')';
146 }
147 if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
148 $sql .= " AND t.fk_soc = sc.fk_soc";
149 }
150 if ($restrictonsocid && $socid) {
151 $sql .= " AND t.fk_soc = ".((int) $socid);
152 }
153 if ($restrictonsocid && $search_sale > 0) {
154 $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
155 }
156 // Insert sale filter
157 if ($restrictonsocid && $search_sale > 0) {
158 $sql .= " AND sc.fk_user = ".((int) $search_sale);
159 }
160 if ($sqlfilters) {
161 $errormessage = '';
162 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
163 if ($errormessage) {
164 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
165 }
166 }
167
168 $sql .= $this->db->order($sortfield, $sortorder);
169 if ($limit) {
170 if ($page < 0) {
171 $page = 0;
172 }
173 $offset = $limit * $page;
174
175 $sql .= $this->db->plimit($limit + 1, $offset);
176 }
177
178 $result = $this->db->query($sql);
179 $i = 0;
180 if ($result) {
181 $num = $this->db->num_rows($result);
182 while ($i < $num) {
183 $obj = $this->db->fetch_object($result);
184 $tmp_object = new MyObject($this->db);
185 if ($tmp_object->fetch($obj->rowid)) {
186 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($tmp_object), $properties);
187 }
188 $i++;
189 }
190 } else {
191 throw new RestException(503, 'Error when retrieving myobject list: '.$this->db->lasterror());
192 }
193
194 return $obj_ret;
195 }
196
207 public function post($request_data = null)
208 {
209 if (!DolibarrApiAccess::$user->rights->mymodule->myobject->write) {
210 throw new RestException(401);
211 }
212
213 // Check mandatory fields
214 $result = $this->_validate($request_data);
215
216 foreach ($request_data as $field => $value) {
217 if ($field === 'caller') {
218 // 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 whith the caller
219 $this->myobject->context['caller'] = $request_data['caller'];
220 continue;
221 }
222
223 $this->myobject->$field = $this->_checkValForAPI($field, $value, $this->myobject);
224 }
225
226 // Clean data
227 // $this->myobject->abc = sanitizeVal($this->myobject->abc, 'alphanohtml');
228
229 if ($this->myobject->create(DolibarrApiAccess::$user)<0) {
230 throw new RestException(500, "Error creating MyObject", array_merge(array($this->myobject->error), $this->myobject->errors));
231 }
232 return $this->myobject->id;
233 }
234
246 public function put($id, $request_data = null)
247 {
248 if (!DolibarrApiAccess::$user->rights->mymodule->myobject->write) {
249 throw new RestException(401);
250 }
251
252 $result = $this->myobject->fetch($id);
253 if (!$result) {
254 throw new RestException(404, 'MyObject not found');
255 }
256
257 if (!DolibarrApi::_checkAccessToResource('myobject', $this->myobject->id, 'mymodule_myobject')) {
258 throw new RestException(401, 'Access to instance id='.$this->myobject->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
259 }
260
261 foreach ($request_data as $field => $value) {
262 if ($field == 'id') {
263 continue;
264 }
265 if ($field === 'caller') {
266 // 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 whith the caller
267 $this->myobject->context['caller'] = $request_data['caller'];
268 continue;
269 }
270
271 if ($field == 'array_options' && is_array($value)) {
272 foreach ($value as $index => $val) {
273 $this->myobject->array_options[$index] = $this->_checkValForAPI($field, $val, $this->myobject);
274 }
275 continue;
276 }
277
278 $this->myobject->$field = $this->_checkValForAPI($field, $value, $this->myobject);
279 }
280
281 // Clean data
282 // $this->myobject->abc = sanitizeVal($this->myobject->abc, 'alphanohtml');
283
284 if ($this->myobject->update(DolibarrApiAccess::$user, false) > 0) {
285 return $this->get($id);
286 } else {
287 throw new RestException(500, $this->myobject->error);
288 }
289 }
290
301 public function delete($id)
302 {
303 if (!DolibarrApiAccess::$user->rights->mymodule->myobject->delete) {
304 throw new RestException(401);
305 }
306 $result = $this->myobject->fetch($id);
307 if (!$result) {
308 throw new RestException(404, 'MyObject not found');
309 }
310
311 if (!DolibarrApi::_checkAccessToResource('myobject', $this->myobject->id, 'mymodule_myobject')) {
312 throw new RestException(401, 'Access to instance id='.$this->myobject->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
313 }
314
315 if ($this->myobject->delete(DolibarrApiAccess::$user) == 0) {
316 throw new RestException(409, 'Error when deleting MyObject : '.$this->myobject->error);
317 } elseif ($this->myobject->delete(DolibarrApiAccess::$user) < 0) {
318 throw new RestException(500, 'Error when deleting MyObject : '.$this->myobject->error);
319 }
320
321 return array(
322 'success' => array(
323 'code' => 200,
324 'message' => 'MyObject deleted'
325 )
326 );
327 }
328
329
338 private function _validate($data)
339 {
340 $myobject = array();
341 foreach ($this->myobject->fields as $field => $propfield) {
342 if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) {
343 continue; // Not a mandatory field
344 }
345 if (!isset($data[$field])) {
346 throw new RestException(400, "$field field missing");
347 }
348 $myobject[$field] = $data[$field];
349 }
350 return $myobject;
351 }
352
353 /*end methods CRUD*/
354
355 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
362 protected function _cleanObjectDatas($object)
363 {
364 // phpcs:enable
365 $object = parent::_cleanObjectDatas($object);
366
367 unset($object->rowid);
368 unset($object->canvas);
369
370 /*unset($object->name);
371 unset($object->lastname);
372 unset($object->firstname);
373 unset($object->civility_id);
374 unset($object->statut);
375 unset($object->state);
376 unset($object->state_id);
377 unset($object->state_code);
378 unset($object->region);
379 unset($object->region_code);
380 unset($object->country);
381 unset($object->country_id);
382 unset($object->country_code);
383 unset($object->barcode_type);
384 unset($object->barcode_type_code);
385 unset($object->barcode_type_label);
386 unset($object->barcode_type_coder);
387 unset($object->total_ht);
388 unset($object->total_tva);
389 unset($object->total_localtax1);
390 unset($object->total_localtax2);
391 unset($object->total_ttc);
392 unset($object->fk_account);
393 unset($object->comments);
394 unset($object->note);
395 unset($object->mode_reglement_id);
396 unset($object->cond_reglement_id);
397 unset($object->cond_reglement);
398 unset($object->shipping_method_id);
399 unset($object->fk_incoterms);
400 unset($object->label_incoterms);
401 unset($object->location_incoterms);
402 */
403
404 // If object has lines, remove $db property
405 if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
406 $nboflines = count($object->lines);
407 for ($i = 0; $i < $nboflines; $i++) {
408 $this->_cleanObjectDatas($object->lines[$i]);
409
410 unset($object->lines[$i]->lines);
411 unset($object->lines[$i]->note);
412 }
413 }
414
415 return $object;
416 }
417}
Class for API REST v1.
Definition api.class.php:31
_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:85
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.
_validate($data)
Validate fields before create or update object.
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.