dolibarr 22.0.5
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="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
197print load_fiche_titre($langs->trans($page_name), $linkback);
198
199// Configuration header
201print dol_get_fiche_head($head, 'settings', $langs->trans($page_name), -1, "multicurrency");
202
203
204print '<br>';
205
206
207print '<div class="div-table-responsive-no-min">';
208print '<table class="noborder centpercent">';
209print '<tr class="liste_titre">';
210print '<td>'.$langs->trans("Parameters").'</td>'."\n";
211print '<td class="center">'.$langs->trans("Status").'</td>'."\n";
212print '</tr>';
213
214print '<tr class="oddeven">';
215print '<td>'.$langs->transnoentitiesnoconv("MULTICURRENCY_USE_RATE_ON_DOCUMENT_DATE").'</td>';
216print '<td class="center">';
217if ($conf->use_javascript_ajax) {
218 print ajax_constantonoff('MULTICURRENCY_USE_RATE_ON_DOCUMENT_DATE');
219} else {
220 $arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
221 print $form->selectarray("MULTICURRENCY_USE_RATE_ON_DOCUMENT_DATE", $arrval, $conf->global->MULTICURRENCY_USE_RATE_ON_DOCUMENT_DATE);
222}
223print '</td></tr>';
224
225
226print '<tr class="oddeven">';
227$tooltip = $langs->trans("multicurrency_useOriginTxHelp");
228print '<td>'.$form->textwithpicto($langs->transnoentitiesnoconv("multicurrency_useOriginTx"), $tooltip).'</td>';
229print '<td class="center">';
230if ($conf->use_javascript_ajax) {
231 print ajax_constantonoff('MULTICURRENCY_USE_ORIGIN_TX', array(), null, 0, 0, 0, 2, 0, 1);
232} else {
233 $arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
234 print $form->selectarray("MULTICURRENCY_USE_ORIGIN_TX", $arrval, $conf->global->MULTICURRENCY_USE_ORIGIN_TX);
235}
236print '</td></tr>';
237
238// Online payment with currency on document. This option should be on by default.
239if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2) {
240 print '<tr class="oddeven">';
241 print '<td>'.$langs->transnoentitiesnoconv("MULTICURRENCY_USE_CURRENCY_ON_DOCUMENT").'</td>';
242 print '<td class="center">';
243 if ($conf->use_javascript_ajax) {
244 print ajax_constantonoff('MULTICURRENCY_USE_CURRENCY_ON_DOCUMENT');
245 } else {
246 $arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
247 print $form->selectarray("MULTICURRENCY_USE_CURRENCY_ON_DOCUMENT", $arrval, $conf->global->MULTICURRENCY_USE_CURRENCY_ON_DOCUMENT);
248 }
249 print '</td></tr>';
250}
251
252/* TODO uncomment when the functionality will integrated
253
254print '<tr class="oddeven">';
255print '<td>'.$langs->transnoentitiesnoconv("multicurrency_buyPriceInCurrency").'</td>';
256print '<td class="right">';
257print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
258print '<input type="hidden" name="token" value="'.newToken().'">';
259print '<input type="hidden" name="action" value="set_MULTICURRENCY_BUY_PRICE_IN_CURRENCY">';
260print $form->selectyesno("MULTICURRENCY_BUY_PRICE_IN_CURRENCY",$conf->global->MULTICURRENCY_BUY_PRICE_IN_CURRENCY,1);
261print '<input type="submit" class="button button-edit" value="'.$langs->trans("Modify").'">';
262print '</form>';
263print '</td></tr>';
264*/
265
266/* TODO uncomment when the functionality will integrated
267
268print '<tr class="oddeven">';
269print '<td>'.$langs->transnoentitiesnoconv("multicurrency_modifyRateApplication").'</td>';
270print '<td class="right">';
271print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
272print '<input type="hidden" name="token" value="'.newToken().'">';
273print '<input type="hidden" name="action" value="set_MULTICURRENCY_MODIFY_RATE_APPLICATION">';
274print $form->selectarray('MULTICURRENCY_MODIFY_RATE_APPLICATION', array('PU_DOLIBARR' => 'PU_DOLIBARR', 'PU_CURRENCY' => 'PU_CURRENCY'), $conf->global->MULTICURRENCY_MODIFY_RATE_APPLICATION);
275print '<input type="submit" class="button button-edit" value="'.$langs->trans("Modify").'">';
276print '</form>';
277print '</td></tr>';
278
279*/
280
281print '</table>';
282print '</div>';
283
284print '<br>';
285
286print '<div class="div-table-responsive-no-min">';
287print '<table class="noborder centpercent nomarginbottom">';
288
289print '<tr class="liste_titre">';
290print '<td>'.$form->textwithpicto($langs->trans("CurrenciesUsed"), $langs->transnoentitiesnoconv("CurrenciesUsed_help_to_add")).'</td>'."\n";
291print '<td class="right">'.$langs->trans("Rate").' / '.$langs->getCurrencySymbol($conf->currency).'</td>'."\n";
292print '</tr>';
293
294print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
295print '<input type="hidden" name="token" value="'.newToken().'">';
296print '<input type="hidden" name="action" value="add_currency">';
297
298print '<tr class="oddeven">';
299print '<td>'.$form->selectCurrency('', 'code', 1, '1').'</td>';
300print '<td class="right">';
301print '<input type="text" name="rate" value="" class="width75 right" placeholder="'.$langs->trans('Rate').'" />&nbsp;';
302print '<input type="submit" class="button button-add smallpaddingimp" value="'.$langs->trans("Add").'">';
303print '</td>';
304print '</tr>';
305
306print '</form>';
307
308// Main currency
309print '<tr class="oddeven">';
310print '<td>'.$conf->currency;
311print ' ('.$langs->getCurrencySymbol($conf->currency).')';
312print $form->textwithpicto(' ', $langs->trans("BaseCurrency"));
313if (!empty($TAvailableCurrency[$conf->currency]) && empty($TAvailableCurrency[$conf->currency]['active'])) {
314 print img_warning('Warning: This code has been disabled into Home - Setup - Dictionaries - Currencies');
315}
316print '</td>';
317print '<td class="right">1</td>';
318print '</tr>';
319
320foreach ($TCurrency as &$currency) {
321 if ($currency->code == $conf->currency) {
322 continue;
323 }
324
325 print '<tr class="oddeven">';
326 print '<td>'.$currency->code.' - '.$currency->name;
327 if (!empty($TAvailableCurrency[$currency->code]) && empty($TAvailableCurrency[$currency->code]['active'])) {
328 print img_warning('Warning: The code '.$currency->code.' has been disabled into Home - Setup - Dictionaries - Currencies');
329 }
330 print '</td>';
331 print '<td class="right">';
332 print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
333 print '<input type="hidden" name="token" value="'.newToken().'">';
334 print '<input type="hidden" name="action" value="update_currency">';
335 print '<input type="hidden" name="fk_multicurrency" value="'.$currency->id.'">';
336 print '1 '.$conf->currency.' = ';
337 print '<input type="text" name="rate" class="width125 right" value="'.($currency->rate->rate ? $currency->rate->rate : '').'">&nbsp;'.$currency->code.'&nbsp;';
338 print '<input type="submit" name="updatecurrency" class="button button-edit smallpaddingimp" value="'.$langs->trans("Modify").'">&nbsp;';
339 print '<input type="submit" name="deletecurrency" class="button smallpaddingimp" value="'.$langs->trans("Delete").'">';
340 print '</form>';
341 print '</td></tr>';
342}
343
344print '</table>';
345print '</div>';
346
347print '
348 <script type="text/javascript">
349 function getRates()
350 {
351 $("#bt_sync").attr("disabled", true);
352 return true;
353 }
354 </script>
355';
356
357
358print '<br>';
359
360if (!getDolGlobalString('MULTICURRENCY_DISABLE_SYNC_CURRENCYLAYER')) {
361 print '<br>';
362
363 print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'" id="form_sync">';
364 print '<input type="hidden" name="token" value="'.newToken().'">';
365 print '<input type="hidden" name="action" value="setapilayer">';
366
367 print '<div class="div-table-responsive-no-min">';
368 print '<table class="noborder centpercent">';
369
370 $urlforapilayer = 'https://currencylayer.com'; //https://apilayer.net
371
372 $endpointdefault = 'https://api.currencylayer.com/live?access_key=__MULTICURRENCY_APP_KEY__&source=__MULTICURRENCY_APP_SOURCE__';
373 $endpointdefault2 = 'https://api.apilayer.com/currency_data/live?base=__MULTICURRENCY_APP_SOURCE__';
374
375 $tooltiptext = $langs->trans("CurrencyLayerAccount_help_to_synchronize", $urlforapilayer).'<br><span class="small">';
376 $tooltiptext .= '<br>- Endpoint for currencylayer:<br>'.$endpointdefault;
377 $tooltiptext .= '<br>- Endpoint for apilayer:<br>'.$endpointdefault2;
378 $tooltiptext .= '</span><br>';
379
380 print '<tr class="liste_titre">';
381 print '<td>'.$form->textwithpicto($langs->trans("CurrencyLayerAccount"), $tooltiptext, 1, 'help', 'valignmiddle', 0, 3, 'tooltipcurrencylayer').'</td>'."\n";
382 print '<td class="right">';
383 print '<textarea id="response" class="hideobject" name="response"></textarea>';
384 print '<input type="submit" name="modify_apilayer" class="button buttongen" value="'.$langs->trans("Modify").'">';
385 print '<input type="submit" id="bt_sync" name="bt_sync_apilayer" class="button buttongen" value="'.$langs->trans('Synchronize').'"';
386 if (!getDolGlobalString('MULTICURRENCY_APP_KEY')) {
387 print ' disabled="disabled"';
388 }
389 print '/>';
390 print '</td></tr>';
391
392 print '<tr class="oddeven">';
393 print '<td>'.$langs->transnoentitiesnoconv("multicurrency_appId").'</td>';
394 print '<td class="right">';
395 print '<input class="width300" type="text" name="MULTICURRENCY_APP_KEY" value="' . getDolGlobalString('MULTICURRENCY_APP_KEY').'" />&nbsp;';
396 print '</td></tr>';
397
398 print '<tr class="oddeven">';
399 print '<td>'.$langs->transnoentitiesnoconv("multicurrency_appCurrencySource").'</td>';
400 print '<td class="right">';
401 print '<input type="text" name="MULTICURRENCY_APP_SOURCE" value="' . getDolGlobalString('MULTICURRENCY_APP_SOURCE').'" size="10" placeholder="USD" />&nbsp;'; // Default: USD
402 print '</td></tr>';
403
404 print '<tr class="oddeven">';
405 print '<td>'.$langs->transnoentitiesnoconv("MULTICURRENCY_APP_ENDPOINT").'</td>';
406 print '<td class="right">';
407 print '<input class="width500" type="text" name="MULTICURRENCY_APP_ENDPOINT" value="' . getDolGlobalString('MULTICURRENCY_APP_ENDPOINT', MultiCurrency::MULTICURRENCY_APP_ENDPOINT_DEFAULT).'" />&nbsp;';
408 print '</td></tr>';
409
410 /*print '<tr class="oddeven">';
411 print '<td>'.$langs->transnoentitiesnoconv("multicurrency_alternateCurrencySource").'</td>';
412 print '<td class="right">';
413 print '<input type="text" name="MULTICURRENCY_ALTERNATE_SOURCE" value="'.$conf->global->MULTICURRENCY_ALTERNATE_SOURCE.'" size="10" placeholder="EUR" />&nbsp;'; // Example: EUR
414 print '</td></tr>';*/
415
416 print '</table>';
417 print '</div>';
418 print '<br>';
419
420 print '</form>';
421}
422
423
424// End of page
425llxFooter();
426$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.
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
Load a title with picto.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
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.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
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.