dolibarr 21.0.0-alpha
multicurrency.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2007-2020 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2014 Juanjo Menent <jmenent@2byte.es>
4 * Copyright (C) 2015 Florian Henry <florian.henry@open-concept.pro>
5 * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
6 * Copyright (C) 2016 Pierre-Henry Favre <phf@atm-consulting.fr>
7 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
8 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 */
23
30require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
31require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/currencyrate.class.php';
32
40{
44 public $element = 'multicurrency';
45
49 public $table_element = 'multicurrency';
50
54 public $table_element_line = "multicurrency_rate";
55
59 public $rates = array();
60
64 public $id;
65
69 public $code;
70
74 public $name;
75
79 public $entity;
80
84 public $date_create;
85
89 public $fk_user;
90
94 public $rate;
95
96
102 public function __construct(DoliDB $db)
103 {
104 $this->db = $db;
105 }
106
114 public function create(User $user, $notrigger = 0)
115 {
116 global $conf, $langs;
117
118 dol_syslog('MultiCurrency::create', LOG_DEBUG);
119
120 $error = 0;
121
122 if (self::checkCodeAlreadyExists($this->code)) {
123 $error++;
124 $this->errors[] = $langs->trans('multicurrency_code_already_added');
125 return -1;
126 }
127
128 if (empty($this->entity) || $this->entity <= 0) {
129 $this->entity = $conf->entity;
130 }
131 $now = dol_now();
132
133 // Insert request
134 $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element."(";
135 $sql .= ' code,';
136 $sql .= ' name,';
137 $sql .= ' entity,';
138 $sql .= ' date_create,';
139 $sql .= ' fk_user';
140 $sql .= ') VALUES (';
141 $sql .= " '".$this->db->escape($this->code)."',";
142 $sql .= " '".$this->db->escape($this->name)."',";
143 $sql .= " ".((int) $this->entity).",";
144 $sql .= " '".$this->db->idate($now)."',";
145 $sql .= " ".((int) $user->id);
146 $sql .= ')';
147
148 $this->db->begin();
149
150 dol_syslog(__METHOD__, LOG_DEBUG);
151 $resql = $this->db->query($sql);
152 if (!$resql) {
153 $error++;
154 $this->errors[] = 'Error '.$this->db->lasterror();
155 dol_syslog('MultiCurrency::create '.implode(',', $this->errors), LOG_ERR);
156 }
157
158 if (!$error) {
159 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
160 $this->date_create = $now;
161 $this->fk_user = $user->id;
162
163 if (empty($notrigger)) {
164 $result = $this->call_trigger('CURRENCY_CREATE', $user);
165 if ($result < 0) {
166 $error++;
167 }
168 }
169 }
170
171 if ($error) {
172 $this->db->rollback();
173
174 return -1 * $error;
175 } else {
176 $this->db->commit();
177
178 return $this->id;
179 }
180 }
181
189 public function fetch($id, $code = null)
190 {
191 dol_syslog('MultiCurrency::fetch', LOG_DEBUG);
192
193 global $conf;
194
195 $sql = "SELECT";
196 $sql .= ' c.rowid, c.name, c.code, c.entity, c.date_create, c.fk_user';
197 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' AS c';
198 if (!empty($code)) {
199 $sql .= ' WHERE c.code = \''.$this->db->escape($code).'\' AND c.entity = '.$conf->entity;
200 } else {
201 $sql .= ' WHERE c.rowid = '.((int) $id);
202 }
203
204 dol_syslog(__METHOD__, LOG_DEBUG);
205 $resql = $this->db->query($sql);
206
207 if ($resql) {
208 $numrows = $this->db->num_rows($resql);
209 if ($numrows) {
210 $obj = $this->db->fetch_object($resql);
211
212 $this->id = $obj->rowid;
213 $this->name = $obj->name;
214 $this->code = $obj->code;
215 $this->entity = $obj->entity;
216 $this->date_create = $obj->date_create;
217 $this->fk_user = $obj->fk_user;
218
219 $this->fetchAllCurrencyRate();
220 $this->getRate();
221 }
222 $this->db->free($resql);
223
224 if ($numrows) {
225 return 1;
226 } else {
227 return 0;
228 }
229 } else {
230 $this->errors[] = 'Error '.$this->db->lasterror();
231 dol_syslog('MultiCurrency::fetch '.implode(',', $this->errors), LOG_ERR);
232
233 return -1;
234 }
235 }
236
242 public function fetchAllCurrencyRate()
243 {
244 $sql = "SELECT cr.rowid";
245 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as cr';
246 $sql .= ' WHERE cr.fk_multicurrency = '.((int) $this->id);
247 $sql .= ' ORDER BY cr.date_sync DESC';
248
249 $this->rates = array();
250
251 dol_syslog(__METHOD__, LOG_DEBUG);
252 $resql = $this->db->query($sql);
253 if ($resql) {
254 $num = $this->db->num_rows($resql);
255
256 while ($obj = $this->db->fetch_object($resql)) {
257 $rate = new CurrencyRate($this->db);
258 $rate->fetch($obj->rowid);
259
260 $this->rates[] = $rate;
261 }
262 $this->db->free($resql);
263
264 return $num;
265 } else {
266 $this->errors[] = 'Error '.$this->db->lasterror();
267 dol_syslog('MultiCurrency::fetchAllCurrencyRate '.implode(',', $this->errors), LOG_ERR);
268
269 return -1;
270 }
271 }
272
280 public function update(User $user, $notrigger = 0)
281 {
282 $error = 0;
283
284 dol_syslog('MultiCurrency::update', LOG_DEBUG);
285
286 // Clean parameters
287 $this->name = trim($this->name);
288 $this->code = trim($this->code);
289
290 // Check parameters
291 if (empty($this->code)) {
292 $error++;
293 dol_syslog('MultiCurrency::update $this->code can not be empty', LOG_ERR);
294
295 return -1;
296 }
297
298 // Update request
299 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
300 $sql .= " name = '".$this->db->escape($this->name)."',";
301 $sql .= " code = '".$this->db->escape($this->code)."'";
302 $sql .= " WHERE rowid = ".((int) $this->id);
303
304 $this->db->begin();
305
306 $resql = $this->db->query($sql);
307 if (!$resql) {
308 $error++;
309 $this->errors[] = 'Error '.$this->db->lasterror();
310 dol_syslog('MultiCurrency::update '.implode(',', $this->errors), LOG_ERR);
311 }
312
313 if (!$error && empty($notrigger)) {
314 $result = $this->call_trigger('CURRENCY_MODIFY', $user);
315 if ($result < 0) {
316 $error++;
317 }
318 }
319
320 // Commit or rollback
321 if ($error) {
322 $this->db->rollback();
323
324 return -1 * $error;
325 } else {
326 $this->db->commit();
327
328 return 1;
329 }
330 }
331
339 public function delete(User $user, $notrigger = 0)
340 {
341 dol_syslog('MultiCurrency::delete', LOG_DEBUG);
342
343 $error = 0;
344
345 $this->db->begin();
346
347 if (empty($notrigger)) {
348 $result = $this->call_trigger('CURRENCY_DELETE', $user);
349 if ($result < 0) {
350 $error++;
351 }
352 }
353
354 if (!$error) {
355 // Delete all rates before
356 if (!$this->deleteRates()) {
357 $error++;
358 $this->errors[] = 'Error '.$this->db->lasterror();
359 dol_syslog('Currency::delete '.implode(',', $this->errors), LOG_ERR);
360 }
361
362 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
363 $sql .= " WHERE rowid = ".((int) $this->id);
364
365 dol_syslog(__METHOD__, LOG_DEBUG);
366 $resql = $this->db->query($sql);
367 if (!$resql) {
368 $error++;
369 $this->errors[] = 'Error '.$this->db->lasterror();
370 dol_syslog('MultiCurrency::delete '.implode(',', $this->errors), LOG_ERR);
371 }
372 }
373
374 // Commit or rollback
375 if ($error) {
376 $this->db->rollback();
377
378 return -1 * $error;
379 } else {
380 $this->db->commit();
381
382 return 1;
383 }
384 }
385
391 public function deleteRates()
392 {
393 global $user;
394
395 foreach ($this->rates as &$rate) {
396 if ($rate->delete($user) <= 0) {
397 return false;
398 }
399 }
400
401 return true;
402 }
403
410 public function addRate($rate)
411 {
412 global $user;
413
414 $currencyRate = new CurrencyRate($this->db);
415 $currencyRate->rate = (float) price2num($rate);
416
417 if ($currencyRate->create($user, $this->id) > 0) {
418 $this->rate = $currencyRate;
419 return 1;
420 } else {
421 $this->rate = null;
422 $this->errors = $currencyRate->errors;
423 return -1;
424 }
425 }
426
434 public function addRateFromDolibarr($code, $rate)
435 {
436 global $user;
437
438 $currency = new MultiCurrency($this->db);
439 $currency->code = $code;
440 $currency->name = $code;
441
442 $sql = "SELECT label FROM ".MAIN_DB_PREFIX."c_currencies WHERE code_iso = '".$this->db->escape($code)."'";
443
444 dol_syslog(__METHOD__, LOG_DEBUG);
445 $resql = $this->db->query($sql);
446 if ($resql && ($line = $this->db->fetch_object($resql))) {
447 $currency->name = $line->label;
448 }
449
450 if ($currency->create($user) > 0) {
451 $currency->addRate($rate);
452
453 if (!empty($line)) {
454 return 2;
455 } else {
456 return 1;
457 }
458 }
459
460 return -1;
461 }
462
469 public function updateRate($rate)
470 {
471 return $this->addRate($rate);
472 }
473
479 public function getRate()
480 {
481 $sql = "SELECT cr.rowid";
482 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element_line." as cr";
483 $sql .= " WHERE cr.fk_multicurrency = ".((int) $this->id);
484 $sql .= " AND cr.date_sync = (SELECT MAX(cr2.date_sync) FROM ".MAIN_DB_PREFIX.$this->table_element_line." AS cr2 WHERE cr2.fk_multicurrency = ".((int) $this->id).")";
485
486 dol_syslog(__METHOD__, LOG_DEBUG);
487 $resql = $this->db->query($sql);
488 if ($resql && ($obj = $this->db->fetch_object($resql))) {
489 $this->rate = new CurrencyRate($this->db);
490 return $this->rate->fetch($obj->rowid);
491 }
492
493 return -1;
494 }
495
504 public static function getIdFromCode($dbs, $code)
505 {
506 global $conf;
507
508 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."multicurrency WHERE code = '".$dbs->escape($code)."' AND entity = ".((int) $conf->entity);
509
510 dol_syslog(__METHOD__, LOG_DEBUG);
511 $resql = $dbs->query($sql);
512 if ($resql && $obj = $dbs->fetch_object($resql)) {
513 return $obj->rowid;
514 } else {
515 return 0;
516 }
517 }
518
529 public static function getIdAndTxFromCode($dbs, $code, $date_document = '')
530 {
531 global $conf;
532
533 $sql1 = "SELECT m.rowid, mc.rate FROM ".MAIN_DB_PREFIX."multicurrency m";
534
535 $sql1 .= ' LEFT JOIN '.MAIN_DB_PREFIX.'multicurrency_rate mc ON (m.rowid = mc.fk_multicurrency)';
536 $sql1 .= " WHERE m.code = '".$dbs->escape($code)."'";
537 $sql1 .= " AND m.entity IN (".getEntity('multicurrency').")";
538 $sql2 = '';
539 if (getDolGlobalString('MULTICURRENCY_USE_RATE_ON_DOCUMENT_DATE') && !empty($date_document)) { // Use last known rate compared to document date
540 $tmparray = dol_getdate($date_document);
541 $sql2 .= " AND mc.date_sync <= '".$dbs->idate(dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], true))."'";
542 }
543 $sql3 = " ORDER BY mc.date_sync DESC LIMIT 1";
544
545 dol_syslog(__METHOD__, LOG_DEBUG);
546 $resql = $dbs->query($sql1.$sql2.$sql3);
547
548 if ($resql && $obj = $dbs->fetch_object($resql)) {
549 return array($obj->rowid, $obj->rate);
550 } else {
551 if (getDolGlobalString('MULTICURRENCY_USE_RATE_ON_DOCUMENT_DATE')) {
552 $resql = $dbs->query($sql1.$sql3);
553 if ($resql && $obj = $dbs->fetch_object($resql)) {
554 return array($obj->rowid, $obj->rate);
555 }
556 }
557
558 return array(0, 1);
559 }
560 }
561
572 public static function getAmountConversionFromInvoiceRate($fk_facture, $amount, $way = 'dolibarr', $table = 'facture', $invoice_rate = null)
573 {
574 if (!is_null($invoice_rate)) {
575 $multicurrency_tx = $invoice_rate;
576 } else {
577 $multicurrency_tx = self::getInvoiceRate($fk_facture, $table);
578 }
579
580 if ($multicurrency_tx) {
581 if ($way == 'dolibarr') {
582 return (float) price2num($amount * $multicurrency_tx, 'MU');
583 } else {
584 return (float) price2num($amount / $multicurrency_tx, 'MU');
585 }
586 } else {
587 return false;
588 }
589 }
590
598 public static function getInvoiceRate($fk_facture, $table = 'facture')
599 {
600 global $db;
601
602 $sql = "SELECT multicurrency_tx FROM ".MAIN_DB_PREFIX.$table." WHERE rowid = ".((int) $fk_facture);
603
604 dol_syslog(__METHOD__, LOG_DEBUG);
605 $resql = $db->query($sql);
606 if ($resql && ($line = $db->fetch_object($resql))) {
607 return $line->multicurrency_tx;
608 }
609
610 return false;
611 }
612
620 public function recalculRates(&$TRate)
621 {
622 global $conf;
623
624 if ($conf->currency != getDolGlobalString('MULTICURRENCY_APP_SOURCE')) {
625 $alternate_source = 'USD'.$conf->currency;
626 if (!empty($TRate->$alternate_source)) {
627 $coef = 1 / $TRate->$alternate_source;
628 foreach ($TRate as $attr => &$rate) {
629 $rate *= $coef;
630 }
631 $TRate->USDUSD = $coef;
632 return 1;
633 }
634
635 return -1; // Alternate source not found
636 }
637
638 return 0; // Nothing to do
639 }
640
649 public function syncRates($key, $addifnotfound = 0, $mode = "")
650 {
651 global $conf, $db, $langs;
652
653 if (getDolGlobalString('MULTICURRENCY_DISABLE_SYNC_CURRENCYLAYER')) {
654 if ($mode == "cron") {
655 $this->output = $langs->trans('Use of API for currency update is disabled by option MULTICURRENCY_DISABLE_SYNC_CURRENCYLAYER');
656 } else {
657 setEventMessages($langs->trans('Use of API for currency update is disabled by option MULTICURRENCY_DISABLE_SYNC_CURRENCYLAYER'), null, 'errors');
658 }
659 return -1;
660 }
661
662 if (empty($key)) {
663 $key = getDolGlobalString("MULTICURRENCY_APP_ID");
664 }
665
666 include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
667
668 $urlendpoint = 'http://api.currencylayer.com/live?access_key='.$key;
669 $urlendpoint .= '&source=' . (!getDolGlobalString('MULTICURRENCY_APP_SOURCE') ? 'USD' : $conf->global->MULTICURRENCY_APP_SOURCE);
670
671 dol_syslog("Call url endpoint ".$urlendpoint);
672
673 $resget = getURLContent($urlendpoint);
674
675 if ($resget['content']) {
676 $response = $resget['content'];
677 $response = json_decode($response);
678
679 if ($response->success) {
680 $TRate = $response->quotes;
681 //$timestamp = $response->timestamp;
682
683 if ($this->recalculRates($TRate) >= 0) {
684 foreach ($TRate as $currency_code => $rate) {
685 $code = substr($currency_code, 3, 3);
686 $obj = new MultiCurrency($db);
687 if ($obj->fetch(0, $code) > 0) {
688 $obj->updateRate($rate);
689 } elseif ($addifnotfound) {
690 $this->addRateFromDolibarr($code, $rate);
691 }
692 }
693 }
694
695 if ($mode == "cron") {
696 return 0;
697 }
698 return 1;
699 } else {
700 dol_syslog("Failed to call endpoint ".$response->error->info, LOG_WARNING);
701 if ($mode == "cron") {
702 $this->output = $langs->trans('multicurrency_syncronize_error', $response->error->info);
703 } else {
704 setEventMessages($langs->trans('multicurrency_syncronize_error', $response->error->info), null, 'errors');
705 }
706 return -1;
707 }
708 } else {
709 return -1;
710 }
711 }
712
719 public function checkCodeAlreadyExists($code)
720 {
721 $currencytmp = new MultiCurrency($this->db);
722 if ($currencytmp->fetch('', $code) > 0) {
723 return true;
724 } else {
725 return false;
726 }
727 }
728}
Parent class of all other business classes (invoices, contracts, proposals, orders,...
call_trigger($triggerName, $user)
Call trigger based on this instance.
Class to manage Dolibarr database access.
Class Currency.
delete(User $user, $notrigger=0)
Delete object in database.
update(User $user, $notrigger=0)
Update object into database.
fetchAllCurrencyRate()
Load all rates in object from the database.
checkCodeAlreadyExists($code)
Check in database if the current code already exists.
__construct(DoliDB $db)
Constructor.
create(User $user, $notrigger=0)
Create object into database.
addRateFromDolibarr($code, $rate)
Try get label of code in llx_currency then add rate.
recalculRates(&$TRate)
With free account we can't set source then recalcul all rates to force another source.
fetch($id, $code=null)
Load object in memory from the database.
Class to manage Dolibarr users.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
dol_now($mode='auto')
Return date for now.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getURLContent($url, $postorget='GET', $param='', $followlocation=1, $addheaders=array(), $allowedschemes=array('http', 'https'), $localurl=0, $ssl_verifypeer=-1)
Function to get a content from an URL (use proxy if proxy defined).
a disabled
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:140