dolibarr 21.0.0-beta
api_multicurrencies.class.php
1<?php
2/* Copyright (C) 2022 J-F Bouculat <jfbouculat@gmail.com>
3 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
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
21//require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
22require_once DOL_DOCUMENT_ROOT.'/core/lib/multicurrency.lib.php';
23
31{
35 public function __construct()
36 {
37 global $db;
38
39 $this->db = $db;
40 }
41
57 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '')
58 {
59 global $db;
60
61 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'read')) {
62 throw new RestException(403, "Insufficient rights to read currency");
63 }
64
65 $obj_ret = array();
66
67 $sql = "SELECT t.rowid";
68 $sql .= " FROM ".$this->db->prefix()."multicurrency as t";
69 $sql .= ' WHERE 1 = 1';
70 // Add sql filters
71 if ($sqlfilters) {
72 $errormessage = '';
73 if (!DolibarrApi::_checkFilters($sqlfilters, $errormessage)) {
74 throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
75 }
76 $regexstring = '\‍(([^:\'\‍(\‍)]+:[^:\'\‍(\‍)]+:[^\‍(\‍)]+)\‍)';
77 $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
78 }
79
80 $sql .= $this->db->order($sortfield, $sortorder);
81 if ($limit) {
82 if ($page < 0) {
83 $page = 0;
84 }
85 $offset = $limit * $page;
86
87 $sql .= $this->db->plimit($limit + 1, $offset);
88 }
89
90 $result = $this->db->query($sql);
91 if ($result) {
92 $i = 0;
93 $num = $this->db->num_rows($result);
94 $min = min($num, ($limit <= 0 ? $num : $limit));
95 while ($i < $min) {
96 $obj = $this->db->fetch_object($result);
97 $multicurrency_static = new MultiCurrency($this->db);
98 if ($multicurrency_static->fetch($obj->rowid)) {
99 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($multicurrency_static), $properties);
100 }
101 $i++;
102 }
103 } else {
104 throw new RestException(503, 'Error when retrieve currencies list : '.$this->db->lasterror());
105 }
106
107 return $obj_ret;
108 }
109
120 public function get($id)
121 {
122 $multicurrency = new MultiCurrency($this->db);
123 if (!$multicurrency->fetch($id)) {
124 throw new RestException(404, 'Currency not found');
125 }
126
127 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'read')) {
128 throw new RestException(403, "Insufficient rights to read currency");
129 }
130
131 return $this->_cleanObjectDatas($multicurrency);
132 }
133
145 public function getByCode($code)
146 {
147 $multicurrency = new MultiCurrency($this->db);
148 if (!$multicurrency->fetch(0, $code)) {
149 throw new RestException(404, 'Currency not found');
150 }
151
152 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'read')) {
153 throw new RestException(403, "Insufficient rights to read currency");
154 }
155
156 return $this->_cleanObjectDatas($multicurrency);
157 }
158
170 public function getRates($id)
171 {
172 $multicurrency = new MultiCurrency($this->db);
173 if (!$multicurrency->fetch($id)) {
174 throw new RestException(404, 'Currency not found');
175 }
176
177 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'read')) {
178 throw new RestException(403, "Insufficient rights to read currency rates");
179 }
180
181 if ($multicurrency->fetchAllCurrencyRate() < 0) {
182 throw new RestException(500, "Error when fetching currency rates");
183 }
184
185 // Clean object datas
186 foreach ($multicurrency->rates as $key => $obj) {
187 $multicurrency->rates[$key] = $this->_cleanObjectDatasRate($obj);
188 }
189
190 return $multicurrency->rates;
191 }
192
201 public function post($request_data = null)
202 {
203
204 // Check parameters
205 if (!isset($request_data['code'])) {
206 throw new RestException(400, "code field missing");
207 }
208 if (!isset($request_data['name'])) {
209 throw new RestException(400, "name field missing");
210 }
211
212 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'write')) {
213 throw new RestException(403, "Insufficient rights to create currency");
214 }
215
216 $multicurrency = new MultiCurrency($this->db);
217
218 foreach ($request_data as $field => $value) {
219 if ($field === 'caller') {
220 // 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
221 $multicurrency->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
222 continue;
223 }
224
225 $multicurrency->$field = $this->_checkValForAPI($field, $value, $multicurrency);
226 }
227
228 // Create Currency
229 if ($multicurrency->create(DolibarrApiAccess::$user) < 0) {
230 throw new RestException(500, "Error creating currency", array_merge(array($multicurrency->error), $multicurrency->errors));
231 }
232
233 // Add default rate if defined
234 if (isset($request_data['rate']) && $request_data['rate'] > 0) {
235 if ($multicurrency->addRate($request_data['rate']) < 0) {
236 throw new RestException(500, "Error adding currency rate", array_merge(array($multicurrency->error), $multicurrency->errors));
237 }
238
239 return $multicurrency->id;
240 }
241
242 return $multicurrency->id;
243 }
244
254 public function put($id, $request_data = null)
255 {
256 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'write')) {
257 throw new RestException(403, "Insufficient rights to update currency");
258 }
259
260 $multicurrency = new MultiCurrency($this->db);
261 if (!$multicurrency->fetch($id)) {
262 throw new RestException(404, 'Currency not found');
263 }
264
265 foreach ($request_data as $field => $value) {
266 if ($field == 'id') {
267 continue;
268 }
269 if ($field === 'caller') {
270 // 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
271 $multicurrency->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
272 continue;
273 }
274
275 $multicurrency->$field = $this->_checkValForAPI($field, $value, $multicurrency);
276 }
277
278 if ($multicurrency->update(DolibarrApiAccess::$user) < 0) {
279 throw new RestException(500, "Error updating currency", array_merge(array($multicurrency->error), $multicurrency->errors));
280 }
281
282 return $this->get($id);
283 }
284
293 public function delete($id)
294 {
295 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'delete')) {
296 throw new RestException(403, "Insufficient rights to delete currency");
297 }
298
299 $multicurrency = new MultiCurrency($this->db);
300 if (!$multicurrency->fetch($id)) {
301 throw new RestException(404, 'Currency not found');
302 }
303
304 if (!$multicurrency->delete(DolibarrApiAccess::$user)) {
305 throw new RestException(500, "Error deleting currency", array_merge(array($multicurrency->error), $multicurrency->errors));
306 }
307
308 return array(
309 'success' => array(
310 'code' => 200,
311 'message' => 'Currency deleted'
312 )
313 );
314 }
315
316
327 public function updateRate($id, $request_data = null)
328 {
329 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'write')) {
330 throw new RestException(403, "Insufficient rights to update currency rate");
331 }
332
333 // Check parameters
334 if (!isset($request_data['rate'])) {
335 throw new RestException(400, "Rate field is missing");
336 }
337
338 $multicurrency = new MultiCurrency($this->db);
339 if (!$multicurrency->fetch($id)) {
340 throw new RestException(404, 'Currency not found');
341 }
342
343 // Add rate
344 if ($multicurrency->addRate($request_data['rate']) < 0) {
345 throw new RestException(500, "Error updating currency rate", array_merge(array($multicurrency->error), $multicurrency->errors));
346 }
347
348 return $this->_cleanObjectDatas($multicurrency);
349 }
350
351 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
358 protected function _cleanObjectDatas($object)
359 {
360 // phpcs:enable
361 $object = parent::_cleanObjectDatas($object);
362
363 // Clear all fields out of interest
364 foreach ($object as $key => $value) {
365 if ($key == "rate") {
366 $object->$key = $this->_cleanObjectDatasRate($object->$key);
367 }
368 if ($key == "id" || $key == "code" || $key == "rate" || $key == "name") {
369 continue;
370 }
371 unset($object->$key);
372 }
373
374 return $object;
375 }
376
377 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
384 protected function _cleanObjectDatasRate($object)
385 {
386 // phpcs:enable
387 $object = parent::_cleanObjectDatas($object);
388
389 // Clear all fields out of interest
390 foreach ($object as $key => $value) {
391 if ($key == "id" || $key == "rate" || $key == "date_sync") {
392 continue;
393 }
394 unset($object->$key);
395 }
396
397 return $object;
398 }
399}
$id
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:66
Class for API REST v1.
Definition api.class.php:30
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
_checkFilters($sqlfilters, &$error='')
Return if a $sqlfilters parameter is valid Function no more used.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition api.class.php:82
_cleanObjectDatasRate($object)
Clean sensible MultiCurrencyRate object datas.
getRates($id)
List Currency rates.
put($id, $request_data=null)
Update Currency.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $sqlfilters='', $properties='')
List Currencies.
updateRate($id, $request_data=null)
Update Currency rate @url PUT {id}/rates.
getByCode($code)
Get properties of a Currency object by code.
_cleanObjectDatas($object)
Clean sensible object datas.
post($request_data=null)
Create Currency object.
Class Currency.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.