Merge pull request #13198 from seamuslee001/event_search_561
[civicrm-core.git] / CRM / Utils / Money.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2018
32 */
33
34 /**
35 * Money utilties
36 */
37 class CRM_Utils_Money {
38 static $_currencySymbols = NULL;
39
40 /**
41 * Format a monetary string.
42 *
43 * Format a monetary string basing on the amount provided,
44 * ISO currency code provided and a format string consisting of:
45 *
46 * %a - the formatted amount
47 * %C - the currency ISO code (e.g., 'USD') if provided
48 * %c - the currency symbol (e.g., '$') if available
49 *
50 * @param float $amount
51 * The monetary amount to display (1234.56).
52 * @param string $currency
53 * The three-letter ISO currency code ('USD').
54 * @param string $format
55 * The desired currency format.
56 * @param bool $onlyNumber
57 * @param string $valueFormat
58 * The desired monetary value display format (e.g. '%!i').
59 *
60 * @return string
61 * formatted monetary string
62 *
63 */
64 public static function format($amount, $currency = NULL, $format = NULL, $onlyNumber = FALSE, $valueFormat = NULL) {
65
66 if (CRM_Utils_System::isNull($amount)) {
67 return '';
68 }
69
70 $config = CRM_Core_Config::singleton();
71
72 if (!$format) {
73 $format = $config->moneyformat;
74 }
75
76 if (!$valueFormat) {
77 $valueFormat = $config->moneyvalueformat;
78 }
79
80 if ($onlyNumber) {
81 // money_format() exists only in certain PHP install (CRM-650)
82 if (is_numeric($amount) and function_exists('money_format')) {
83 $amount = money_format($valueFormat, $amount);
84 }
85 return $amount;
86 }
87
88 if (!self::$_currencySymbols) {
89 self::$_currencySymbols = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'currency', array(
90 'keyColumn' => 'name',
91 'labelColumn' => 'symbol',
92 ));
93 }
94
95 if (!$currency) {
96 $currency = $config->defaultCurrency;
97 }
98 $amount = self::formatNumericByFormat($amount, $valueFormat);
99 // If it contains tags, means that HTML was passed and the
100 // amount is already converted properly,
101 // so don't mess with it again.
102 // @todo deprecate handling for the html tags because .... WTF
103 if (strpos($amount, '<') === FALSE) {
104 $amount = self::replaceCurrencySeparators($amount);
105 }
106
107 $replacements = array(
108 '%a' => $amount,
109 '%C' => $currency,
110 '%c' => CRM_Utils_Array::value($currency, self::$_currencySymbols, $currency),
111 );
112 return strtr($format, $replacements);
113 }
114
115 /**
116 * This is a placeholder function for calculating the number of decimal places for a currency.
117 *
118 * Currently code assumes 2 decimal places but some currencies (bitcoin, middle eastern) have
119 * more. By using this function we can signpost the locations where the number of decimal places is
120 * currency specific for future enhancement.
121 *
122 * @param string $currency
123 *
124 * @return int
125 * Number of decimal places.
126 */
127 public static function getCurrencyPrecision($currency = NULL) {
128 return 2;
129 }
130
131 /**
132 * Subtract currencies using integers instead of floats, to preserve precision
133 *
134 * @return float
135 * Result of subtracting $rightOp from $leftOp to the precision of $currency
136 */
137 public static function subtractCurrencies($leftOp, $rightOp, $currency) {
138 if (is_numeric($leftOp) && is_numeric($rightOp)) {
139 $precision = pow(10, self::getCurrencyPrecision($currency));
140 return (($leftOp * $precision) - ($rightOp * $precision)) / $precision;
141 }
142 }
143
144 /**
145 * Tests if two currency values are equal, taking into account the currency's
146 * precision, so that if the difference between the two values is less than
147 * one more order of magnitude for the precision, then the values are
148 * considered as equal. So, if the currency has precision of 2 decimal
149 * points, a difference of more than 0.001 will cause the values to be
150 * considered as different. Anything less than 0.001 will be considered as
151 * equal.
152 *
153 * Eg.
154 *
155 * 1.2312 == 1.2319 with a currency precision of 2 decimal points
156 * 1.2310 != 1.2320 with a currency precision of 2 decimal points
157 * 1.3000 != 1.2000 with a currency precision of 2 decimal points
158 *
159 * @param $value1
160 * @param $value2
161 * @param $currency
162 *
163 * @return bool
164 */
165 public static function equals($value1, $value2, $currency) {
166 $precision = 1 / pow(10, self::getCurrencyPrecision($currency) + 1);
167 $difference = self::subtractCurrencies($value1, $value2, $currency);
168
169 if (abs($difference) > $precision) {
170 return FALSE;
171 }
172
173 return TRUE;
174 }
175
176 /**
177 * Format money for display (just numeric part) according to the current locale.
178 *
179 * This calls the underlying system function but does not handle currency separators.
180 *
181 * It's not totally clear when it changes the $amount value but has historical usage.
182 *
183 * @param $amount
184 *
185 * @return string
186 */
187 protected static function formatLocaleNumeric($amount) {
188 return self::formatNumericByFormat($amount, CRM_Core_Config::singleton()->moneyvalueformat);
189 }
190
191 /**
192 * Format money for display (just numeric part) according to the current locale with rounding.
193 *
194 * At this stage this is conceived as an internal function with the currency wrapper
195 * functions determining the number of places.
196 *
197 * This calls the underlying system function but does not handle currency separators.
198 *
199 * It's not totally clear when it changes the $amount value but has historical usage.
200 *
201 * @param string $amount
202 * @param int $numberOfPlaces
203 *
204 * @return string
205 */
206 protected static function formatLocaleNumericRounded($amount, $numberOfPlaces) {
207 return self::formatLocaleNumeric(round($amount, $numberOfPlaces));
208 }
209
210 /**
211 * Format money for display (just numeric part) according to the current locale with rounding.
212 *
213 * This handles both rounding & replacement of the currency separators for the locale.
214 *
215 * @param string $amount
216 * @param string $currency
217 *
218 * @return string
219 * Formatted amount.
220 */
221 public static function formatLocaleNumericRoundedByCurrency($amount, $currency) {
222 $amount = self::formatLocaleNumericRounded($amount, self::getCurrencyPrecision($currency));
223 return self::replaceCurrencySeparators($amount);
224 }
225
226 /**
227 * Format money for display (just numeric part) according to the current locale with rounding based on the
228 * default currency for the site.
229 *
230 * @param $amount
231 * @return mixed
232 */
233 public static function formatLocaleNumericRoundedForDefaultCurrency($amount) {
234 return self::formatLocaleNumericRoundedByCurrency($amount, self::getCurrencyPrecision(CRM_Core_Config::singleton()->defaultCurrency));
235 }
236
237 /**
238 * Replace currency separators.
239 *
240 * @param string $amount
241 *
242 * @return string
243 */
244 protected static function replaceCurrencySeparators($amount) {
245 $config = CRM_Core_Config::singleton();
246 $rep = array(
247 ',' => $config->monetaryThousandSeparator,
248 '.' => $config->monetaryDecimalPoint,
249 );
250 return strtr($amount, $rep);
251 }
252
253 /**
254 * Format numeric part of currency by the passed in format.
255 *
256 * This is envisaged as an internal function, with wrapper functions defining valueFormat
257 * into easily understood functions / variables and handling separator conversions and
258 * rounding.
259 *
260 * @param string $amount
261 * @param string $valueFormat
262 *
263 * @return string
264 */
265 protected static function formatNumericByFormat($amount, $valueFormat) {
266 // money_format() exists only in certain PHP install (CRM-650)
267 // setlocale() affects native gettext (CRM-11054, CRM-9976)
268 if (is_numeric($amount) && function_exists('money_format')) {
269 $lc = setlocale(LC_MONETARY, 0);
270 setlocale(LC_MONETARY, 'en_US.utf8', 'en_US', 'en_US.utf8', 'en_US', 'C');
271 $amount = money_format($valueFormat, $amount);
272 setlocale(LC_MONETARY, $lc);
273 }
274 return $amount;
275 }
276
277 }