PageRenderTime 63ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/library/Zend/Locale/Format.php

https://bitbucket.org/hjain/loudmusic
PHP | 1267 lines | 926 code | 108 blank | 233 comment | 249 complexity | 19ff391f4bea515453895d934ac3dc52 MD5 | raw file

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: Format.php 24807 2012-05-15 12:10:42Z adamlundrigan $
  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. $oenc = iconv_get_encoding('internal_encoding');
  280. iconv_set_encoding('internal_encoding', '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. iconv_set_encoding('internal_encoding', $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. iconv_set_encoding('internal_encoding', $oenc);
  426. return (string) $format;
  427. }
  428. private static function _seperateFormat($format, $value, $precision)
  429. {
  430. if (iconv_strpos($format, ';') !== false) {
  431. if (call_user_func(Zend_Locale_Math::$comp, $value, 0, $precision) < 0) {
  432. $tmpformat = iconv_substr($format, iconv_strpos($format, ';') + 1);
  433. if ($tmpformat[0] == '(') {
  434. $format = iconv_substr($format, 0, iconv_strpos($format, ';'));
  435. } else {
  436. $format = $tmpformat;
  437. }
  438. } else {
  439. $format = iconv_substr($format, 0, iconv_strpos($format, ';'));
  440. }
  441. }
  442. return $format;
  443. }
  444. /**
  445. * Checks if the input contains a normalized or localized number
  446. *
  447. * @param string $input Localized number string
  448. * @param array $options Options: locale. See {@link setOptions()} for details.
  449. * @return boolean Returns true if a number was found
  450. */
  451. public static function isNumber($input, array $options = array())
  452. {
  453. if (!self::_getUniCodeSupport()) {
  454. trigger_error("Sorry, your PCRE extension does not support UTF8 which is needed for the I18N core", E_USER_NOTICE);
  455. }
  456. $options = self::_checkOptions($options) + self::$_options;
  457. // Get correct signs for this locale
  458. $symbols = Zend_Locale_Data::getList($options['locale'],'symbols');
  459. $regexs = Zend_Locale_Format::_getRegexForType('decimalnumber', $options);
  460. $regexs = array_merge($regexs, Zend_Locale_Format::_getRegexForType('scientificnumber', $options));
  461. if (!empty($input) && ($input[0] == $symbols['decimal'])) {
  462. $input = 0 . $input;
  463. }
  464. foreach ($regexs as $regex) {
  465. preg_match($regex, $input, $found);
  466. if (isset($found[0])) {
  467. return true;
  468. }
  469. }
  470. return false;
  471. }
  472. /**
  473. * Internal method to convert cldr number syntax into regex
  474. *
  475. * @param string $type
  476. * @return string
  477. */
  478. private static function _getRegexForType($type, $options)
  479. {
  480. $decimal = Zend_Locale_Data::getContent($options['locale'], $type);
  481. $decimal = preg_replace('/[^#0,;\.\-Ee]/u', '',$decimal);
  482. $patterns = explode(';', $decimal);
  483. if (count($patterns) == 1) {
  484. $patterns[1] = '-' . $patterns[0];
  485. }
  486. $symbols = Zend_Locale_Data::getList($options['locale'],'symbols');
  487. foreach($patterns as $pkey => $pattern) {
  488. $regex[$pkey] = '/^';
  489. $rest = 0;
  490. $end = null;
  491. if (strpos($pattern, '.') !== false) {
  492. $end = substr($pattern, strpos($pattern, '.') + 1);
  493. $pattern = substr($pattern, 0, -strlen($end) - 1);
  494. }
  495. if (strpos($pattern, ',') !== false) {
  496. $parts = explode(',', $pattern);
  497. $count = count($parts);
  498. foreach($parts as $key => $part) {
  499. switch ($part) {
  500. case '#':
  501. case '-#':
  502. if ($part[0] == '-') {
  503. $regex[$pkey] .= '[' . $symbols['minus'] . '-]{0,1}';
  504. } else {
  505. $regex[$pkey] .= '[' . $symbols['plus'] . '+]{0,1}';
  506. }
  507. if (($parts[$key + 1]) == '##0') {
  508. $regex[$pkey] .= '[0-9]{1,3}';
  509. } else if (($parts[$key + 1]) == '##') {
  510. $regex[$pkey] .= '[0-9]{1,2}';
  511. } else {
  512. throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 1):"' . $pattern . '"');
  513. }
  514. break;
  515. case '##':
  516. if ($parts[$key + 1] == '##0') {
  517. $regex[$pkey] .= '(\\' . $symbols['group'] . '{0,1}[0-9]{2})*';
  518. } else {
  519. throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 2):"' . $pattern . '"');
  520. }
  521. break;
  522. case '##0':
  523. if ($parts[$key - 1] == '##') {
  524. $regex[$pkey] .= '[0-9]';
  525. } else if (($parts[$key - 1] == '#') || ($parts[$key - 1] == '-#')) {
  526. $regex[$pkey] .= '(\\' . $symbols['group'] . '{0,1}[0-9]{3})*';
  527. } else {
  528. throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 3):"' . $pattern . '"');
  529. }
  530. break;
  531. case '#0':
  532. if ($key == 0) {
  533. $regex[$pkey] .= '[0-9]*';
  534. } else {
  535. throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 4):"' . $pattern . '"');
  536. }
  537. break;
  538. }
  539. }
  540. }
  541. if (strpos($pattern, 'E') !== false) {
  542. if (($pattern == '#E0') || ($pattern == '#E00')) {
  543. $regex[$pkey] .= '[' . $symbols['plus']. '+]{0,1}[0-9]{1,}(\\' . $symbols['decimal'] . '[0-9]{1,})*[eE][' . $symbols['plus']. '+]{0,1}[0-9]{1,}';
  544. } else if (($pattern == '-#E0') || ($pattern == '-#E00')) {
  545. $regex[$pkey] .= '[' . $symbols['minus']. '-]{0,1}[0-9]{1,}(\\' . $symbols['decimal'] . '[0-9]{1,})*[eE][' . $symbols['minus']. '-]{0,1}[0-9]{1,}';
  546. } else {
  547. throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 5):"' . $pattern . '"');
  548. }
  549. }
  550. if (!empty($end)) {
  551. if ($end == '###') {
  552. $regex[$pkey] .= '(\\' . $symbols['decimal'] . '{1}[0-9]{1,}){0,1}';
  553. } else if ($end == '###-') {
  554. $regex[$pkey] .= '(\\' . $symbols['decimal'] . '{1}[0-9]{1,}){0,1}[' . $symbols['minus']. '-]';
  555. } else {
  556. throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 6):"' . $pattern . '"');
  557. }
  558. }
  559. $regex[$pkey] .= '$/u';
  560. }
  561. return $regex;
  562. }
  563. /**
  564. * Alias for getNumber
  565. *
  566. * @param string $value Number to localize
  567. * @param array $options Options: locale, precision. See {@link setOptions()} for details.
  568. * @return float
  569. */
  570. public static function getFloat($input, array $options = array())
  571. {
  572. return floatval(self::getNumber($input, $options));
  573. }
  574. /**
  575. * Returns a locale formatted integer number
  576. * Alias for toNumber()
  577. *
  578. * @param string $value Number to normalize
  579. * @param array $options Options: locale, precision. See {@link setOptions()} for details.
  580. * @return string Locale formatted number
  581. */
  582. public static function toFloat($value, array $options = array())
  583. {
  584. $options['number_format'] = Zend_Locale_Format::STANDARD;
  585. return self::toNumber($value, $options);
  586. }
  587. /**
  588. * Returns if a float was found
  589. * Alias for isNumber()
  590. *
  591. * @param string $input Localized number string
  592. * @param array $options Options: locale. See {@link setOptions()} for details.
  593. * @return boolean Returns true if a number was found
  594. */
  595. public static function isFloat($value, array $options = array())
  596. {
  597. return self::isNumber($value, $options);
  598. }
  599. /**
  600. * Returns the first found integer from an string
  601. * Parsing depends on given locale (grouping and decimal)
  602. *
  603. * Examples for input:
  604. * ' 2345.4356,1234' = 23455456
  605. * '+23,3452.123' = 233452
  606. * ' 12343 ' = 12343
  607. * '-9456km' = -9456
  608. * '0' = 0
  609. * '(-){0,1}(\d+(\.){0,1})*(\,){0,1})\d+'
  610. *
  611. * @param string $input Input string to parse for numbers
  612. * @param array $options Options: locale. See {@link setOptions()} for details.
  613. * @return integer Returns the extracted number
  614. */
  615. public static function getInteger($input, array $options = array())
  616. {
  617. $options['precision'] = 0;
  618. return intval(self::getFloat($input, $options));
  619. }
  620. /**
  621. * Returns a localized number
  622. *
  623. * @param string $value Number to normalize
  624. * @param array $options Options: locale. See {@link setOptions()} for details.
  625. * @return string Locale formatted number
  626. */
  627. public static function toInteger($value, array $options = array())
  628. {
  629. $options['precision'] = 0;
  630. $options['number_format'] = Zend_Locale_Format::STANDARD;
  631. return self::toNumber($value, $options);
  632. }
  633. /**
  634. * Returns if a integer was found
  635. *
  636. * @param string $input Localized number string
  637. * @param array $options Options: locale. See {@link setOptions()} for details.
  638. * @return boolean Returns true if a integer was found
  639. */
  640. public static function isInteger($value, array $options = array())
  641. {
  642. if (!self::isNumber($value, $options)) {
  643. return false;
  644. }
  645. if (self::getInteger($value, $options) == self::getFloat($value, $options)) {
  646. return true;
  647. }
  648. return false;
  649. }
  650. /**
  651. * Converts a format string from PHP's date format to ISO format
  652. * Remember that Zend Date always returns localized string, so a month name which returns the english
  653. * month in php's date() will return the translated month name with this function... use 'en' as locale
  654. * if you are in need of the original english names
  655. *
  656. * The conversion has the following restrictions:
  657. * 'a', 'A' - Meridiem is not explicit upper/lowercase, you have to upper/lowercase the translated value yourself
  658. *
  659. * @param string $format Format string in PHP's date format
  660. * @return string Format string in ISO format
  661. */
  662. public static function convertPhpToIsoFormat($format)
  663. {
  664. if ($format === null) {
  665. return null;
  666. }
  667. $convert = array('d' => 'dd' , 'D' => 'EE' , 'j' => 'd' , 'l' => 'EEEE', 'N' => 'eee' , 'S' => 'SS' ,
  668. 'w' => 'e' , 'z' => 'D' , 'W' => 'ww' , 'F' => 'MMMM', 'm' => 'MM' , 'M' => 'MMM' ,
  669. 'n' => 'M' , 't' => 'ddd' , 'L' => 'l' , 'o' => 'YYYY', 'Y' => 'yyyy', 'y' => 'yy' ,
  670. 'a' => 'a' , 'A' => 'a' , 'B' => 'B' , 'g' => 'h' , 'G' => 'H' , 'h' => 'hh' ,
  671. 'H' => 'HH' , 'i' => 'mm' , 's' => 'ss' , 'e' => 'zzzz', 'I' => 'I' , 'O' => 'Z' ,
  672. 'P' => 'ZZZZ', 'T' => 'z' , 'Z' => 'X' , 'c' => 'yyyy-MM-ddTHH:mm:ssZZZZ',
  673. 'r' => 'r' , 'U' => 'U');
  674. $values = str_split($format);
  675. foreach ($values as $key => $value) {
  676. if (isset($convert[$value]) === true) {
  677. $values[$key] = $convert[$value];
  678. }
  679. }
  680. return join($values);
  681. }
  682. /**
  683. * Parse date and split in named array fields
  684. *
  685. * @param string $date Date string to parse
  686. * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.
  687. * @return array Possible array members: day, month, year, hour, minute, second, fixed, format
  688. */
  689. private static function _parseDate($date, $options)
  690. {
  691. if (!self::_getUniCodeSupport()) {
  692. trigger_error("Sorry, your PCRE extension does not support UTF8 which is needed for the I18N core", E_USER_NOTICE);
  693. }
  694. $options = self::_checkOptions($options) + self::$_options;
  695. $test = array('h', 'H', 'm', 's', 'y', 'Y', 'M', 'd', 'D', 'E', 'S', 'l', 'B', 'I',
  696. 'X', 'r', 'U', 'G', 'w', 'e', 'a', 'A', 'Z', 'z', 'v');
  697. $format = $options['date_format'];
  698. $number = $date; // working copy
  699. $result['date_format'] = $format; // save the format used to normalize $number (convenience)
  700. $result['locale'] = $options['locale']; // save the locale used to normalize $number (convenience)
  701. $oenc = iconv_get_encoding('internal_encoding');
  702. iconv_set_encoding('internal_encoding', 'UTF-8');
  703. $day = iconv_strpos($format, 'd');
  704. $month = iconv_strpos($format, 'M');
  705. $year = iconv_strpos($format, 'y');
  706. $hour = iconv_strpos($format, 'H');
  707. $min = iconv_strpos($format, 'm');
  708. $sec = iconv_strpos($format, 's');
  709. $am = null;
  710. if ($hour === false) {
  711. $hour = iconv_strpos($format, 'h');
  712. }
  713. if ($year === false) {
  714. $year = iconv_strpos($format, 'Y');
  715. }
  716. if ($day === false) {
  717. $day = iconv_strpos($format, 'E');
  718. if ($day === false) {
  719. $day = iconv_strpos($format, 'D');
  720. }
  721. }
  722. if ($day !== false) {
  723. $parse[$day] = 'd';
  724. if (!empty($options['locale']) && ($options['locale'] !== 'root') &&
  725. (!is_object($options['locale']) || ((string) $options['locale'] !== 'root'))) {
  726. // erase day string
  727. $daylist = Zend_Locale_Data::getList($options['locale'], 'day');
  728. foreach($daylist as $key => $name) {
  729. if (iconv_strpos($number, $name) !== false) {
  730. $number = str_replace($name, "EEEE", $number);
  731. break;
  732. }
  733. }
  734. }
  735. }
  736. $position = false;
  737. if ($month !== false) {
  738. $parse[$month] = 'M';
  739. if (!empty($options['locale']) && ($options['locale'] !== 'root') &&
  740. (!is_object($options['locale']) || ((string) $options['locale'] !== 'root'))) {
  741. // prepare to convert month name to their numeric equivalents, if requested,
  742. // and we have a $options['locale']
  743. $position = self::_replaceMonth($number, Zend_Locale_Data::getList($options['locale'],
  744. 'month'));
  745. if ($position === false) {
  746. $position = self::_replaceMonth($number, Zend_Locale_Data::getList($options['locale'],
  747. 'month', array('gregorian', 'format', 'abbreviated')));
  748. }
  749. }
  750. }
  751. if ($year !== false) {
  752. $parse[$year] = 'y';
  753. }
  754. if ($hour !== false) {
  755. $parse[$hour] = 'H';
  756. }
  757. if ($min !== false) {
  758. $parse[$min] = 'm';
  759. }
  760. if ($sec !== false) {
  761. $parse[$sec] = 's';
  762. }
  763. if (empty($parse)) {
  764. iconv_set_encoding('internal_encoding', $oenc);
  765. require_once 'Zend/Locale/Exception.php';
  766. throw new Zend_Locale_Exception("Unknown date format, neither date nor time in '" . $format . "' found");
  767. }
  768. ksort($parse);
  769. // get daytime
  770. if (iconv_strpos($format, 'a') !== false) {
  771. if (iconv_strpos(strtoupper($number), strtoupper(Zend_Locale_Data::getContent($options['locale'], 'am'))) !== false) {
  772. $am = true;
  773. } else if (iconv_strpos(strtoupper($number), strtoupper(Zend_Locale_Data::getContent($options['locale'], 'pm'))) !== false) {
  774. $am = false;
  775. }
  776. }
  777. // split number parts
  778. $split = false;
  779. preg_match_all('/\d+/u', $number, $splitted);
  780. if (count($splitted[0]) == 0) {
  781. iconv_set_encoding('internal_encoding', $oenc);
  782. require_once 'Zend/Locale/Exception.php';
  783. throw new Zend_Locale_Exception("No date part in '$date' found.");
  784. }
  785. if (count($splitted[0]) == 1) {
  786. $split = 0;
  787. }
  788. $cnt = 0;
  789. foreach($parse as $key => $value) {
  790. switch($value) {
  791. case 'd':
  792. if ($split === false) {
  793. if (count($splitted[0]) > $cnt) {
  794. $result['day'] = $splitted[0][$cnt];
  795. }
  796. } else {
  797. $result['day'] = iconv_substr($splitted[0][0], $split, 2);
  798. $split += 2;
  799. }
  800. ++$cnt;
  801. break;
  802. case 'M':
  803. if ($split === false) {
  804. if (count($splitted[0]) > $cnt) {
  805. $result['month'] = $splitted[0][$cnt];
  806. }
  807. } else {
  808. $result['month'] = iconv_substr($splitted[0][0], $split, 2);
  809. $split += 2;
  810. }
  811. ++$cnt;
  812. break;
  813. case 'y':
  814. $length = 2;
  815. if ((iconv_substr($format, $year, 4) == 'yyyy')
  816. || (iconv_substr($format, $year, 4) == 'YYYY')) {
  817. $length = 4;
  818. }
  819. if ($split === false) {
  820. if (count($splitted[0]) > $cnt) {
  821. $result['year'] = $splitted[0][$cnt];
  822. }
  823. } else {
  824. $result['year'] = iconv_substr($splitted[0][0], $split, $length);
  825. $split += $length;
  826. }
  827. ++$cnt;
  828. break;
  829. case 'H':
  830. if ($split === false) {
  831. if (count($splitted[0]) > $cnt) {
  832. $result['hour'] = $splitted[0][$cnt];
  833. }
  834. } else {
  835. $result['hour'] = iconv_substr($splitted[0][0], $split, 2);
  836. $split += 2;
  837. }
  838. ++$cnt;
  839. break;
  840. case 'm':
  841. if ($split === false) {
  842. if (count($splitted[0]) > $cnt) {
  843. $result['minute'] = $splitted[0][$cnt];
  844. }
  845. } else {
  846. $result['minute'] = iconv_substr($splitted[0][0], $split, 2);
  847. $split += 2;
  848. }
  849. ++$cnt;
  850. break;
  851. case 's':
  852. if ($split === false) {
  853. if (count($splitted[0]) > $cnt) {
  854. $result['second'] = $splitted[0][$cnt];
  855. }
  856. } else {
  857. $result['second'] = iconv_substr($splitted[0][0], $split, 2);
  858. $split += 2;
  859. }
  860. ++$cnt;
  861. break;
  862. }
  863. }
  864. // AM/PM correction
  865. if ($hour !== false) {
  866. if (($am === true) and ($result['hour'] == 12)){
  867. $result['hour'] = 0;
  868. } else if (($am === false) and ($result['hour'] != 12)) {
  869. $result['hour'] += 12;
  870. }
  871. }
  872. if ($options['fix_date'] === true) {
  873. $result['fixed'] = 0; // nothing has been "fixed" by swapping date parts around (yet)
  874. }
  875. if ($day !== false) {
  876. // fix false month
  877. if (isset($result['day']) and isset($result['month'])) {
  878. if (($position !== false) and ((iconv_strpos($date, $result['day']) === false) or
  879. (isset($result['year']) and (iconv_strpos($date, $result['year']) === false)))) {
  880. if ($options['fix_date'] !== true) {
  881. iconv_set_encoding('internal_encoding', $oenc);
  882. require_once 'Zend/Locale/Exception.php';
  883. throw new Zend_Locale_Exception("Unable to parse date '$date' using '" . $format
  884. . "' (false month, $position, $month)");
  885. }
  886. $temp = $result['day'];
  887. $result['day'] = $result['month'];
  888. $result['month'] = $temp;
  889. $result['fixed'] = 1;
  890. }
  891. }
  892. // fix switched values d <> y
  893. if (isset($result['day']) and isset($result['year'])) {
  894. if ($result['day'] > 31) {
  895. if ($options['fix_date'] !== true) {
  896. iconv_set_encoding('internal_encoding', $oenc);
  897. require_once 'Zend/Locale/Exception.php';
  898. throw new Zend_Locale_Exception("Unable to parse date '$date' using '"
  899. . $format . "' (d <> y)");
  900. }
  901. $temp = $result['year'];
  902. $result['year'] = $result['day'];
  903. $result['day'] = $temp;
  904. $result['fixed'] = 2;
  905. }
  906. }
  907. // fix switched values M <> y
  908. if (isset($result['month']) and isset($result['year'])) {
  909. if ($result['month'] > 31) {
  910. if ($options['fix_date'] !== true) {
  911. iconv_set_encoding('internal_encoding', $oenc);
  912. require_once 'Zend/Locale/Exception.php';
  913. throw new Zend_Locale_Exception("Unable to parse date '$date' using '"
  914. . $format . "' (M <> y)");
  915. }
  916. $temp = $result['year'];
  917. $result['year'] = $result['month'];
  918. $result['month'] = $temp;
  919. $result['fixed'] = 3;
  920. }
  921. }
  922. // fix switched values M <> d
  923. if (isset($result['month']) and isset($result['day'])) {
  924. if ($result['month'] > 12) {
  925. if ($options['fix_date'] !== true || $result['month'] > 31) {
  926. iconv_set_encoding('internal_encoding', $oenc);
  927. require_once 'Zend/Locale/Exception.php';
  928. throw new Zend_Locale_Exception("Unable to parse date '$date' using '"
  929. . $format . "' (M <> d)");
  930. }
  931. $temp = $result['day'];
  932. $result['day'] = $result['month'];
  933. $result['month'] = $temp;
  934. $result['fixed'] = 4;
  935. }
  936. }
  937. }
  938. if (isset($result['year'])) {
  939. if (((iconv_strlen($result['year']) == 2) && ($result['year'] < 10)) ||
  940. (((iconv_strpos($format, 'yy') !== false) && (iconv_strpos($format, 'yyyy') === false)) ||
  941. ((iconv_strpos($format, 'YY') !== false) && (iconv_strpos($format, 'YYYY') === false)))) {
  942. if (($result['year'] >= 0) && ($result['year'] < 100)) {
  943. if ($result['year'] < 70) {
  944. $result['year'] = (int) $result['year'] + 100;
  945. }
  946. $result['year'] = (int) $result['year'] + 1900;
  947. }
  948. }
  949. }
  950. iconv_set_encoding('internal_encoding', $oenc);
  951. return $result;
  952. }
  953. /**
  954. * Search $number for a month name found in $monthlist, and replace if found.
  955. *
  956. * @param string $number Date string (modified)
  957. * @param array $monthlist List of month names
  958. *
  959. * @return int|false Position of replaced string (false if nothing replaced)
  960. */
  961. protected static function _replaceMonth(&$number, $monthlist)
  962. {
  963. // If $locale was invalid, $monthlist will default to a "root" identity
  964. // mapping for each month number from 1 to 12.
  965. // If no $locale was given, or $locale was invalid, do not use this identity mapping to normalize.
  966. // Otherwise, translate locale aware month names in $number to their numeric equivalents.
  967. $position = false;
  968. if ($monthlist && $monthlist[1] != 1) {
  969. foreach($monthlist as $key => $name) {
  970. if (($position = iconv_strpos($number, $name, 0, 'UTF-8')) !== false) {
  971. $number = str_ireplace($name, $key, $number);
  972. return $position;
  973. }
  974. }
  975. }
  976. return false;
  977. }
  978. /**
  979. * Returns the default date format for $locale.
  980. *
  981. * @param string|Zend_Locale $locale OPTIONAL Locale of $number, possibly in string form (e.g. 'de_AT')
  982. * @return string format
  983. * @throws Zend_Locale_Exception throws an exception when locale data is broken
  984. */
  985. public static function getDateFormat($locale = null)
  986. {
  987. $format = Zend_Locale_Data::getContent($locale, 'date');
  988. if (empty($format)) {
  989. require_once 'Zend/Locale/Exception.php';
  990. throw new Zend_Locale_Exception("failed to receive data from locale $locale");
  991. }
  992. return $format;
  993. }
  994. /**
  995. * Returns an array with the normalized date from an locale date
  996. * a input of 10.01.2006 without a $locale would return:
  997. * array ('day' => 10, 'month' => 1, 'year' => 2006)
  998. * The 'locale' option is only used to convert human readable day
  999. * and month names to their numeric equivalents.
  1000. * The 'format' option allows specification of self-defined date formats,
  1001. * when not using the default format for the 'locale'.
  1002. *
  1003. * @param string $date Date string
  1004. * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.
  1005. * @return array Possible array members: day, month, year, hour, minute, second, fixed, format
  1006. */
  1007. public static function getDate($date, array $options = array())
  1008. {
  1009. $options = self::_checkOptions($options) + self::$_options;
  1010. if (empty($options['date_format'])) {
  1011. $options['format_type'] = 'iso';
  1012. $options['date_format'] = self::getDateFormat($options['locale']);
  1013. }
  1014. return self::_parseDate($date, $options);
  1015. }
  1016. /**
  1017. * Returns if the given datestring contains all date parts from the given format.
  1018. * If no format is given, the default date format from the locale is used
  1019. * If you want to check if the date is a proper date you should use Zend_Date::isDate()
  1020. *
  1021. * @param string $date Date string
  1022. * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.
  1023. * @return boolean
  1024. */
  1025. public static function checkDateFormat($date, array $options = array())
  1026. {
  1027. try {
  1028. $date = self::getDate($date, $options);
  1029. } catch (Exception $e) {
  1030. return false;
  1031. }
  1032. if (empty($options['date_format'])) {
  1033. $options['format_type'] = 'iso';
  1034. $options['date_format'] = self::getDateFormat(isset($options['locale']) ? $options['locale'] : null);
  1035. }
  1036. $options = self::_checkOptions($options) + self::$_options;
  1037. // day expected but not parsed
  1038. if ((iconv_strpos($options['date_format'], 'd', 0, 'UTF-8') !== false) and (!isset($date['day']) or ($date['day'] === ""))) {
  1039. return false;
  1040. }
  1041. // month expected but not parsed
  1042. if ((iconv_strpos($options['date_format'], 'M', 0, 'UTF-8') !== false) and (!isset($date['month']) or ($date['month'] === ""))) {
  1043. return false;
  1044. }
  1045. // year expected but not parsed
  1046. if (((iconv_strpos($options['date_format'], 'Y', 0, 'UTF-8') !== false) or
  1047. (iconv_strpos($options['date_format'], 'y', 0, 'UTF-8') !== false)) and (!isset($date['year']) or ($date['year'] === ""))) {
  1048. return false;
  1049. }
  1050. // second expected but not parsed
  1051. if ((iconv_strpos($options['date_format'], 's', 0, 'UTF-8') !== false) and (!isset($date['second']) or ($date['second'] === ""))) {
  1052. return false;
  1053. }
  1054. // minute expected but not parsed
  1055. if ((iconv_strpos($options['date_format'], 'm', 0, 'UTF-8') !== false) and (!isset($date['minute']) or ($date['minute'] === ""))) {
  1056. return false;
  1057. }
  1058. // hour expected but not parsed
  1059. if (((iconv_strpos($options['date_format'], 'H', 0, 'UTF-8') !== false) or
  1060. (iconv_strpos($options['date_for…

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