| 1 | <?php |
| 2 | /* |
| 3 | +--------------------------------------------------------------------+ |
| 4 | | Copyright CiviCRM LLC. All rights reserved. | |
| 5 | | | |
| 6 | | This work is published under the GNU AGPLv3 license with some | |
| 7 | | permitted exceptions and without any warranty. For full license | |
| 8 | | and copyright information, see https://civicrm.org/licensing | |
| 9 | +--------------------------------------------------------------------+ |
| 10 | */ |
| 11 | |
| 12 | /** |
| 13 | * |
| 14 | * @package CRM |
| 15 | * @copyright CiviCRM LLC https://civicrm.org/licensing |
| 16 | */ |
| 17 | |
| 18 | use Brick\Money\Money; |
| 19 | use Brick\Money\Context\DefaultContext; |
| 20 | use Brick\Money\Context\CustomContext; |
| 21 | use Brick\Math\RoundingMode; |
| 22 | |
| 23 | /** |
| 24 | * Money utilties |
| 25 | */ |
| 26 | class CRM_Utils_Money { |
| 27 | public static $_currencySymbols = NULL; |
| 28 | |
| 29 | /** |
| 30 | * Format a monetary string. |
| 31 | * |
| 32 | * Format a monetary string basing on the amount provided, |
| 33 | * ISO currency code provided and a format string consisting of: |
| 34 | * |
| 35 | * %a - the formatted amount |
| 36 | * %C - the currency ISO code (e.g., 'USD') if provided |
| 37 | * %c - the currency symbol (e.g., '$') if available |
| 38 | * |
| 39 | * @param float $amount |
| 40 | * The monetary amount to display (1234.56). |
| 41 | * @param string $currency |
| 42 | * The three-letter ISO currency code ('USD'). |
| 43 | * @param string $format |
| 44 | * The desired currency format. |
| 45 | * @param bool $onlyNumber |
| 46 | * |
| 47 | * @return string |
| 48 | * formatted monetary string |
| 49 | * |
| 50 | */ |
| 51 | public static function format($amount, $currency = NULL, $format = NULL, $onlyNumber = FALSE) { |
| 52 | |
| 53 | if (CRM_Utils_System::isNull($amount)) { |
| 54 | return ''; |
| 55 | } |
| 56 | |
| 57 | $config = CRM_Core_Config::singleton(); |
| 58 | |
| 59 | if (!$format) { |
| 60 | $format = $config->moneyformat; |
| 61 | } |
| 62 | |
| 63 | if (!$currency) { |
| 64 | $currency = $config->defaultCurrency; |
| 65 | } |
| 66 | |
| 67 | if ($onlyNumber) { |
| 68 | $amount = self::formatLocaleNumericRoundedByCurrency($amount, $currency); |
| 69 | return $amount; |
| 70 | } |
| 71 | |
| 72 | if (!self::$_currencySymbols) { |
| 73 | self::$_currencySymbols = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'currency', [ |
| 74 | 'keyColumn' => 'name', |
| 75 | 'labelColumn' => 'symbol', |
| 76 | ]); |
| 77 | } |
| 78 | |
| 79 | // ensure $currency is a valid currency code |
| 80 | // for backwards-compatibility, also accept one space instead of a currency |
| 81 | if ($currency != ' ' && !array_key_exists($currency, self::$_currencySymbols)) { |
| 82 | throw new CRM_Core_Exception("Invalid currency \"{$currency}\""); |
| 83 | } |
| 84 | |
| 85 | if ($currency === ' ') { |
| 86 | CRM_Core_Error::deprecatedWarning('Passing empty currency to CRM_Utils_Money::format is deprecated if you need it for display without currency call CRM_Utils_Money::formatLocaleNumericRounded'); |
| 87 | } |
| 88 | $amount = self::formatUSLocaleNumericRounded($amount, 2); |
| 89 | // If it contains tags, means that HTML was passed and the |
| 90 | // amount is already converted properly, |
| 91 | // so don't mess with it again. |
| 92 | // @todo deprecate handling for the html tags because .... WTF |
| 93 | if (strpos($amount, '<') === FALSE) { |
| 94 | $amount = self::replaceCurrencySeparators($amount); |
| 95 | } |
| 96 | |
| 97 | $replacements = [ |
| 98 | '%a' => $amount, |
| 99 | '%C' => $currency, |
| 100 | '%c' => CRM_Utils_Array::value($currency, self::$_currencySymbols, $currency), |
| 101 | ]; |
| 102 | return strtr($format, $replacements); |
| 103 | } |
| 104 | |
| 105 | /** |
| 106 | * This is a placeholder function for calculating the number of decimal places for a currency. |
| 107 | * |
| 108 | * Currently code assumes 2 decimal places but some currencies (bitcoin, middle eastern) have |
| 109 | * more. By using this function we can signpost the locations where the number of decimal places is |
| 110 | * currency specific for future enhancement. |
| 111 | * |
| 112 | * @param string $currency |
| 113 | * |
| 114 | * @return int |
| 115 | * Number of decimal places. |
| 116 | */ |
| 117 | public static function getCurrencyPrecision($currency = NULL) { |
| 118 | return 2; |
| 119 | } |
| 120 | |
| 121 | /** |
| 122 | * Subtract currencies using integers instead of floats, to preserve precision |
| 123 | * |
| 124 | * @param string|float $leftOp |
| 125 | * @param string|float $rightOp |
| 126 | * @param string $currency |
| 127 | * |
| 128 | * @return float |
| 129 | * Result of subtracting $rightOp from $leftOp to the precision of $currency |
| 130 | */ |
| 131 | public static function subtractCurrencies($leftOp, $rightOp, $currency) { |
| 132 | if (is_numeric($leftOp) && is_numeric($rightOp)) { |
| 133 | $leftMoney = Money::of($leftOp, $currency, new DefaultContext(), RoundingMode::CEILING); |
| 134 | $rightMoney = Money::of($rightOp, $currency, new DefaultContext(), RoundingMode::CEILING); |
| 135 | return $leftMoney->minus($rightMoney)->getAmount()->toFloat(); |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | /** |
| 140 | * Tests if two currency values are equal, taking into account the currency's |
| 141 | * precision, so that the two values are compared as integers after rounding. |
| 142 | * |
| 143 | * Eg. |
| 144 | * |
| 145 | * 1.231 == 1.232 with a currency precision of 2 decimal points |
| 146 | * 1.234 != 1.236 with a currency precision of 2 decimal points |
| 147 | * 1.300 != 1.200 with a currency precision of 2 decimal points |
| 148 | * |
| 149 | * @param int|float $value1 |
| 150 | * @param int|float $value2 |
| 151 | * @param string $currency |
| 152 | * |
| 153 | * @return bool |
| 154 | */ |
| 155 | public static function equals($value1, $value2, $currency) { |
| 156 | $precision = pow(10, self::getCurrencyPrecision($currency)); |
| 157 | |
| 158 | return (int) round($value1 * $precision) == (int) round($value2 * $precision); |
| 159 | } |
| 160 | |
| 161 | /** |
| 162 | * Format money (or number) for display (just numeric part) according to the current or supplied locale. |
| 163 | * |
| 164 | * Note this should not be used in conjunction with any calls to |
| 165 | * replaceCurrencySeparators as this function already does that. |
| 166 | * |
| 167 | * @param string $amount |
| 168 | * @param string $locale |
| 169 | * @param string $currency |
| 170 | * @param int $numberOfPlaces |
| 171 | * |
| 172 | * @return string |
| 173 | * @throws \Brick\Money\Exception\UnknownCurrencyException |
| 174 | */ |
| 175 | protected static function formatLocaleNumeric(string $amount, $locale = NULL, $currency = NULL, $numberOfPlaces = 2): string { |
| 176 | $money = Money::of($amount, $currency ?? CRM_Core_Config::singleton()->defaultCurrency, new CustomContext($numberOfPlaces), RoundingMode::HALF_UP); |
| 177 | $formatter = new \NumberFormatter($locale ?? CRM_Core_I18n::getLocale(), NumberFormatter::DECIMAL); |
| 178 | $formatter->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, $numberOfPlaces); |
| 179 | return $money->formatWith($formatter); |
| 180 | } |
| 181 | |
| 182 | /** |
| 183 | * Format money for display (just numeric part) according to the current locale with rounding. |
| 184 | * |
| 185 | * At this stage this is conceived as an internal function with the currency wrapper |
| 186 | * functions determining the number of places. |
| 187 | * |
| 188 | * This calls the underlying system function but does not handle currency separators. |
| 189 | * |
| 190 | * It's not totally clear when it changes the $amount value but has historical usage. |
| 191 | * |
| 192 | * @param string|float $amount |
| 193 | * @param int $numberOfPlaces |
| 194 | * |
| 195 | * @return string |
| 196 | */ |
| 197 | public static function formatUSLocaleNumericRounded($amount, int $numberOfPlaces): string { |
| 198 | if (!extension_loaded('intl') || !is_numeric($amount)) { |
| 199 | // @todo - we should not attempt to format non-numeric strings. For now |
| 200 | // these will not fail but will give notices on php 7.4 |
| 201 | if (!is_numeric($amount)) { |
| 202 | CRM_Core_Error::deprecatedWarning('Formatting non-numeric values is no longer supported: ' . htmlspecialchars($amount)); |
| 203 | } |
| 204 | else { |
| 205 | self::missingIntlNotice(); |
| 206 | } |
| 207 | return self::formatNumericByFormat($amount, '%!.' . $numberOfPlaces . 'i'); |
| 208 | } |
| 209 | $money = Money::of($amount, CRM_Core_Config::singleton()->defaultCurrency, new CustomContext($numberOfPlaces), RoundingMode::HALF_UP); |
| 210 | // @todo - we specify en_US here because we don't want this function to do |
| 211 | // currency replacement at the moment because |
| 212 | // formatLocaleNumericRoundedByPrecision is doing it and if it |
| 213 | // is done there then it is swapped back in there.. This is a short term |
| 214 | // fix to allow us to resolve formatLocaleNumericRoundedByPrecision |
| 215 | // and to make the function comments correct - but, we need to reconsider this |
| 216 | // in master as it is probably better to use locale than our currency separator fields. |
| 217 | $formatter = new \NumberFormatter('en_US', NumberFormatter::DECIMAL); |
| 218 | $formatter->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, $numberOfPlaces); |
| 219 | return $money->formatWith($formatter); |
| 220 | } |
| 221 | |
| 222 | /** |
| 223 | * Format money for display (just numeric part) according to the current locale with rounding. |
| 224 | * |
| 225 | * This handles both rounding & replacement of the currency separators for the locale. |
| 226 | * |
| 227 | * @param string $amount |
| 228 | * @param string $currency |
| 229 | * |
| 230 | * @return string |
| 231 | * Formatted amount. |
| 232 | */ |
| 233 | public static function formatLocaleNumericRoundedByCurrency($amount, $currency) { |
| 234 | return self::formatLocaleNumericRoundedByPrecision($amount, self::getCurrencyPrecision($currency)); |
| 235 | } |
| 236 | |
| 237 | /** |
| 238 | * Format money for display (just numeric part) according to the current locale with rounding to the supplied precision. |
| 239 | * |
| 240 | * This handles both rounding & replacement of the currency separators for the locale. |
| 241 | * |
| 242 | * @param string $amount |
| 243 | * @param int $precision |
| 244 | * |
| 245 | * @return string |
| 246 | * Formatted amount. |
| 247 | */ |
| 248 | public static function formatLocaleNumericRoundedByPrecision($amount, $precision) { |
| 249 | $amount = self::formatUSLocaleNumericRounded($amount, $precision); |
| 250 | return self::replaceCurrencySeparators($amount); |
| 251 | } |
| 252 | |
| 253 | /** |
| 254 | * Format money for display with rounding to the supplied precision but without padding. |
| 255 | * |
| 256 | * If the string is shorter than the precision trailing zeros are not added to reach the precision |
| 257 | * beyond the 2 required for normally currency formatting. |
| 258 | * |
| 259 | * This handles both rounding & replacement of the currency separators for the locale. |
| 260 | * |
| 261 | * @param string $amount |
| 262 | * @param int $precision |
| 263 | * |
| 264 | * @return string |
| 265 | * Formatted amount. |
| 266 | */ |
| 267 | public static function formatLocaleNumericRoundedByOptionalPrecision($amount, $precision) { |
| 268 | $decimalPlaces = self::getDecimalPlacesForAmount((string) $amount); |
| 269 | $amount = self::formatUSLocaleNumericRounded($amount, $precision > $decimalPlaces ? $decimalPlaces : $precision); |
| 270 | return self::replaceCurrencySeparators($amount); |
| 271 | } |
| 272 | |
| 273 | /** |
| 274 | * Format money for display (just numeric part) according to the current locale with rounding based on the |
| 275 | * default currency for the site. |
| 276 | * |
| 277 | * @param $amount |
| 278 | * @return mixed |
| 279 | */ |
| 280 | public static function formatLocaleNumericRoundedForDefaultCurrency($amount) { |
| 281 | return self::formatLocaleNumericRoundedByCurrency($amount, self::getCurrencyPrecision(CRM_Core_Config::singleton()->defaultCurrency)); |
| 282 | } |
| 283 | |
| 284 | /** |
| 285 | * Replace currency separators. |
| 286 | * |
| 287 | * @param string $amount |
| 288 | * |
| 289 | * @return string |
| 290 | */ |
| 291 | protected static function replaceCurrencySeparators($amount) { |
| 292 | $config = CRM_Core_Config::singleton(); |
| 293 | $rep = [ |
| 294 | ',' => $config->monetaryThousandSeparator, |
| 295 | '.' => $config->monetaryDecimalPoint, |
| 296 | ]; |
| 297 | return strtr($amount, $rep); |
| 298 | } |
| 299 | |
| 300 | /** |
| 301 | * Format numeric part of currency by the passed in format. |
| 302 | * |
| 303 | * This is envisaged as an internal function, with wrapper functions defining valueFormat |
| 304 | * into easily understood functions / variables and handling separator conversions and |
| 305 | * rounding. |
| 306 | * |
| 307 | * @param string $amount |
| 308 | * @param string $valueFormat |
| 309 | * |
| 310 | * @return string |
| 311 | */ |
| 312 | protected static function formatNumericByFormat($amount, $valueFormat = '%!i') { |
| 313 | // money_format() exists only in certain PHP install (CRM-650) |
| 314 | // setlocale() affects native gettext (CRM-11054, CRM-9976) |
| 315 | if (is_numeric($amount) && function_exists('money_format')) { |
| 316 | $lc = setlocale(LC_MONETARY, 0); |
| 317 | setlocale(LC_MONETARY, 'en_US.utf8', 'en_US', 'en_US.utf8', 'en_US', 'C'); |
| 318 | $amount = money_format($valueFormat, $amount); |
| 319 | setlocale(LC_MONETARY, $lc); |
| 320 | } |
| 321 | return $amount; |
| 322 | } |
| 323 | |
| 324 | /** |
| 325 | * Emits a notice indicating we have fallen back to a less accurate way of formatting money due to missing intl extension |
| 326 | */ |
| 327 | public static function missingIntlNotice() { |
| 328 | CRM_Core_Session::singleton()->setStatus(ts('As this system does not include the PHP intl extension, CiviCRM has fallen back onto a slightly less accurate and deprecated method to format money'), ts('Missing PHP INTL extension')); |
| 329 | } |
| 330 | |
| 331 | /** |
| 332 | * Get the number of characters after the decimal point. |
| 333 | * |
| 334 | * @param string $amount |
| 335 | * |
| 336 | * @return int |
| 337 | */ |
| 338 | protected static function getDecimalPlacesForAmount(string $amount): int { |
| 339 | $decimalPlaces = strlen(substr($amount, strpos($amount, '.') + 1)); |
| 340 | return $decimalPlaces; |
| 341 | } |
| 342 | |
| 343 | } |