PageRenderTime 52ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Zend/Locale/Format.php

https://gitlab.com/blingbang2016/shop
PHP | 1194 lines | 879 code | 98 blank | 217 comment | 251 complexity | a23dfa06d33afc8c8f5a3840d3d20999 MD5 | raw file
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Locale
  17. * @subpackage Format
  18. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @version $Id$
  20. * @license http://framework.zend.com/license/new-bsd New BSD License
  21. */
  22. /**
  23. * include needed classes
  24. */
  25. #require_once 'Zend/Locale/Data.php';
  26. /**
  27. * @category Zend
  28. * @package Zend_Locale
  29. * @subpackage Format
  30. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  31. * @license http://framework.zend.com/license/new-bsd New BSD License
  32. */
  33. class Zend_Locale_Format
  34. {
  35. const STANDARD = 'auto';
  36. private static $_options = array('date_format' => null,
  37. 'number_format' => null,
  38. 'format_type' => 'iso',
  39. 'fix_date' => false,
  40. 'locale' => null,
  41. 'cache' => null,
  42. 'disableCache' => null,
  43. 'precision' => null);
  44. /**
  45. * Sets class wide options, if no option was given, the actual set options will be returned
  46. * The 'precision' option of a value is used to truncate or stretch extra digits. -1 means not to touch the extra digits.
  47. * The 'locale' option helps when parsing numbers and dates using separators and month names.
  48. * The date format 'format_type' option selects between CLDR/ISO date format specifier tokens and PHP's date() tokens.
  49. * The 'fix_date' option enables or disables heuristics that attempt to correct invalid dates.
  50. * The 'number_format' option can be used to specify a default number format string
  51. * The 'date_format' option can be used to specify a default date format string, but beware of using getDate(),
  52. * checkDateFormat() and getTime() after using setOptions() with a 'format'. To use these four methods
  53. * with the default date format for a locale, use array('date_format' => null, 'locale' => $locale) for their options.
  54. *
  55. * @param array $options Array of options, keyed by option name: format_type = 'iso' | 'php', fix_date = true | false,
  56. * locale = Zend_Locale | locale string, precision = whole number between -1 and 30
  57. * @throws Zend_Locale_Exception
  58. * @return array if no option was given
  59. */
  60. public static function setOptions(array $options = array())
  61. {
  62. self::$_options = self::_checkOptions($options) + self::$_options;
  63. return self::$_options;
  64. }
  65. /**
  66. * Internal function for checking the options array of proper input values
  67. * See {@link setOptions()} for details.
  68. *
  69. * @param array $options Array of options, keyed by option name: format_type = 'iso' | 'php', fix_date = true | false,
  70. * locale = Zend_Locale | locale string, precision = whole number between -1 and 30
  71. * @throws Zend_Locale_Exception
  72. * @return array if no option was given
  73. */
  74. private static function _checkOptions(array $options = array())
  75. {
  76. if (count($options) == 0) {
  77. return self::$_options;
  78. }
  79. foreach ($options as $name => $value) {
  80. $name = strtolower($name);
  81. if ($name !== 'locale') {
  82. if (gettype($value) === 'string') {
  83. $value = strtolower($value);
  84. }
  85. }
  86. switch($name) {
  87. case 'number_format' :
  88. if ($value == Zend_Locale_Format::STANDARD) {
  89. $locale = self::$_options['locale'];
  90. if (isset($options['locale'])) {
  91. $locale = $options['locale'];
  92. }
  93. $options['number_format'] = Zend_Locale_Data::getContent($locale, 'decimalnumber');
  94. } else if ((gettype($value) !== 'string') and ($value !== NULL)) {
  95. #require_once 'Zend/Locale/Exception.php';
  96. $stringValue = (string)(is_array($value) ? implode(' ', $value) : $value);
  97. throw new Zend_Locale_Exception("Unknown number format type '" . gettype($value) . "'. "
  98. . "Format '$stringValue' must be a valid number format string.");
  99. }
  100. break;
  101. case 'date_format' :
  102. if ($value == Zend_Locale_Format::STANDARD) {
  103. $locale = self::$_options['locale'];
  104. if (isset($options['locale'])) {
  105. $locale = $options['locale'];
  106. }
  107. $options['date_format'] = Zend_Locale_Format::getDateFormat($locale);
  108. } else if ((gettype($value) !== 'string') and ($value !== NULL)) {
  109. #require_once 'Zend/Locale/Exception.php';
  110. $stringValue = (string)(is_array($value) ? implode(' ', $value) : $value);
  111. throw new Zend_Locale_Exception("Unknown dateformat type '" . gettype($value) . "'. "
  112. . "Format '$stringValue' must be a valid ISO or PHP date format string.");
  113. } else {
  114. if (((isset($options['format_type']) === true) and ($options['format_type'] == 'php')) or
  115. ((isset($options['format_type']) === false) and (self::$_options['format_type'] == 'php'))) {
  116. $options['date_format'] = Zend_Locale_Format::convertPhpToIsoFormat($value);
  117. }
  118. }
  119. break;
  120. case 'format_type' :
  121. if (($value != 'php') && ($value != 'iso')) {
  122. #require_once 'Zend/Locale/Exception.php';
  123. throw new Zend_Locale_Exception("Unknown date format type '$value'. Only 'iso' and 'php'"
  124. . " are supported.");
  125. }
  126. break;
  127. case 'fix_date' :
  128. if (($value !== true) && ($value !== false)) {
  129. #require_once 'Zend/Locale/Exception.php';
  130. throw new Zend_Locale_Exception("Enabling correction of dates must be either true or false"
  131. . "(fix_date='$value').");
  132. }
  133. break;
  134. case 'locale' :
  135. $options['locale'] = Zend_Locale::findLocale($value);
  136. break;
  137. case 'cache' :
  138. if ($value instanceof Zend_Cache_Core) {
  139. Zend_Locale_Data::setCache($value);
  140. }
  141. break;
  142. case 'disablecache' :
  143. if (null !== $value) {
  144. Zend_Locale_Data::disableCache($value);
  145. }
  146. break;
  147. case 'precision' :
  148. if ($value === NULL) {
  149. $value = -1;
  150. }
  151. if (($value < -1) || ($value > 30)) {
  152. #require_once 'Zend/Locale/Exception.php';
  153. throw new Zend_Locale_Exception("'$value' precision is not a whole number less than 30.");
  154. }
  155. break;
  156. default:
  157. #require_once 'Zend/Locale/Exception.php';
  158. throw new Zend_Locale_Exception("Unknown option: '$name' = '$value'");
  159. break;
  160. }
  161. }
  162. return $options;
  163. }
  164. /**
  165. * Changes the numbers/digits within a given string from one script to another
  166. * 'Decimal' representated the stardard numbers 0-9, if a script does not exist
  167. * an exception will be thrown.
  168. *
  169. * Examples for conversion from Arabic to Latin numerals:
  170. * convertNumerals('١١٠ Tests', 'Arab'); -> returns '100 Tests'
  171. * Example for conversion from Latin to Arabic numerals:
  172. * convertNumerals('100 Tests', 'Latn', 'Arab'); -> returns '١١٠ Tests'
  173. *
  174. * @param string $input String to convert
  175. * @param string $from Script to parse, see {@link Zend_Locale::getScriptList()} for details.
  176. * @param string $to OPTIONAL Script to convert to
  177. * @return string Returns the converted input
  178. * @throws Zend_Locale_Exception
  179. */
  180. public static function convertNumerals($input, $from, $to = null)
  181. {
  182. if (!self::_getUniCodeSupport()) {
  183. trigger_error("Sorry, your PCRE extension does not support UTF8 which is needed for the I18N core", E_USER_NOTICE);
  184. }
  185. $from = strtolower($from);
  186. $source = Zend_Locale_Data::getContent('en', 'numberingsystem', $from);
  187. if (empty($source)) {
  188. #require_once 'Zend/Locale/Exception.php';
  189. throw new Zend_Locale_Exception("Unknown script '$from'. Use 'Latn' for digits 0,1,2,3,4,5,6,7,8,9.");
  190. }
  191. if ($to !== null) {
  192. $to = strtolower($to);
  193. $target = Zend_Locale_Data::getContent('en', 'numberingsystem', $to);
  194. if (empty($target)) {
  195. #require_once 'Zend/Locale/Exception.php';
  196. throw new Zend_Locale_Exception("Unknown script '$to'. Use 'Latn' for digits 0,1,2,3,4,5,6,7,8,9.");
  197. }
  198. } else {
  199. $target = '0123456789';
  200. }
  201. for ($x = 0; $x < 10; ++$x) {
  202. $asource[$x] = "/" . iconv_substr($source, $x, 1, 'UTF-8') . "/u";
  203. $atarget[$x] = iconv_substr($target, $x, 1, 'UTF-8');
  204. }
  205. return preg_replace($asource, $atarget, $input);
  206. }
  207. /**
  208. * Returns the normalized number from a localized one
  209. * Parsing depends on given locale (grouping and decimal)
  210. *
  211. * Examples for input:
  212. * '2345.4356,1234' = 23455456.1234
  213. * '+23,3452.123' = 233452.123
  214. * '12343 ' = 12343
  215. * '-9456' = -9456
  216. * '0' = 0
  217. *
  218. * @param string $input Input string to parse for numbers
  219. * @param array $options Options: locale, precision. See {@link setOptions()} for details.
  220. * @return string Returns the extracted number
  221. * @throws Zend_Locale_Exception
  222. */
  223. public static function getNumber($input, array $options = array())
  224. {
  225. $options = self::_checkOptions($options) + self::$_options;
  226. if (!is_string($input)) {
  227. return $input;
  228. }
  229. if (!self::isNumber($input, $options)) {
  230. #require_once 'Zend/Locale/Exception.php';
  231. throw new Zend_Locale_Exception('No localized value in ' . $input . ' found, or the given number does not match the localized format');
  232. }
  233. // Get correct signs for this locale
  234. $symbols = Zend_Locale_Data::getList($options['locale'],'symbols');
  235. // Change locale input to be default number
  236. if (($input[0] == $symbols['minus']) && ('-' != $input[0])) {
  237. $input = '-' . substr($input, 1);
  238. }
  239. $input = str_replace($symbols['group'],'', $input);
  240. if (strpos($input, $symbols['decimal']) !== false) {
  241. if ($symbols['decimal'] != '.') {
  242. $input = str_replace($symbols['decimal'], ".", $input);
  243. }
  244. $pre = substr($input, strpos($input, '.') + 1);
  245. if ($options['precision'] === null) {
  246. $options['precision'] = strlen($pre);
  247. }
  248. if (strlen($pre) >= $options['precision']) {
  249. $input = substr($input, 0, strlen($input) - strlen($pre) + $options['precision']);
  250. }
  251. if (($options['precision'] == 0) && ($input[strlen($input) - 1] == '.')) {
  252. $input = substr($input, 0, -1);
  253. }
  254. }
  255. return $input;
  256. }
  257. /**
  258. * Returns a locale formatted number depending on the given options.
  259. * The seperation and fraction sign is used from the set locale.
  260. * ##0.# -> 12345.12345 -> 12345.12345
  261. * ##0.00 -> 12345.12345 -> 12345.12
  262. * ##,##0.00 -> 12345.12345 -> 12,345.12
  263. *
  264. * @param string $value Localized number string
  265. * @param array $options Options: number_format, locale, precision. See {@link setOptions()} for details.
  266. * @return string locale formatted number
  267. * @throws Zend_Locale_Exception
  268. */
  269. public static function toNumber($value, array $options = array())
  270. {
  271. // load class within method for speed
  272. #require_once 'Zend/Locale/Math.php';
  273. $value = Zend_Locale_Math::floatalize($value);
  274. $value = Zend_Locale_Math::normalize($value);
  275. $options = self::_checkOptions($options) + self::$_options;
  276. $options['locale'] = (string) $options['locale'];
  277. // Get correct signs for this locale
  278. $symbols = Zend_Locale_Data::getList($options['locale'], 'symbols');
  279. $oenc = self::_getEncoding();
  280. self::_setEncoding('UTF-8');
  281. // Get format
  282. $format = $options['number_format'];
  283. if ($format === null) {
  284. $format = Zend_Locale_Data::getContent($options['locale'], 'decimalnumber');
  285. $format = self::_seperateFormat($format, $value, $options['precision']);
  286. if ($options['precision'] !== null) {
  287. $value = Zend_Locale_Math::normalize(Zend_Locale_Math::round($value, $options['precision']));
  288. }
  289. } else {
  290. // seperate negative format pattern when available
  291. $format = self::_seperateFormat($format, $value, $options['precision']);
  292. if (strpos($format, '.')) {
  293. if (is_numeric($options['precision'])) {
  294. $value = Zend_Locale_Math::round($value, $options['precision']);
  295. } else {
  296. if (substr($format, iconv_strpos($format, '.') + 1, 3) == '###') {
  297. $options['precision'] = null;
  298. } else {
  299. $options['precision'] = iconv_strlen(iconv_substr($format, iconv_strpos($format, '.') + 1,
  300. iconv_strrpos($format, '0') - iconv_strpos($format, '.')));
  301. $format = iconv_substr($format, 0, iconv_strpos($format, '.') + 1) . '###'
  302. . iconv_substr($format, iconv_strrpos($format, '0') + 1);
  303. }
  304. }
  305. } else {
  306. $value = Zend_Locale_Math::round($value, 0);
  307. $options['precision'] = 0;
  308. }
  309. $value = Zend_Locale_Math::normalize($value);
  310. }
  311. if (iconv_strpos($format, '0') === false) {
  312. self::_setEncoding($oenc);
  313. #require_once 'Zend/Locale/Exception.php';
  314. throw new Zend_Locale_Exception('Wrong format... missing 0');
  315. }
  316. // get number parts
  317. $pos = iconv_strpos($value, '.');
  318. if ($pos !== false) {
  319. if ($options['precision'] === null) {
  320. $precstr = iconv_substr($value, $pos + 1);
  321. } else {
  322. $precstr = iconv_substr($value, $pos + 1, $options['precision']);
  323. if (iconv_strlen($precstr) < $options['precision']) {
  324. $precstr = $precstr . str_pad("0", ($options['precision'] - iconv_strlen($precstr)), "0");
  325. }
  326. }
  327. } else {
  328. if ($options['precision'] > 0) {
  329. $precstr = str_pad("0", ($options['precision']), "0");
  330. }
  331. }
  332. if ($options['precision'] === null) {
  333. if (isset($precstr)) {
  334. $options['precision'] = iconv_strlen($precstr);
  335. } else {
  336. $options['precision'] = 0;
  337. }
  338. }
  339. // get fraction and format lengths
  340. if (strpos($value, '.') !== false) {
  341. $number = substr((string) $value, 0, strpos($value, '.'));
  342. } else {
  343. $number = $value;
  344. }
  345. $prec = call_user_func(Zend_Locale_Math::$sub, $value, $number, $options['precision']);
  346. $prec = Zend_Locale_Math::floatalize($prec);
  347. $prec = Zend_Locale_Math::normalize($prec);
  348. if (iconv_strpos($prec, '-') !== false) {
  349. $prec = iconv_substr($prec, 1);
  350. }
  351. if (($prec == 0) and ($options['precision'] > 0)) {
  352. $prec = "0.0";
  353. }
  354. if (($options['precision'] + 2) > iconv_strlen($prec)) {
  355. $prec = str_pad((string) $prec, $options['precision'] + 2, "0", STR_PAD_RIGHT);
  356. }
  357. if (iconv_strpos($number, '-') !== false) {
  358. $number = iconv_substr($number, 1);
  359. }
  360. $group = iconv_strrpos($format, ',');
  361. $group2 = iconv_strpos ($format, ',');
  362. $point = iconv_strpos ($format, '0');
  363. // Add fraction
  364. $rest = "";
  365. if (iconv_strpos($format, '.')) {
  366. $rest = iconv_substr($format, iconv_strpos($format, '.') + 1);
  367. $length = iconv_strlen($rest);
  368. for($x = 0; $x < $length; ++$x) {
  369. if (($rest[0] == '0') || ($rest[0] == '#')) {
  370. $rest = iconv_substr($rest, 1);
  371. }
  372. }
  373. $format = iconv_substr($format, 0, iconv_strlen($format) - iconv_strlen($rest));
  374. }
  375. if ($options['precision'] == '0') {
  376. if (iconv_strrpos($format, '-') != 0) {
  377. $format = iconv_substr($format, 0, $point)
  378. . iconv_substr($format, iconv_strrpos($format, '#') + 2);
  379. } else {
  380. $format = iconv_substr($format, 0, $point);
  381. }
  382. } else {
  383. $format = iconv_substr($format, 0, $point) . $symbols['decimal']
  384. . iconv_substr($prec, 2);
  385. }
  386. $format .= $rest;
  387. // Add seperation
  388. if ($group == 0) {
  389. // no seperation
  390. $format = $number . iconv_substr($format, $point);
  391. } else if ($group == $group2) {
  392. // only 1 seperation
  393. $seperation = ($point - $group);
  394. for ($x = iconv_strlen($number); $x > $seperation; $x -= $seperation) {
  395. if (iconv_substr($number, 0, $x - $seperation) !== "") {
  396. $number = iconv_substr($number, 0, $x - $seperation) . $symbols['group']
  397. . iconv_substr($number, $x - $seperation);
  398. }
  399. }
  400. $format = iconv_substr($format, 0, iconv_strpos($format, '#')) . $number . iconv_substr($format, $point);
  401. } else {
  402. // 2 seperations
  403. if (iconv_strlen($number) > ($point - $group)) {
  404. $seperation = ($point - $group);
  405. $number = iconv_substr($number, 0, iconv_strlen($number) - $seperation) . $symbols['group']
  406. . iconv_substr($number, iconv_strlen($number) - $seperation);
  407. if ((iconv_strlen($number) - 1) > ($point - $group + 1)) {
  408. $seperation2 = ($group - $group2 - 1);
  409. for ($x = iconv_strlen($number) - $seperation2 - 2; $x > $seperation2; $x -= $seperation2) {
  410. $number = iconv_substr($number, 0, $x - $seperation2) . $symbols['group']
  411. . iconv_substr($number, $x - $seperation2);
  412. }
  413. }
  414. }
  415. $format = iconv_substr($format, 0, iconv_strpos($format, '#')) . $number . iconv_substr($format, $point);
  416. }
  417. // set negative sign
  418. if (call_user_func(Zend_Locale_Math::$comp, $value, 0, $options['precision']) < 0) {
  419. if (iconv_strpos($format, '-') === false) {
  420. $format = $symbols['minus'] . $format;
  421. } else {
  422. $format = str_replace('-', $symbols['minus'], $format);
  423. }
  424. }
  425. self::_setEncoding($oenc);
  426. return (string) $format;
  427. }
  428. /**
  429. * @param string $format
  430. * @param string $value
  431. * @param int $precision
  432. * @return string
  433. */
  434. private static function _seperateFormat($format, $value, $precision)
  435. {
  436. if (iconv_strpos($format, ';') !== false) {
  437. if (call_user_func(Zend_Locale_Math::$comp, $value, 0, $precision) < 0) {
  438. $tmpformat = iconv_substr($format, iconv_strpos($format, ';') + 1);
  439. if ($tmpformat[0] == '(') {
  440. $format = iconv_substr($format, 0, iconv_strpos($format, ';'));
  441. } else {
  442. $format = $tmpformat;
  443. }
  444. } else {
  445. $format = iconv_substr($format, 0, iconv_strpos($format, ';'));
  446. }
  447. }
  448. return $format;
  449. }
  450. /**
  451. * Checks if the input contains a normalized or localized number
  452. *
  453. * @param string $input Localized number string
  454. * @param array $options Options: locale. See {@link setOptions()} for details.
  455. * @return boolean Returns true if a number was found
  456. */
  457. public static function isNumber($input, array $options = array())
  458. {
  459. if (!self::_getUniCodeSupport()) {
  460. trigger_error("Sorry, your PCRE extension does not support UTF8 which is needed for the I18N core", E_USER_NOTICE);
  461. }
  462. $options = self::_checkOptions($options) + self::$_options;
  463. // Get correct signs for this locale
  464. $symbols = Zend_Locale_Data::getList($options['locale'],'symbols');
  465. $regexs = Zend_Locale_Format::_getRegexForType('decimalnumber', $options);
  466. $regexs = array_merge($regexs, Zend_Locale_Format::_getRegexForType('scientificnumber', $options));
  467. if (!empty($input) && ($input[0] == $symbols['decimal'])) {
  468. $input = 0 . $input;
  469. }
  470. foreach ($regexs as $regex) {
  471. preg_match($regex, $input, $found);
  472. if (isset($found[0])) {
  473. return true;
  474. }
  475. }
  476. return false;
  477. }
  478. /**
  479. * Internal method to convert cldr number syntax into regex
  480. *
  481. * @param string $type
  482. * @param array $options Options: locale. See {@link setOptions()} for details.
  483. * @return string
  484. * @throws Zend_Locale_Exception
  485. */
  486. private static function _getRegexForType($type, $options)
  487. {
  488. $decimal = Zend_Locale_Data::getContent($options['locale'], $type);
  489. $decimal = preg_replace('/[^#0,;\.\-Ee]/u', '',$decimal);
  490. $patterns = explode(';', $decimal);
  491. if (count($patterns) == 1) {
  492. $patterns[1] = '-' . $patterns[0];
  493. }
  494. $symbols = Zend_Locale_Data::getList($options['locale'],'symbols');
  495. foreach($patterns as $pkey => $pattern) {
  496. $regex[$pkey] = '/^';
  497. $rest = 0;
  498. $end = null;
  499. if (strpos($pattern, '.') !== false) {
  500. $end = substr($pattern, strpos($pattern, '.') + 1);
  501. $pattern = substr($pattern, 0, -strlen($end) - 1);
  502. }
  503. if (strpos($pattern, ',') !== false) {
  504. $parts = explode(',', $pattern);
  505. $count = count($parts);
  506. foreach($parts as $key => $part) {
  507. switch ($part) {
  508. case '#':
  509. case '-#':
  510. if ($part[0] == '-') {
  511. $regex[$pkey] .= '[' . $symbols['minus'] . '-]{0,1}';
  512. } else {
  513. $regex[$pkey] .= '[' . $symbols['plus'] . '+]{0,1}';
  514. }
  515. if (($parts[$key + 1]) == '##0') {
  516. $regex[$pkey] .= '[0-9]{1,3}';
  517. } else if (($parts[$key + 1]) == '##') {
  518. $regex[$pkey] .= '[0-9]{1,2}';
  519. } else {
  520. throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 1):"' . $pattern . '"');
  521. }
  522. break;
  523. case '##':
  524. if ($parts[$key + 1] == '##0') {
  525. $regex[$pkey] .= '(\\' . $symbols['group'] . '{0,1}[0-9]{2})*';
  526. } else {
  527. throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 2):"' . $pattern . '"');
  528. }
  529. break;
  530. case '##0':
  531. if ($parts[$key - 1] == '##') {
  532. $regex[$pkey] .= '[0-9]';
  533. } else if (($parts[$key - 1] == '#') || ($parts[$key - 1] == '-#')) {
  534. $regex[$pkey] .= '(\\' . $symbols['group'] . '{0,1}[0-9]{3})*';
  535. } else {
  536. throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 3):"' . $pattern . '"');
  537. }
  538. break;
  539. case '#0':
  540. if ($key == 0) {
  541. $regex[$pkey] .= '[0-9]*';
  542. } else {
  543. throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 4):"' . $pattern . '"');
  544. }
  545. break;
  546. }
  547. }
  548. }
  549. if (strpos($pattern, 'E') !== false) {
  550. if (($pattern == '#E0') || ($pattern == '#E00')) {
  551. $regex[$pkey] .= '[' . $symbols['plus']. '+]{0,1}[0-9]{1,}(\\' . $symbols['decimal'] . '[0-9]{1,})*[eE][' . $symbols['plus']. '+]{0,1}[0-9]{1,}';
  552. } else if (($pattern == '-#E0') || ($pattern == '-#E00')) {
  553. $regex[$pkey] .= '[' . $symbols['minus']. '-]{0,1}[0-9]{1,}(\\' . $symbols['decimal'] . '[0-9]{1,})*[eE][' . $symbols['minus']. '-]{0,1}[0-9]{1,}';
  554. } else {
  555. throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 5):"' . $pattern . '"');
  556. }
  557. }
  558. if (!empty($end)) {
  559. if ($end == '###') {
  560. $regex[$pkey] .= '(\\' . $symbols['decimal'] . '{1}[0-9]{1,}){0,1}';
  561. } else if ($end == '###-') {
  562. $regex[$pkey] .= '(\\' . $symbols['decimal'] . '{1}[0-9]{1,}){0,1}[' . $symbols['minus']. '-]';
  563. } else {
  564. throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 6):"' . $pattern . '"');
  565. }
  566. }
  567. $regex[$pkey] .= '$/u';
  568. }
  569. return $regex;
  570. }
  571. /**
  572. * Alias for getNumber
  573. *
  574. * @param string $input Number to localize
  575. * @param array $options Options: locale, precision. See {@link setOptions()} for details.
  576. * @return float
  577. */
  578. public static function getFloat($input, array $options = array())
  579. {
  580. return floatval(self::getNumber($input, $options));
  581. }
  582. /**
  583. * Returns a locale formatted integer number
  584. * Alias for toNumber()
  585. *
  586. * @param string $value Number to normalize
  587. * @param array $options Options: locale, precision. See {@link setOptions()} for details.
  588. * @return string Locale formatted number
  589. */
  590. public static function toFloat($value, array $options = array())
  591. {
  592. $options['number_format'] = Zend_Locale_Format::STANDARD;
  593. return self::toNumber($value, $options);
  594. }
  595. /**
  596. * Returns if a float was found
  597. * Alias for isNumber()
  598. *
  599. * @param string $value Localized number string
  600. * @param array $options Options: locale. See {@link setOptions()} for details.
  601. * @return boolean Returns true if a number was found
  602. */
  603. public static function isFloat($value, array $options = array())
  604. {
  605. return self::isNumber($value, $options);
  606. }
  607. /**
  608. * Returns the first found integer from an string
  609. * Parsing depends on given locale (grouping and decimal)
  610. *
  611. * Examples for input:
  612. * ' 2345.4356,1234' = 23455456
  613. * '+23,3452.123' = 233452
  614. * ' 12343 ' = 12343
  615. * '-9456km' = -9456
  616. * '0' = 0
  617. * '(-){0,1}(\d+(\.){0,1})*(\,){0,1})\d+'
  618. *
  619. * @param string $input Input string to parse for numbers
  620. * @param array $options Options: locale. See {@link setOptions()} for details.
  621. * @return integer Returns the extracted number
  622. */
  623. public static function getInteger($input, array $options = array())
  624. {
  625. $options['precision'] = 0;
  626. return intval(self::getFloat($input, $options));
  627. }
  628. /**
  629. * Returns a localized number
  630. *
  631. * @param string $value Number to normalize
  632. * @param array $options Options: locale. See {@link setOptions()} for details.
  633. * @return string Locale formatted number
  634. */
  635. public static function toInteger($value, array $options = array())
  636. {
  637. $options['precision'] = 0;
  638. $options['number_format'] = Zend_Locale_Format::STANDARD;
  639. return self::toNumber($value, $options);
  640. }
  641. /**
  642. * Returns if a integer was found
  643. *
  644. * @param string $value Localized number string
  645. * @param array $options Options: locale. See {@link setOptions()} for details.
  646. * @return boolean Returns true if a integer was found
  647. */
  648. public static function isInteger($value, array $options = array())
  649. {
  650. if (!self::isNumber($value, $options)) {
  651. return false;
  652. }
  653. if (self::getInteger($value, $options) == self::getFloat($value, $options)) {
  654. return true;
  655. }
  656. return false;
  657. }
  658. /**
  659. * Converts a format string from PHP's date format to ISO format
  660. * Remember that Zend Date always returns localized string, so a month name which returns the english
  661. * month in php's date() will return the translated month name with this function... use 'en' as locale
  662. * if you are in need of the original english names
  663. *
  664. * The conversion has the following restrictions:
  665. * 'a', 'A' - Meridiem is not explicit upper/lowercase, you have to upper/lowercase the translated value yourself
  666. *
  667. * @param string $format Format string in PHP's date format
  668. * @return string Format string in ISO format
  669. */
  670. public static function convertPhpToIsoFormat($format)
  671. {
  672. if ($format === null) {
  673. return null;
  674. }
  675. $convert = array(
  676. 'd' => 'dd' , 'D' => 'EE' , 'j' => 'd' , 'l' => 'EEEE',
  677. 'N' => 'eee' , 'S' => 'SS' , 'w' => 'e' , 'z' => 'D' ,
  678. 'W' => 'ww' , 'F' => 'MMMM', 'm' => 'MM' , 'M' => 'MMM' ,
  679. 'n' => 'M' , 't' => 'ddd' , 'L' => 'l' , 'o' => 'YYYY',
  680. 'Y' => 'yyyy', 'y' => 'yy' , 'a' => 'a' , 'A' => 'a' ,
  681. 'B' => 'B' , 'g' => 'h' , 'G' => 'H' , 'h' => 'hh' ,
  682. 'H' => 'HH' , 'i' => 'mm' , 's' => 'ss' , 'e' => 'zzzz',
  683. 'I' => 'I' , 'O' => 'Z' , 'P' => 'ZZZZ', 'T' => 'z' ,
  684. 'Z' => 'X' , 'c' => 'yyyy-MM-ddTHH:mm:ssZZZZ', 'r' => 'r',
  685. 'U' => 'U',
  686. );
  687. $escaped = false;
  688. $inEscapedString = false;
  689. $converted = array();
  690. foreach (str_split($format) as $char) {
  691. if (!$escaped && $char == '\\') {
  692. // Next char will be escaped: let's remember it
  693. $escaped = true;
  694. } elseif ($escaped) {
  695. if (!$inEscapedString) {
  696. // First escaped string: start the quoted chunk
  697. $converted[] = "'";
  698. $inEscapedString = true;
  699. }
  700. // Since the previous char was a \ and we are in the quoted
  701. // chunk, let's simply add $char as it is
  702. $converted[] = $char;
  703. $escaped = false;
  704. } elseif ($char == "'") {
  705. // Single quotes need to be escaped like this
  706. $converted[] = "''";
  707. } else {
  708. if ($inEscapedString) {
  709. // Close the single-quoted chunk
  710. $converted[] = "'";
  711. $inEscapedString = false;
  712. }
  713. // Convert the unescaped char if needed
  714. if (isset($convert[$char])) {
  715. $converted[] = $convert[$char];
  716. } else {
  717. $converted[] = $char;
  718. }
  719. }
  720. }
  721. return implode($converted);
  722. }
  723. /**
  724. * Parse date and split in named array fields
  725. *
  726. * @param string $date Date string to parse
  727. * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.
  728. * @return array Possible array members: day, month, year, hour, minute, second, fixed, format
  729. * @throws Zend_Locale_Exception
  730. */
  731. private static function _parseDate($date, $options)
  732. {
  733. if (!self::_getUniCodeSupport()) {
  734. trigger_error("Sorry, your PCRE extension does not support UTF8 which is needed for the I18N core", E_USER_NOTICE);
  735. }
  736. $options = self::_checkOptions($options) + self::$_options;
  737. $test = array('h', 'H', 'm', 's', 'y', 'Y', 'M', 'd', 'D', 'E', 'S', 'l', 'B', 'I',
  738. 'X', 'r', 'U', 'G', 'w', 'e', 'a', 'A', 'Z', 'z', 'v');
  739. $format = $options['date_format'];
  740. $number = $date; // working copy
  741. $result['date_format'] = $format; // save the format used to normalize $number (convenience)
  742. $result['locale'] = $options['locale']; // save the locale used to normalize $number (convenience)
  743. $oenc = self::_getEncoding();
  744. self::_setEncoding('UTF-8');
  745. $day = iconv_strpos($format, 'd');
  746. $month = iconv_strpos($format, 'M');
  747. $year = iconv_strpos($format, 'y');
  748. $hour = iconv_strpos($format, 'H');
  749. $min = iconv_strpos($format, 'm');
  750. $sec = iconv_strpos($format, 's');
  751. $am = null;
  752. if ($hour === false) {
  753. $hour = iconv_strpos($format, 'h');
  754. }
  755. if ($year === false) {
  756. $year = iconv_strpos($format, 'Y');
  757. }
  758. if ($day === false) {
  759. $day = iconv_strpos($format, 'E');
  760. if ($day === false) {
  761. $day = iconv_strpos($format, 'D');
  762. }
  763. }
  764. if ($day !== false) {
  765. $parse[$day] = 'd';
  766. if (!empty($options['locale']) && ($options['locale'] !== 'root') &&
  767. (!is_object($options['locale']) || ((string) $options['locale'] !== 'root'))) {
  768. // erase day string
  769. $daylist = Zend_Locale_Data::getList($options['locale'], 'day');
  770. foreach($daylist as $key => $name) {
  771. if (iconv_strpos($number, $name) !== false) {
  772. $number = str_replace($name, "EEEE", $number);
  773. break;
  774. }
  775. }
  776. }
  777. }
  778. $position = false;
  779. if ($month !== false) {
  780. $parse[$month] = 'M';
  781. if (!empty($options['locale']) && ($options['locale'] !== 'root') &&
  782. (!is_object($options['locale']) || ((string) $options['locale'] !== 'root'))) {
  783. // prepare to convert month name to their numeric equivalents, if requested,
  784. // and we have a $options['locale']
  785. $position = self::_replaceMonth($number, Zend_Locale_Data::getList($options['locale'],
  786. 'month'));
  787. if ($position === false) {
  788. $position = self::_replaceMonth($number, Zend_Locale_Data::getList($options['locale'],
  789. 'month', array('gregorian', 'format', 'abbreviated')));
  790. }
  791. }
  792. }
  793. if ($year !== false) {
  794. $parse[$year] = 'y';
  795. }
  796. if ($hour !== false) {
  797. $parse[$hour] = 'H';
  798. }
  799. if ($min !== false) {
  800. $parse[$min] = 'm';
  801. }
  802. if ($sec !== false) {
  803. $parse[$sec] = 's';
  804. }
  805. if (empty($parse)) {
  806. self::_setEncoding($oenc);
  807. #require_once 'Zend/Locale/Exception.php';
  808. throw new Zend_Locale_Exception("Unknown date format, neither date nor time in '" . $format . "' found");
  809. }
  810. ksort($parse);
  811. // get daytime
  812. if (iconv_strpos($format, 'a') !== false) {
  813. if (iconv_strpos(strtoupper($number), strtoupper(Zend_Locale_Data::getContent($options['locale'], 'am'))) !== false) {
  814. $am = true;
  815. } else if (iconv_strpos(strtoupper($number), strtoupper(Zend_Locale_Data::getContent($options['locale'], 'pm'))) !== false) {
  816. $am = false;
  817. }
  818. }
  819. // split number parts
  820. $split = false;
  821. preg_match_all('/\d+/u', $number, $splitted);
  822. if (count($splitted[0]) == 0) {
  823. self::_setEncoding($oenc);
  824. #require_once 'Zend/Locale/Exception.php';
  825. throw new Zend_Locale_Exception("No date part in '$date' found.");
  826. }
  827. if (count($splitted[0]) == 1) {
  828. $split = 0;
  829. }
  830. $cnt = 0;
  831. foreach($parse as $key => $value) {
  832. switch($value) {
  833. case 'd':
  834. if ($split === false) {
  835. if (count($splitted[0]) > $cnt) {
  836. $result['day'] = $splitted[0][$cnt];
  837. }
  838. } else {
  839. $result['day'] = iconv_substr($splitted[0][0], $split, 2);
  840. $split += 2;
  841. }
  842. ++$cnt;
  843. break;
  844. case 'M':
  845. if ($split === false) {
  846. if (count($splitted[0]) > $cnt) {
  847. $result['month'] = $splitted[0][$cnt];
  848. }
  849. } else {
  850. $result['month'] = iconv_substr($splitted[0][0], $split, 2);
  851. $split += 2;
  852. }
  853. ++$cnt;
  854. break;
  855. case 'y':
  856. $length = 2;
  857. if ((iconv_substr($format, $year, 4) == 'yyyy')
  858. || (iconv_substr($format, $year, 4) == 'YYYY')) {
  859. $length = 4;
  860. }
  861. if ($split === false) {
  862. if (count($splitted[0]) > $cnt) {
  863. $result['year'] = $splitted[0][$cnt];
  864. }
  865. } else {
  866. $result['year'] = iconv_substr($splitted[0][0], $split, $length);
  867. $split += $length;
  868. }
  869. ++$cnt;
  870. break;
  871. case 'H':
  872. if ($split === false) {
  873. if (count($splitted[0]) > $cnt) {
  874. $result['hour'] = $splitted[0][$cnt];
  875. }
  876. } else {
  877. $result['hour'] = iconv_substr($splitted[0][0], $split, 2);
  878. $split += 2;
  879. }
  880. ++$cnt;
  881. break;
  882. case 'm':
  883. if ($split === false) {
  884. if (count($splitted[0]) > $cnt) {
  885. $result['minute'] = $splitted[0][$cnt];
  886. }
  887. } else {
  888. $result['minute'] = iconv_substr($splitted[0][0], $split, 2);
  889. $split += 2;
  890. }
  891. ++$cnt;
  892. break;
  893. case 's':
  894. if ($split === false) {
  895. if (count($splitted[0]) > $cnt) {
  896. $result['second'] = $splitted[0][$cnt];
  897. }
  898. } else {
  899. $result['second'] = iconv_substr($splitted[0][0], $split, 2);
  900. $split += 2;
  901. }
  902. ++$cnt;
  903. break;
  904. }
  905. }
  906. // AM/PM correction
  907. if ($hour !== false) {
  908. if (($am === true) and ($result['hour'] == 12)){
  909. $result['hour'] = 0;
  910. } else if (($am === false) and ($result['hour'] != 12)) {
  911. $result['hour'] += 12;
  912. }
  913. }
  914. if ($options['fix_date'] === true) {
  915. $result['fixed'] = 0; // nothing has been "fixed" by swapping date parts around (yet)
  916. }
  917. if ($day !== false) {
  918. // fix false month
  919. if (isset($result['day']) and isset($result['month'])) {
  920. if (($position !== false) and ((iconv_strpos($date, $result['day']) === false) or
  921. (isset($result['year']) and (iconv_strpos($date, $result['year']) === false)))) {
  922. if ($options['fix_date'] !== true) {
  923. self::_setEncoding($oenc);
  924. #require_once 'Zend/Locale/Exception.php';
  925. throw new Zend_Locale_Exception("Unable to parse date '$date' using '" . $format
  926. . "' (false month, $position, $month)");
  927. }
  928. $temp = $result['day'];
  929. $result['day'] = $result['month'];
  930. $result['month'] = $temp;
  931. $result['fixed'] = 1;
  932. }
  933. }
  934. // fix switched values d <> y
  935. if (isset($result['day']) and isset($result['year'])) {
  936. if ($result['day'] > 31) {
  937. if ($options['fix_date'] !== true) {
  938. self::_setEncoding($oenc);
  939. #require_once 'Zend/Locale/Exception.php';
  940. throw new Zend_Locale_Exception("Unable to parse date '$date' using '"
  941. . $format . "' (d <> y)");
  942. }
  943. $temp = $result['year'];
  944. $result['year'] = $result['day'];
  945. $result['day'] = $temp;
  946. $result['fixed'] = 2;
  947. }
  948. }
  949. // fix switched values M <> y
  950. if (isset($result['month']) and isset($result['year'])) {
  951. if ($result['month'] > 31) {
  952. if ($options['fix_date'] !== true) {
  953. self::_setEncoding($oenc);
  954. #require_once 'Zend/Locale/Exception.php';
  955. throw new Zend_Locale_Exception("Unable to parse date '$date' using '"
  956. . $format . "' (M <> y)");
  957. }
  958. $temp = $result['year'];
  959. $result['year'] = $result['month'];
  960. $result['month'] = $temp;
  961. $result['fixed'] = 3;
  962. }
  963. }
  964. // fix switched values M <> d
  965. if (isset($result['month']) and isset($result['day'])) {
  966. if ($result['month'] > 12) {
  967. if ($options['fix_date'] !== true || $result['month'] > 31) {
  968. self::_setEncoding($oenc);
  969. #require_once 'Zend/Locale/Exception.php';
  970. throw new Zend_Locale_Exception("Unable to parse date '$date' using '"
  971. . $format . "' (M <> d)");
  972. }
  973. $temp = $result['day'];
  974. $result['day'] = $result['month'];
  975. $result['month'] = $temp;
  976. $result['fixed'] = 4;
  977. }
  978. }
  979. }
  980. if (isset($result['year'])) {
  981. if (((iconv_strlen($result['year']) == 2) && ($result['year'] < 10)) ||
  982. (((iconv_strpos($format, 'yy') !== false) && (iconv_strpos($format, 'yyyy') === false)) ||
  983. ((iconv_strpos($format, 'YY') !== false) && (iconv_strpos($format, 'YYYY') === false)))) {
  984. if (($result['year'] >= 0) && ($result['year'] < 100)) {
  985. if ($result['year'] < 70) {
  986. $result['year'] = (int) $result['year'] + 100;
  987. }
  988. $result['year'] = (int) $result['year'] + 1900;
  989. }
  990. }
  991. }
  992. self::_setEncoding($oenc);
  993. return $result;
  994. }
  995. /**
  996. * Search $number for a month name found in $monthlist, and replace if found.
  997. *
  998. * @param string $number Date string (modified)
  999. * @param array $monthlist List of month names
  1000. *
  1001. * @return int|false Position of replaced string (false if nothing replaced)
  1002. */
  1003. protected static function _replaceMonth(&$number, $monthlist)
  1004. {
  1005. // If $locale was invalid, $monthlist will default to a "root" identity
  1006. // mapping for each month number from 1 to 12.
  1007. // If no $locale was given, or $locale was invalid, do not use this identity mapping to normalize.
  1008. // Otherwise, translate locale aware month names in $number to their numeric equivalents.
  1009. $position = false;
  1010. if ($monthlist && $monthlist[1] != 1) {
  1011. foreach($monthlist as $key => $name) {
  1012. if (($position = iconv_strpos($number, $name, 0, 'UTF-8')) !== false) {
  1013. $number = str_ireplace($name, $key, $number);
  1014. return $position;
  1015. }
  1016. }
  1017. }
  1018. return false;
  1019. }
  1020. /**
  1021. * Returns the default date format for $locale.
  1022. *
  1023. * @param string|Zend_Locale $locale OPTIONAL Locale of $number, possibly in string form (e.g. 'de_AT')
  1024. * @return string format
  1025. * @throws Zend_Locale_Exception throws an exception when locale data is broken
  1026. */
  1027. public static function getDateFormat($locale = null)
  1028. {
  1029. $format = Zend_Locale_Data::getContent($locale, 'date');
  1030. if (empty($format)) {
  1031. #require_once 'Zend/Locale/Exception.php';
  1032. throw new Zend_Locale_Exception("failed to receive data from locale $locale");
  1033. }
  1034. return $format;
  1035. }
  1036. /**
  1037. * Returns an array with the normalized date from an locale date
  1038. * a input of 10.01.2006 without a $locale would return:
  1039. * array ('day' => 10, 'month' => 1, 'year' => 2006)
  1040. * The 'locale' option is only used to convert human readable day
  1041. * and month names to their numeric equivalents.
  1042. * The 'format' option allows specification of self-defined date formats,
  1043. * when not using the default format for the 'locale'.
  1044. *
  1045. * @param string $date Date string
  1046. * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.
  1047. * @return array Possible array members: day, month, year, hour, minute, second, fixed, format
  1048. */
  1049. public static function getDate($date, array $options = array())
  1050. {
  1051. $options = self::_checkOptions($options) + self::$_options;
  1052. if (empty($options['date_format'])) {
  1053. $options['format_type'] = 'iso';
  1054. $options['date_format'] = self::getDateFormat($options['locale']);
  1055. }
  1056. return self::_parseDate($date, $options);
  1057. }
  1058. /**
  1059. * Returns if the given datestring contains all date parts from the given format.
  1060. * If no format is given, the default date format from the locale is used
  1061. * If you want to check if the date is a proper date you should use Zend_Date::isDate()
  1062. *
  1063. * @param string $date Date string
  1064. * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.
  1065. * @return boolean
  1066. */
  1067. public static function checkDateFormat($date, array $options = array())
  1068. {
  1069. try {
  1070. $date = self::getDate($date, $options);
  1071. } catch (Exception $e) {
  1072. return false;
  1073. }
  1074. if (empty($options['date_format'])) {
  1075. $options['format_type'] = 'iso';
  1076. $options['date_format'] = self::getDateFormat(isset($options['locale']) ? $options['locale'] : null);
  1077. }
  1078. $options = self::_checkOptions($options) + self::$_options;
  1079. // day expected but not parsed
  1080. if ((iconv_strpos($options['date_format'], 'd', 0, 'UTF-8') !== false) and (!isset($date['day']) or ($date['day'] === ""))) {
  1081. return false;
  1082. }
  1083. // month expected but not parsed
  1084. if ((iconv_strpos($options['date_format'], 'M', 0, 'UTF-8')