[ Index ]

PHP Cross Reference of vtigercrm-6.1.0

title

Body

[close]

/include/fields/ -> CurrencyField.php (source)

   1  <?php
   2  /*+**********************************************************************************
   3   * The contents of this file are subject to the vtiger CRM Public License Version 1.0
   4   * ("License"); You may not use this file except in compliance with the License
   5   * The Original Code is:  vtiger CRM Open Source
   6   * The Initial Developer of the Original Code is vtiger.
   7   * Portions created by vtiger are Copyright (C) vtiger.
   8   * All Rights Reserved.
   9   ************************************************************************************/
  10  
  11  class CurrencyField {
  12  
  13      private $CURRENCY_PATTERN_PLAIN = '123456789';
  14      private $CURRENCY_PATTERN_SINGLE_GROUPING = '123456,789';
  15      private $CURRENCY_PATTERN_THOUSAND_GROUPING = '123,456,789';
  16      private $CURRENCY_PATTERN_MIXED_GROUPING = '12,34,56,789';
  17  
  18      /**
  19       * Currency Format(3,3,3) or (2,2,3)
  20       * @var String
  21       */
  22      var $currencyFormat = '123,456,789';
  23  
  24      /**
  25       * Currency Separator for example (comma, dot, hash)
  26       * @var String
  27       */
  28      var $currencySeparator = ',';
  29  
  30      /**
  31       * Decimal Separator for example (dot, comma, space)
  32       * @var <type>
  33       */
  34      var $decimalSeparator = '.';
  35  
  36      /**
  37       * Number of Decimal Numbers
  38       * @var Integer
  39       */
  40      var $numberOfDecimal = 3;
  41  
  42      /**
  43       * Currency Id
  44       * @var Integer
  45       */
  46      var $currencyId = 1;
  47  
  48      /**
  49       * Currency Symbol
  50       * @var String
  51       */
  52      var $currencySymbol;
  53  
  54      /**
  55       * Currency Symbol Placement
  56       */
  57      var $currencySymbolPlacement;
  58  
  59      /**
  60       * Currency Conversion Rate
  61       * @var Number
  62       */
  63      var $conversionRate = 1;
  64  
  65      /**
  66       * Value to be converted
  67       * @param Number $value
  68       */
  69      var $value = null;
  70  
  71      /**
  72       * Maximum Number Of Currency Decimals
  73       * @var Number
  74       */
  75      var $maxNumberOfDecimals = 5;
  76      /**
  77       * Constructor
  78       * @param Number $value
  79       */
  80      public function  __construct($value) {
  81          $this->value = $value;
  82      }
  83  
  84      /**
  85       * Initializes the User's Currency Details
  86       * @global Users $current_user
  87       * @param Users $user
  88       */
  89      public function initialize($user=null) {
  90          global $current_user,$default_charset;
  91          if(empty($user)) {
  92              $user = $current_user;
  93          }
  94  
  95          if(!empty($user->currency_grouping_pattern)) {
  96              $this->currencyFormat = html_entity_decode($user->currency_grouping_pattern, ENT_QUOTES, $default_charset);
  97              $this->currencySeparator = html_entity_decode($user->currency_grouping_separator, ENT_QUOTES, $default_charset);
  98              $this->decimalSeparator = html_entity_decode($user->currency_decimal_separator, ENT_QUOTES, $default_charset);
  99          }
 100  
 101          if(!empty($user->currency_id)) {
 102              $this->currencyId = $user->currency_id;
 103          } else {
 104              $this->currencyId = self::getDBCurrencyId();
 105          }
 106          $currencyRateAndSymbol = getCurrencySymbolandCRate($this->currencyId);
 107          $this->currencySymbol = $currencyRateAndSymbol['symbol'];
 108          $this->conversionRate = $currencyRateAndSymbol['rate'];
 109          $this->currencySymbolPlacement = $user->currency_symbol_placement;
 110          $this->numberOfDecimal = getCurrencyDecimalPlaces();
 111      }
 112  
 113  	public function getCurrencySymbol() {
 114          return $this->currencySymbol;
 115      }
 116  
 117  
 118      /**
 119       * Returns the Formatted Currency value for the User
 120       * @global Users $current_user
 121       * @param Users $user
 122       * @param Boolean $skipConversion
 123       * @return String - Formatted Currency
 124       */
 125      public static function convertToUserFormat($value, $user=null, $skipConversion=false, $skipFormatting=false) {
 126          // To support negative values
 127          $negative = false;
 128          if(stripos($value, '-') === 0) {
 129              $negative = true;
 130              $value = substr($value, 1);
 131          }
 132          $self = new self($value);
 133          $value = $self->getDisplayValue($user,$skipConversion,$skipFormatting);
 134          return ($negative) ? '-'.$value : $value;
 135      }
 136  
 137      /**
 138       * Function that converts the Number into Users Currency
 139       * @param Users $user
 140       * @param Boolean $skipConversion
 141       * @return Formatted Currency
 142       */
 143      public function getDisplayValue($user=null, $skipConversion=false, $skipFormatting=false) {
 144          global $current_user;
 145          if(empty($user)) {
 146              $user = $current_user;
 147          }
 148          $this->initialize($user);
 149  
 150          $value = $this->value;
 151          if($skipConversion == false) {
 152              $value = self::convertFromDollar($value,$this->conversionRate);
 153          }
 154  
 155          if($skipFormatting == false) {
 156              $value = $this->_formatCurrencyValue($value);
 157          }
 158          return $this->currencyDecimalFormat($value, $user);
 159      }
 160  
 161      /**
 162       * Function that converts the Number into Users Currency along with currency symbol
 163       * @param Users $user
 164       * @param Boolean $skipConversion
 165       * @return Formatted Currency
 166       */
 167      public function getDisplayValueWithSymbol($user=null, $skipConversion=false) {
 168          $formattedValue = $this->getDisplayValue($user, $skipConversion);
 169          return self::appendCurrencySymbol($formattedValue, $this->currencySymbol, $this->currencySymbolPlacement);
 170      }
 171  
 172      /**
 173       * Static Function that appends the currency symbol to a given currency value, based on the preferred symbol placement
 174       * @param Number $currencyValue
 175       * @param String $currencySymbol
 176       * @param String $currencySymbolPlacement
 177       * @return Currency value appended with the currency symbol
 178       */
 179  	public static function appendCurrencySymbol($currencyValue, $currencySymbol, $currencySymbolPlacement='') {
 180          global $current_user;
 181          if(empty($currencySymbolPlacement)) {
 182              $currencySymbolPlacement = $current_user->currency_symbol_placement;
 183          }
 184  
 185          switch($currencySymbolPlacement) {
 186              case '1.0$' :    $returnValue = $currencyValue . $currencySymbol;
 187                              break;
 188              case '$1.0'    :
 189              default        :    $returnValue = $currencySymbol . $currencyValue;
 190          }
 191          return $returnValue;
 192      }
 193  
 194      /**
 195       * Function that formats the Number based on the User configured Pattern, Currency separator and Decimal separator
 196       * @param Number $value
 197       * @return Formatted Currency
 198       */
 199  	private function _formatCurrencyValue($value) {
 200  
 201          $currencyPattern = $this->currencyFormat;
 202          $currencySeparator = $this->currencySeparator;
 203          $decimalSeparator  = $this->decimalSeparator;
 204          $currencyDecimalPlaces = $this->numberOfDecimal;
 205          $value = number_format($value, $currencyDecimalPlaces,'.','');
 206          if(empty($currencySeparator)) $currencySeparator = ' ';
 207          if(empty($decimalSeparator)) $decimalSeparator = ' ';
 208  
 209          if($currencyPattern == $this->CURRENCY_PATTERN_PLAIN) {
 210              // Replace '.' with Decimal Separator
 211              $number = str_replace('.', $decimalSeparator, $value);
 212              return $number;
 213          }
 214          if($currencyPattern == $this->CURRENCY_PATTERN_SINGLE_GROUPING) {
 215              // Separate the numeric and decimal parts
 216              $numericParts = explode('.', $value);
 217              $wholeNumber = $numericParts[0];
 218              // First part of the number which remains intact
 219              if(strlen($wholeNumber) > 3) {
 220                  $wholeNumberFirstPart = substr($wholeNumber,0,strlen($wholeNumber)-3);
 221              }
 222              // Second Part of the number (last 3 digits) which should be separated from the First part using Currency Separator
 223              $wholeNumberLastPart = substr($wholeNumber,-3);
 224              // Re-create the whole number with user's configured currency separator
 225              if(!empty($wholeNumberFirstPart)) {
 226                  $numericParts[0] = $wholeNumberFirstPart.$currencySeparator.$wholeNumberLastPart;
 227              } else {
 228                  $numericParts[0] = $wholeNumberLastPart;
 229              }
 230              // Re-create the currency value combining the whole number and the decimal part using Decimal separator
 231              $number = implode($decimalSeparator, $numericParts);
 232              return $number;
 233          }
 234          if($currencyPattern == $this->CURRENCY_PATTERN_THOUSAND_GROUPING) {
 235              $negativeNumber = false;
 236              if($value < 0) {
 237                  $negativeNumber = true;
 238              }
 239              
 240              // Separate the numeric and decimal parts
 241              $numericParts = explode('.', $value);
 242              $wholeNumber = $numericParts[0];
 243              
 244              //check the whole number is negative value, then separate the negative symbol from whole number
 245              if($wholeNumber < 0 || $negativeNumber) {
 246                  $negativeNumber = true;
 247                  $positiveValues = explode('-', $wholeNumber);
 248                  $wholeNumber = $positiveValues[1];
 249              }
 250              
 251              // Pad the rest of the length in the number string with Leading 0, to get it to the multiples of 3
 252              $numberLength = strlen($wholeNumber);
 253              // First grouping digits length
 254              $OddGroupLength = $numberLength%3;
 255              $gapsToBeFilled = 0;
 256              if($OddGroupLength > 0) $gapsToBeFilled = 3 - $OddGroupLength;
 257              $wholeNumber = str_pad($wholeNumber, $numberLength+$gapsToBeFilled, '0', STR_PAD_LEFT);
 258              // Split the whole number into chunks of 3 digits
 259              $wholeNumberParts = str_split($wholeNumber,3);
 260              // Re-create the whole number with user's configured currency separator
 261              $numericParts[0] = $wholeNumber = implode($currencySeparator, $wholeNumberParts);
 262              if($wholeNumber != 0) {
 263                  $numericParts[0] = ltrim($wholeNumber, '0');
 264              } else {
 265                  $numericParts[0] = 0;
 266              }
 267              
 268              //if its negative number, append-back the negative symbol to the whole number part
 269              if($negativeNumber) {
 270                  $numericParts[0] = '-'.$numericParts[0];
 271              }
 272              
 273              // Re-create the currency value combining the whole number and the decimal part using Decimal separator
 274              $number = implode($decimalSeparator, $numericParts);
 275              return $number;
 276          }
 277          if($currencyPattern == $this->CURRENCY_PATTERN_MIXED_GROUPING) {
 278              $negativeNumber = false;
 279              if($value < 0) {
 280                  $negativeNumber = true;
 281              }
 282              
 283              // Separate the numeric and decimal parts
 284              $numericParts = explode('.', $value);
 285              $wholeNumber = $numericParts[0];
 286              
 287              //check the whole number is negative value, then separate the negative symbol from whole number
 288              if($wholeNumber < 0 || $negativeNumber) {
 289                  $negativeNumber = true;
 290                  $positiveValues = explode('-', $wholeNumber);
 291                  $wholeNumber = $positiveValues[1];
 292              }
 293              
 294              // First part of the number which needs separate division
 295              if(strlen($wholeNumber) > 3) {
 296                  $wholeNumberFirstPart = substr($wholeNumber,0,strlen($wholeNumber)-3);
 297              }
 298              // Second Part of the number (last 3 digits) which should be separated from the First part using Currency Separator
 299              $wholeNumberLastPart = substr($wholeNumber,-3);
 300              if(!empty($wholeNumberFirstPart)) {
 301                  // Pad the rest of the length in the number string with Leading 0, to get it to the multiples of 2
 302                  $numberLength = strlen($wholeNumberFirstPart);
 303                  // First grouping digits length
 304                  $OddGroupLength = $numberLength%2;
 305                  $gapsToBeFilled = 0;
 306                  if($OddGroupLength > 0) $gapsToBeFilled = 2 - $OddGroupLength;
 307                  $wholeNumberFirstPart = str_pad($wholeNumberFirstPart, $numberLength+$gapsToBeFilled, '0', STR_PAD_LEFT);
 308                  // Split the first part of tne number into chunks of 2 digits
 309                  $wholeNumberFirstPartElements = str_split($wholeNumberFirstPart,2);
 310                  $wholeNumberFirstPart = ltrim(implode($currencySeparator, $wholeNumberFirstPartElements), '0');
 311                  $wholeNumberFirstPart = implode($currencySeparator, $wholeNumberFirstPartElements);
 312                  if($wholeNumberFirstPart != 0) {
 313                      $wholeNumberFirstPart = ltrim($wholeNumberFirstPart, '0');
 314                  } else {
 315                      $wholeNumberFirstPart = 0;
 316                  }
 317                  // Re-create the whole number with user's configured currency separator
 318                  $numericParts[0] = $wholeNumberFirstPart.$currencySeparator.$wholeNumberLastPart;
 319              } else {
 320                  $numericParts[0] = $wholeNumberLastPart;
 321              }
 322              
 323              //if its negative number, append-back the negative symbol to the whole number part
 324              if($negativeNumber) {
 325                  $numericParts[0] = '-'.$numericParts[0];
 326              }
 327              
 328              // Re-create the currency value combining the whole number and the decimal part using Decimal separator
 329              $number = implode($decimalSeparator, $numericParts);
 330              return $number;
 331          }
 332          return $number;
 333      }
 334  
 335      /**
 336       * Returns the Currency value without formatting for DB Operations
 337       * @global Users $current_user
 338       * @param Users $user
 339       * @param Boolean $skipConversion
 340       * @return Number
 341       */
 342      public function getDBInsertedValue($user=null, $skipConversion=false) {
 343          global $current_user;
 344          if(empty($user)) {
 345              $user = $current_user;
 346          }
 347  
 348          $this->initialize($user);
 349  
 350          $value = $this->value;
 351  
 352          $currencySeparator = $this->currencySeparator;
 353          $decimalSeparator  = $this->decimalSeparator;
 354          if(empty($currencySeparator)) $currencySeparator = ' ';
 355          if(empty($decimalSeparator)) $decimalSeparator = ' ';
 356          $value = str_replace("$currencySeparator", "", $value);
 357          $value = str_replace("$decimalSeparator", ".", $value);
 358  
 359          if($skipConversion == false) {
 360              $value = self::convertToDollar($value,$this->conversionRate);
 361          }
 362          //$value = round($value, $this->maxNumberOfDecimals);
 363  
 364          return $value;
 365      }
 366  
 367      /**
 368       * Returns the Currency value without formatting for DB Operations
 369       * @param Number $value
 370       * @param Users $user
 371       * @param Boolean $skipConversion
 372       * @return Number
 373       */
 374  	public static function convertToDBFormat($value, $user=null, $skipConversion=false) {
 375          $self = new self($value);
 376          return $self->getDBInsertedValue($user, $skipConversion);
 377      }
 378  
 379      /**
 380       * Function to get the default CRM currency
 381       * @return Integer Default system currency id
 382       */
 383  	public static function getDBCurrencyId() {
 384          $adb = PearDatabase::getInstance();
 385  
 386          $result = $adb->pquery('SELECT id FROM vtiger_currency_info WHERE defaultid < 0', array());
 387          $noOfRows = $adb->num_rows($result);
 388          if($noOfRows > 0) {
 389              return $adb->query_result($result, 0, 'id');
 390          }
 391          return null;
 392      }
 393      
 394  	public static function convertToDollar($amount, $conversionRate) {
 395          if ($conversionRate == 0) return 0;
 396          return $amount / $conversionRate;
 397      }
 398      
 399  	public static function convertFromDollar($amount, $conversionRate) {
 400          $currencyField = new CurrencyField($amount);
 401          return round($amount * $conversionRate, $currencyField->maxNumberOfDecimals);
 402      }
 403      
 404      /** This function returns the amount converted from master currency.
 405       * param $amount - amount to be converted.
 406       * param $crate - conversion rate.
 407       */
 408  	public static function convertFromMasterCurrency($amount, $conversionRate) {
 409          return $amount * $conversionRate;
 410      }
 411      
 412  	function currencyDecimalFormat($value, $user = null){
 413          global $current_user;
 414          if (!$user) {
 415              $user = $current_user;
 416          }
 417          if($user->truncate_trailing_zeros == true) {
 418              if(strpos($value, $user->currency_decimal_separator) != 0){
 419                  /**
 420                   * We should trim extra zero's if only the value had decimal separator(Ex :- 1600.00)
 421                   * else it'll change orginal value
 422                   */
 423                  $value = rtrim($value, '0');
 424              }
 425              $fld_value = explode(decode_html($user->currency_decimal_separator), $value);
 426              if(strlen($fld_value[1]) <= 1){
 427                  if(strlen($fld_value[1]) == 1)
 428                      return $value = $fld_value[0].$user->currency_decimal_separator.$fld_value[1].'0';
 429                  else
 430                      return $value = $fld_value[0].$user->currency_decimal_separator.'00';
 431              }else{
 432                  return preg_replace("/(?<=\\.[0-9])[0]+\$/","",$value);
 433              }
 434          }else{
 435              return $value;
 436          }
 437      }
 438  }
 439  ?>


Generated: Fri Nov 28 20:08:37 2014 Cross-referenced by PHPXref 0.7.1