dolibarr 24.0.0-beta
multicurrency.php
Go to the documentation of this file.
1<?php
2/* <one line to give the program's name and a brief idea of what it does.>
3 * Copyright (C) 2015 ATM Consulting <support@atm-consulting.fr>
4 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
27// Dolibarr environment
28require '../main.inc.php';
29require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
30require_once DOL_DOCUMENT_ROOT.'/core/lib/multicurrency.lib.php';
31require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
32
41// Load translation files required by the page
42$langs->loadLangs(array('admin', 'multicurrency'));
43
44// Access control
45if (!$user->admin || !isModEnabled('multicurrency')) {
47}
48
49// Parameters
50$action = GETPOST('action', 'aZ09');
51
52$multicurrency = new MultiCurrency($db);
53
54
55/*
56 * Actions
57 */
58
59$reg = array();
60if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) {
61 $code = $reg[1];
62 $value = GETPOST($code, 'alpha');
63 if (dolibarr_set_const($db, $code, $value, 'chaine', 0, '', $conf->entity) > 0) {
64 setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
65 } else {
66 setEventMessages($langs->trans("Error"), null, 'errors');
67 }
68}
69
70if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) {
71 $code = $reg[1];
72 if (dolibarr_del_const($db, $code, 0) > 0) {
73 setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
74 } else {
75 setEventMessages($langs->trans("Error"), null, 'errors');
76 }
77}
78
79if ($action == 'add_currency') { // Manual insertion of a rate
80 $error = 0;
81
82 $langs->loadCacheCurrencies('');
83
84 $code = GETPOST('code', 'alpha');
85 $rate = price2num(GETPOST('rate', 'alpha'));
86 $currency = new MultiCurrency($db);
87 $currency->code = $code;
88 $currency->name = !empty($langs->cache_currencies[$code]['label']) ? $langs->cache_currencies[$code]['label'].' ('.$langs->getCurrencySymbol($code).')' : $code;
89
90 if (empty($currency->code) || $currency->code == '-1') {
91 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Currency")), null, 'errors');
92 $error++;
93 }
94 if (empty($rate)) {
95 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Rate")), null, 'errors');
96 $error++;
97 }
98
99 if (!$error) {
100 if ($currency->create($user) > 0) {
101 if ($currency->addRate((float) $rate)) {
102 setEventMessages($langs->trans('RecordSaved'), array());
103 } else {
104 setEventMessages($langs->trans('ErrorAddRateFail'), array(), 'errors');
105 }
106 } else {
107 setEventMessages($langs->trans('ErrorAddCurrencyFail'), $currency->errors, 'errors');
108 }
109 }
110} elseif ($action == 'update_currency') { // Manual update of rate
111 $error = 0;
112
113 if (GETPOST('updatecurrency', 'alpha')) {
114 $fk_multicurrency = GETPOSTINT('fk_multicurrency');
115 $rate = price2num(GETPOST('rate', 'alpha'));
116 $currency = new MultiCurrency($db);
117
118 if (empty($rate)) {
119 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Rate")), null, 'errors');
120 $error++;
121 }
122 if (!$error) {
123 if ($currency->fetch($fk_multicurrency) > 0) {
124 $result = $currency->updateRate((float) $rate);
125 if ($result < 0) {
126 setEventMessages(null, $currency->errors, 'errors');
127 }
128 }
129 }
130 } elseif (GETPOST('deletecurrency', 'alpha')) {
131 $fk_multicurrency = GETPOSTINT('fk_multicurrency');
132 $currency = new MultiCurrency($db);
133
134 if ($currency->fetch($fk_multicurrency) > 0) {
135 if ($currency->delete($user) > 0) {
136 setEventMessages($langs->trans('RecordDeleted'), array());
137 } else {
138 setEventMessages($langs->trans('ErrorDeleteCurrencyFail'), array(), 'errors');
139 }
140 }
141 }
142} elseif ($action == 'setapilayer') { // Update rate from currencylayer
143 if (GETPOSTISSET('modify_apilayer')) {
144 // Save setup
145 dolibarr_set_const($db, 'MULTICURRENCY_APP_KEY', GETPOST('MULTICURRENCY_APP_KEY', 'alpha'), 'chaine', 0, '', $conf->entity);
146 dolibarr_set_const($db, 'MULTICURRENCY_APP_SOURCE', GETPOST('MULTICURRENCY_APP_SOURCE', 'alpha'), 'chaine', 0, '', $conf->entity);
147 dolibarr_set_const($db, 'MULTICURRENCY_APP_ENDPOINT', GETPOST('MULTICURRENCY_APP_ENDPOINT', 'alpha'), 'chaine', 0, '', $conf->entity);
148 //dolibarr_set_const($db, 'MULTICURRENCY_ALTERNATE_SOURCE', GETPOST('MULTICURRENCY_ALTERNATE_SOURCE', 'alpha'), 'chaine', 0, '', $conf->entity);
149
150 setEventMessages($langs->trans("SetupSaved"), null);
151 } else {
152 // Run the update o currency rate (this may updates database)
153 $result = $multicurrency->syncRates(0, 0, '');
154 if ($result > 0) {
155 setEventMessages($langs->trans("CurrencyRateSyncSucceed"), null, "mesgs");
156 } else {
157 setEventMessages($multicurrency->output, null, 'errors');
158 }
159 }
160}
161
162
163$TAvailableCurrency = array();
164$sql = "SELECT code_iso, label, unicode, active FROM ".MAIN_DB_PREFIX."c_currencies";
165$resql = $db->query($sql);
166if ($resql) {
167 while ($obj = $db->fetch_object($resql)) {
168 $TAvailableCurrency[$obj->code_iso] = array('code' => $obj->code_iso, 'active' => $obj->active);
169 }
170}
171
172$TCurrency = array();
173$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."multicurrency WHERE entity = ".((int) $conf->entity);
174$resql = $db->query($sql);
175if ($resql) {
176 while ($obj = $db->fetch_object($resql)) {
177 $currency = new MultiCurrency($db);
178 $currency->fetch($obj->rowid);
179 $TCurrency[] = $currency;
180 }
181}
182
183
184/*
185 * View
186 */
187
188$form = new Form($db);
189
190$page_name = "MultiCurrencySetup";
191$help_url = '';
192
193llxHeader('', $langs->trans($page_name), $help_url, '', 0, 0, '', '', '', 'mod-admin page-multicurrency');
194
195// Subheader
196$linkback = '<a href="'.dolBuildUrl(DOL_URL_ROOT.'/admin/modules.php', ['restore_lastsearch_values' => 1]).'">'.img_picto($langs->trans("BackToModuleList"), 'back', 'class="pictofixedwidth"').'<span class="hideonsmartphone">'.$langs->trans("BackToModuleList").'</span></a>';
197
198print load_fiche_titre($langs->trans($page_name), $linkback);
199
200// Configuration header
202print dol_get_fiche_head($head, 'settings', $langs->trans($page_name), -1, "multicurrency");
203
204
205print '<br>';
206
207
208print '<div class="div-table-responsive-no-min">';
209print '<table class="noborder centpercent">';
210print '<tr class="liste_titre">';
211print '<td>'.$langs->trans("Parameters").'</td>'."\n";
212print '<td class="center">'.$langs->trans("Status").'</td>'."\n";
213print '</tr>';
214
215print '<tr class="oddeven">';
216print '<td>'.$langs->transnoentitiesnoconv("MULTICURRENCY_USE_RATE_ON_DOCUMENT_DATE").'</td>';
217print '<td class="center">';
218if ($conf->use_javascript_ajax) {
219 print ajax_constantonoff('MULTICURRENCY_USE_RATE_ON_DOCUMENT_DATE');
220} else {
221 $arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
222 print $form->selectarray("MULTICURRENCY_USE_RATE_ON_DOCUMENT_DATE", $arrval, getDolGlobalInt("MULTICURRENCY_USE_RATE_ON_DOCUMENT_DATE"));
223}
224print '</td></tr>';
225
226
227print '<tr class="oddeven">';
228$tooltip = $langs->trans("multicurrency_useOriginTxHelp");
229print '<td>'.$form->textwithpicto($langs->transnoentitiesnoconv("multicurrency_useOriginTx"), $tooltip).'</td>';
230print '<td class="center">';
231if ($conf->use_javascript_ajax) {
232 print ajax_constantonoff('MULTICURRENCY_USE_ORIGIN_TX', array(), null, 0, 0, 0, 2, 0, 1);
233} else {
234 $arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
235 print $form->selectarray("MULTICURRENCY_USE_ORIGIN_TX", $arrval, getDolGlobalInt("MULTICURRENCY_USE_ORIGIN_TX"));
236}
237print '</td></tr>';
238
239// Online payment with currency on document. This option should be on by default.
240if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2) {
241 print '<tr class="oddeven">';
242 print '<td>'.$langs->transnoentitiesnoconv("MULTICURRENCY_USE_CURRENCY_ON_DOCUMENT").'</td>';
243 print '<td class="center">';
244 if ($conf->use_javascript_ajax) {
245 print ajax_constantonoff('MULTICURRENCY_USE_CURRENCY_ON_DOCUMENT');
246 } else {
247 $arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
248 print $form->selectarray("MULTICURRENCY_USE_CURRENCY_ON_DOCUMENT", $arrval, getDolGlobalInt("MULTICURRENCY_USE_CURRENCY_ON_DOCUMENT"));
249 }
250 print '</td></tr>';
251}
252
253/* TODO uncomment when the functionality will integrated
254
255print '<tr class="oddeven">';
256print '<td>'.$langs->transnoentitiesnoconv("multicurrency_buyPriceInCurrency").'</td>';
257print '<td class="right">';
258print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
259print '<input type="hidden" name="token" value="'.newToken().'">';
260print '<input type="hidden" name="action" value="set_MULTICURRENCY_BUY_PRICE_IN_CURRENCY">';
261print $form->selectyesno("MULTICURRENCY_BUY_PRICE_IN_CURRENCY",$conf->global->MULTICURRENCY_BUY_PRICE_IN_CURRENCY,1);
262print '<input type="submit" class="button button-edit" value="'.$langs->trans("Modify").'">';
263print '</form>';
264print '</td></tr>';
265*/
266
267/* TODO uncomment when the functionality will integrated
268
269print '<tr class="oddeven">';
270print '<td>'.$langs->transnoentitiesnoconv("multicurrency_modifyRateApplication").'</td>';
271print '<td class="right">';
272print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
273print '<input type="hidden" name="token" value="'.newToken().'">';
274print '<input type="hidden" name="action" value="set_MULTICURRENCY_MODIFY_RATE_APPLICATION">';
275print $form->selectarray('MULTICURRENCY_MODIFY_RATE_APPLICATION', array('PU_DOLIBARR' => 'PU_DOLIBARR', 'PU_CURRENCY' => 'PU_CURRENCY'), $conf->global->MULTICURRENCY_MODIFY_RATE_APPLICATION);
276print '<input type="submit" class="button button-edit" value="'.$langs->trans("Modify").'">';
277print '</form>';
278print '</td></tr>';
279
280*/
281
282print '</table>';
283print '</div>';
284
285print '<br>';
286
287print '<div class="div-table-responsive-no-min">';
288print '<table class="noborder centpercent nomarginbottom">';
289
290print '<tr class="liste_titre">';
291print '<td>'.$form->textwithpicto($langs->trans("CurrenciesUsed"), $langs->transnoentitiesnoconv("CurrenciesUsed_help_to_add")).'</td>'."\n";
292print '<td class="right">'.$langs->trans("Rate").' / '.$langs->getCurrencySymbol(getDolCurrency()).'</td>'."\n";
293print '</tr>';
294
295print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
296print '<input type="hidden" name="token" value="'.newToken().'">';
297print '<input type="hidden" name="action" value="add_currency">';
298
299print '<tr class="oddeven">';
300print '<td>'.$form->selectCurrency('', 'code', 1, '1').'</td>';
301print '<td class="right">';
302print '<input type="text" name="rate" value="" class="width75 right" placeholder="'.$langs->trans('Rate').'" />&nbsp;';
303print '<input type="submit" class="button button-add smallpaddingimp" value="'.$langs->trans("Add").'">';
304print '</td>';
305print '</tr>';
306
307print '</form>';
308
309// Main currency
310print '<tr class="oddeven">';
311print '<td>'.getDolCurrency();
312print ' ('.$langs->getCurrencySymbol(getDolCurrency()).')';
313print $form->textwithpicto(' ', $langs->trans("BaseCurrency"));
314if (!empty($TAvailableCurrency[getDolCurrency()]) && empty($TAvailableCurrency[getDolCurrency()]['active'])) {
315 print img_warning('Warning: This code has been disabled into Home - Setup - Dictionaries - Currencies');
316}
317print '</td>';
318print '<td class="right">1</td>';
319print '</tr>';
320
321foreach ($TCurrency as &$currency) {
322 if ($currency->code == getDolCurrency()) {
323 continue;
324 }
325
326 print '<tr class="oddeven">';
327 print '<td>'.$currency->code.' - '.$currency->name;
328 if (!empty($TAvailableCurrency[$currency->code]) && empty($TAvailableCurrency[$currency->code]['active'])) {
329 print img_warning('Warning: The code '.$currency->code.' has been disabled into Home - Setup - Dictionaries - Currencies');
330 }
331 print '</td>';
332 print '<td class="right">';
333 print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
334 print '<input type="hidden" name="token" value="'.newToken().'">';
335 print '<input type="hidden" name="action" value="update_currency">';
336 print '<input type="hidden" name="fk_multicurrency" value="'.$currency->id.'">';
337 print '1 '.getDolCurrency().' = ';
338 print '<input type="text" name="rate" class="width125 right" value="'.($currency->rate->rate ? $currency->rate->rate : '').'">&nbsp;'.$currency->code.'&nbsp;';
339 print '<input type="submit" name="updatecurrency" class="button button-edit smallpaddingimp" value="'.$langs->trans("Modify").'">&nbsp;';
340 print '<input type="submit" name="deletecurrency" class="button smallpaddingimp" value="'.$langs->trans("Delete").'">';
341 print '</form>';
342 print '</td></tr>';
343}
344
345print '</table>';
346print '</div>';
347
348print '
349 <script type="text/javascript">
350 function getRates()
351 {
352 $("#bt_sync").attr("disabled", true);
353 return true;
354 }
355 </script>
356';
357
358
359print '<br>';
360
361if (!getDolGlobalString('MULTICURRENCY_DISABLE_SYNC_CURRENCYLAYER')) {
362 print '<br>';
363
364 print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'" id="form_sync">';
365 print '<input type="hidden" name="token" value="'.newToken().'">';
366 print '<input type="hidden" name="action" value="setapilayer">';
367
368 print '<div class="div-table-responsive-no-min">';
369 print '<table class="noborder centpercent">';
370
371 $urlforapilayer = 'https://currencylayer.com'; //https://apilayer.net
372
373 $endpointdefault = 'https://api.currencylayer.com/live?access_key=__MULTICURRENCY_APP_KEY__&source=__MULTICURRENCY_APP_SOURCE__';
374 $endpointdefault2 = 'https://api.apilayer.com/currency_data/live?base=__MULTICURRENCY_APP_SOURCE__';
375
376 $tooltiptext = $langs->trans("CurrencyLayerAccount_help_to_synchronize", $urlforapilayer).'<br><span class="small">';
377 $tooltiptext .= '<br>- Endpoint for currencylayer:<br>'.$endpointdefault;
378 $tooltiptext .= '<br>- Endpoint for apilayer:<br>'.$endpointdefault2;
379 $tooltiptext .= '</span><br>';
380
381 print '<tr class="liste_titre">';
382 print '<td>'.$form->textwithpicto($langs->trans("CurrencyLayerAccount"), $tooltiptext, 1, 'help', 'valignmiddle', 0, 3, 'tooltipcurrencylayer').'</td>'."\n";
383 print '<td class="right">';
384 print '<textarea id="response" class="hideobject" name="response"></textarea>';
385 print '<input type="submit" name="modify_apilayer" class="button buttongen" value="'.$langs->trans("Modify").'">';
386 print '<input type="submit" id="bt_sync" name="bt_sync_apilayer" class="button buttongen" value="'.$langs->trans('Synchronize').'"';
387 if (!getDolGlobalString('MULTICURRENCY_APP_KEY')) {
388 print ' disabled="disabled"';
389 }
390 print '/>';
391 print '</td></tr>';
392
393 print '<tr class="oddeven">';
394 print '<td>'.$langs->transnoentitiesnoconv("multicurrency_appId").'</td>';
395 print '<td class="right">';
396 print '<input class="width300" type="text" name="MULTICURRENCY_APP_KEY" value="' . getDolGlobalString('MULTICURRENCY_APP_KEY').'" />&nbsp;';
397 print '</td></tr>';
398
399 print '<tr class="oddeven">';
400 print '<td>'.$langs->transnoentitiesnoconv("multicurrency_appCurrencySource").'</td>';
401 print '<td class="right">';
402 print '<input type="text" name="MULTICURRENCY_APP_SOURCE" value="' . getDolGlobalString('MULTICURRENCY_APP_SOURCE').'" size="10" placeholder="USD" />&nbsp;'; // Default: USD
403 print '</td></tr>';
404
405 print '<tr class="oddeven">';
406 print '<td>'.$langs->transnoentitiesnoconv("MULTICURRENCY_APP_ENDPOINT").'</td>';
407 print '<td class="right">';
408 print '<input class="width500" type="text" name="MULTICURRENCY_APP_ENDPOINT" value="' . getDolGlobalString('MULTICURRENCY_APP_ENDPOINT', MultiCurrency::MULTICURRENCY_APP_ENDPOINT_DEFAULT).'" />&nbsp;';
409 print '</td></tr>';
410
411 /*print '<tr class="oddeven">';
412 print '<td>'.$langs->transnoentitiesnoconv("multicurrency_alternateCurrencySource").'</td>';
413 print '<td class="right">';
414 print '<input type="text" name="MULTICURRENCY_ALTERNATE_SOURCE" value="'.$conf->global->MULTICURRENCY_ALTERNATE_SOURCE.'" size="10" placeholder="EUR" />&nbsp;'; // Example: EUR
415 print '</td></tr>';*/
416
417 print '</table>';
418 print '</div>';
419 print '<br>';
420
421 print '</form>';
422}
423
424
425// End of page
426llxFooter();
427$db->close();
dolibarr_set_const($db, $name, $value, $type='chaine', $visible=0, $note='', $entity=1)
Insert a parameter (key,value) into database (delete old key then insert it again).
dolibarr_del_const($db, $name, $entity=1)
Delete a constant.
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
Class to manage generation of HTML components Only common components must be here.
Class Currency.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getDolCurrency()
Return the main currency ('EUR', 'USD', ...)
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
multicurrencyAdminPrepareHead()
Prepare array with list of tabs.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.