2
0

Format.php 49 KB

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