PageRenderTime 56ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Zend/Locale/Format.php

https://bitbucket.org/claudiu_marginean/magento-hg-mirror
PHP | 1265 lines | 903 code | 108 blank | 254 comment | 249 complexity | dffaec5eaba9d478141519e24d1bb677 MD5 | raw file
Possible License(s): CC-BY-SA-3.0, LGPL-2.1, GPL-2.0, WTFPL

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

Large files files are truncated, but you can click here to view the full file