PageRenderTime 25ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/thirdparty/Zend/Locale/Format.php

http://github.com/silverstripe/sapphire
PHP | 1313 lines | 972 code | 108 blank | 233 comment | 271 complexity | 61bd84eecf086d1a872b03488458f423 MD5 | raw file
Possible License(s): BSD-3-Clause, MIT, CC-BY-3.0, GPL-2.0, AGPL-1.0, LGPL-2.1

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

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