dolibarr 22.0.5
api_multicurrencies.class.php
1<?php
2/* Copyright (C) 2022 J-F Bouculat <jfbouculat@gmail.com>
3 * Copyright (C) 2024-2025 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
59 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '')
60 {
61 global $db;
62
63 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'read')) {
64 throw new RestException(403, "Insufficient rights to read currency");
65 }
66
67 $obj_ret = array();
68
69 $sql = "SELECT t.rowid";
70 $sql .= " FROM ".$this->db->prefix()."multicurrency as t";
71 $sql .= " WHERE t.entity IN (".getEntity('multicurrency').")";
72 // Add sql filters
73 if ($sqlfilters) {
74 $errormessage = '';
75 if (!DolibarrApi::_checkFilters($sqlfilters, $errormessage)) {
76 throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
77 }
78 $regexstring = '\‍(([^:\'\‍(\‍)]+:[^:\'\‍(\‍)]+:[^\‍(\‍)]+)\‍)';
79 $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
80 }
81
82 $sql .= $this->db->order($sortfield, $sortorder);
83 if ($limit) {
84 if ($page < 0) {
85 $page = 0;
86 }
87 $offset = $limit * $page;
88
89 $sql .= $this->db->plimit($limit + 1, $offset);
90 }
91
92 $result = $this->db->query($sql);
93 if ($result) {
94 $i = 0;
95 $num = $this->db->num_rows($result);
96 $min = min($num, ($limit <= 0 ? $num : $limit));
97 while ($i < $min) {
98 $obj = $this->db->fetch_object($result);
99 $multicurrency_static = new MultiCurrency($this->db);
100 if ($multicurrency_static->fetch($obj->rowid)) {
101 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($multicurrency_static), $properties);
102 }
103 $i++;
104 }
105 } else {
106 throw new RestException(503, 'Error when retrieve currencies list : '.$this->db->lasterror());
107 }
108
109 return $obj_ret;
110 }
111
122 public function get($id)
123 {
124 $multicurrency = new MultiCurrency($this->db);
125 if (!$multicurrency->fetch($id)) {
126 throw new RestException(404, 'Currency not found');
127 }
128
129 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'read')) {
130 throw new RestException(403, "Insufficient rights to read currency");
131 }
132
133 return $this->_cleanObjectDatas($multicurrency);
134 }
135
147 public function getByCode($code)
148 {
149 $multicurrency = new MultiCurrency($this->db);
150 if (!$multicurrency->fetch(0, $code)) {
151 throw new RestException(404, 'Currency not found');
152 }
153
154 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'read')) {
155 throw new RestException(403, "Insufficient rights to read currency");
156 }
157
158 return $this->_cleanObjectDatas($multicurrency);
159 }
160
172 public function getRates($id)
173 {
174 $multicurrency = new MultiCurrency($this->db);
175 if (!$multicurrency->fetch($id)) {
176 throw new RestException(404, 'Currency not found');
177 }
178
179 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'read')) {
180 throw new RestException(403, "Insufficient rights to read currency rates");
181 }
182
183 if ($multicurrency->fetchAllCurrencyRate() < 0) {
184 throw new RestException(500, "Error when fetching currency rates");
185 }
186
187 // Clean object datas
188 foreach ($multicurrency->rates as $key => $obj) {
189 $multicurrency->rates[$key] = $this->_cleanObjectDatasRate($obj);
190 }
191
192 return $multicurrency->rates;
193 }
194
205 public function post($request_data = null)
206 {
207
208 // Check parameters
209 if (!isset($request_data['code'])) {
210 throw new RestException(400, "code field missing");
211 }
212 if (!isset($request_data['name'])) {
213 throw new RestException(400, "name field missing");
214 }
215
216 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'write')) {
217 throw new RestException(403, "Insufficient rights to create currency");
218 }
219
220 $multicurrency = new MultiCurrency($this->db);
221
222 foreach ($request_data as $field => $value) {
223 if ($field === 'caller') {
224 // 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
225 $multicurrency->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
226 continue;
227 }
228
229 $multicurrency->$field = $this->_checkValForAPI($field, $value, $multicurrency);
230 }
231
232 // Create Currency
233 if ($multicurrency->create(DolibarrApiAccess::$user) < 0) {
234 throw new RestException(500, "Error creating currency", array_merge(array($multicurrency->error), $multicurrency->errors));
235 }
236
237 // Add default rate if defined
238 if (isset($request_data['rate']) && $request_data['rate'] > 0) {
239 if ($multicurrency->addRate((float) $request_data['rate']) < 0) {
240 throw new RestException(500, "Error adding currency rate", array_merge(array($multicurrency->error), $multicurrency->errors));
241 }
242
243 return $multicurrency->id;
244 }
245
246 return $multicurrency->id;
247 }
248
260 public function put($id, $request_data = null)
261 {
262 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'write')) {
263 throw new RestException(403, "Insufficient rights to update currency");
264 }
265
266 $multicurrency = new MultiCurrency($this->db);
267 if (!$multicurrency->fetch($id)) {
268 throw new RestException(404, 'Currency not found');
269 }
270
271 foreach ($request_data as $field => $value) {
272 if ($field == 'id') {
273 continue;
274 }
275 if ($field === 'caller') {
276 // 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
277 $multicurrency->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
278 continue;
279 }
280
281 $multicurrency->$field = $this->_checkValForAPI($field, $value, $multicurrency);
282 }
283
284 if ($multicurrency->update(DolibarrApiAccess::$user) < 0) {
285 throw new RestException(500, "Error updating currency", array_merge(array($multicurrency->error), $multicurrency->errors));
286 }
287
288 return $this->get($id);
289 }
290
301 public function delete($id)
302 {
303 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'delete')) {
304 throw new RestException(403, "Insufficient rights to delete currency");
305 }
306
307 $multicurrency = new MultiCurrency($this->db);
308 if (!$multicurrency->fetch($id)) {
309 throw new RestException(404, 'Currency not found');
310 }
311
312 if (!$multicurrency->delete(DolibarrApiAccess::$user)) {
313 throw new RestException(500, "Error deleting currency", array_merge(array($multicurrency->error), $multicurrency->errors));
314 }
315
316 return array(
317 'success' => array(
318 'code' => 200,
319 'message' => 'Currency deleted'
320 )
321 );
322 }
323
324
337 public function updateRate($id, $request_data = null)
338 {
339 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'write')) {
340 throw new RestException(403, "Insufficient rights to update currency rate");
341 }
342
343 // Check parameters
344 if (!isset($request_data['rate'])) {
345 throw new RestException(400, "Rate field is missing");
346 }
347
348 $multicurrency = new MultiCurrency($this->db);
349 if (!$multicurrency->fetch($id)) {
350 throw new RestException(404, 'Currency not found');
351 }
352
353 // Add rate
354 if ($multicurrency->addRate((float) $request_data['rate']) < 0) {
355 throw new RestException(500, "Error updating currency rate", array_merge(array($multicurrency->error), $multicurrency->errors));
356 }
357
358 return $this->_cleanObjectDatas($multicurrency);
359 }
360
361 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
368 protected function _cleanObjectDatas($object)
369 {
370 // phpcs:enable
371 $object = parent::_cleanObjectDatas($object);
372
373 // Clear all fields out of interest
374 foreach ($object as $key => $value) {
375 if ($key == "rate") {
376 $object->$key = $this->_cleanObjectDatasRate($object->$key);
377 }
378 if ($key == "id" || $key == "code" || $key == "rate" || $key == "name") {
379 continue;
380 }
381 unset($object->$key);
382 }
383
384 return $object;
385 }
386
387 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
394 protected function _cleanObjectDatasRate($object)
395 {
396 // phpcs:enable
397 $object = parent::_cleanObjectDatas($object);
398
399 // Clear all fields out of interest
400 foreach ($object as $key => $value) {
401 if ($key == "id" || $key == "rate" || $key == "date_sync") {
402 continue;
403 }
404 unset($object->$key);
405 }
406
407 return $object;
408 }
409}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
Class for API REST v1.
Definition api.class.php:33
_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:98
_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.