PageRenderTime 55ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/website/library/Zend/Locale/Format.php

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

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