dolibarr 23.0.3
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 * Copyright (C) 2025 Frédéric France <frederic.france@free.fr>
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
22//require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
23require_once DOL_DOCUMENT_ROOT.'/core/lib/multicurrency.lib.php';
24
32{
36 public function __construct()
37 {
38 global $db;
39
40 $this->db = $db;
41 }
42
60 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '')
61 {
62 global $db;
63
64 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'read')) {
65 throw new RestException(403, "Insufficient rights to read currency");
66 }
67
68 $obj_ret = array();
69
70 $sql = "SELECT t.rowid";
71 $sql .= " FROM ".$this->db->prefix()."multicurrency as t";
72 $sql .= " WHERE t.entity IN (".getEntity('multicurrency').")";
73 // Add sql filters
74 if ($sqlfilters) {
75 $errormessage = '';
76 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
77 if ($errormessage) {
78 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
79 }
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
372 protected function _cleanObjectDatas($object)
373 {
374 // phpcs:enable
375 $object = parent::_cleanObjectDatas($object);
376
377 // Clear all fields out of interest
378 foreach ($object as $key => $value) {
379 if ($key == "rate") {
380 $object->$key = $this->_cleanObjectDatasRate($object->$key);
381 }
382 if ($key == "id" || $key == "code" || $key == "rate" || $key == "name") {
383 continue;
384 }
385 unset($object->$key);
386 }
387
388 return $object;
389 }
390
391 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
398 protected function _cleanObjectDatasRate($object)
399 {
400 // phpcs:enable
401 $object = parent::_cleanObjectDatas($object);
402
403 // Clear all fields out of interest
404 foreach ($object as $key => $value) {
405 if ($key == "id" || $key == "rate" || $key == "date_sync") {
406 continue;
407 }
408 unset($object->$key);
409 }
410
411 return $object;
412 }
413}
$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:33
_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.
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 @phpstan-template T.
post($request_data=null)
Create Currency object.
Class Currency.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.