RuleRegistry.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * Registers rule objects and uses them for validation
  5. *
  6. * PHP versions 4 and 5
  7. *
  8. * LICENSE: This source file is subject to version 3.01 of the PHP license
  9. * that is available through the world-wide-web at the following URI:
  10. * http://www.php.net/license/3_01.txt If you did not receive a copy of
  11. * the PHP License and are unable to obtain it through the web, please
  12. * send a note to license@php.net so we can mail you a copy immediately.
  13. *
  14. * @category HTML
  15. * @package HTML_QuickForm
  16. * @author Adam Daniel <adaniel1@eesus.jnj.com>
  17. * @author Bertrand Mansion <bmansion@mamasam.com>
  18. * @author Alexey Borzov <avb@php.net>
  19. * @copyright 2001-2009 The PHP Group
  20. * @license http://www.php.net/license/3_01.txt PHP License 3.01
  21. * @version CVS: $Id: RuleRegistry.php,v 1.19 2009/04/04 21:34:02 avb Exp $
  22. * @link http://pear.php.net/package/HTML_QuickForm
  23. */
  24. /**
  25. * Registers rule objects and uses them for validation
  26. *
  27. * @category HTML
  28. * @package HTML_QuickForm
  29. * @author Adam Daniel <adaniel1@eesus.jnj.com>
  30. * @author Bertrand Mansion <bmansion@mamasam.com>
  31. * @author Alexey Borzov <avb@php.net>
  32. * @version Release: 3.2.11
  33. * @since 3.2
  34. */
  35. class HTML_QuickForm_RuleRegistry
  36. {
  37. /**
  38. * Array containing references to used rules
  39. * @var array
  40. * @access private
  41. */
  42. var $_rules = array();
  43. /**
  44. * Returns a singleton of HTML_QuickForm_RuleRegistry
  45. *
  46. * Usually, only one RuleRegistry object is needed, this is the reason
  47. * why it is recommended to use this method to get the validation object.
  48. *
  49. * @access public
  50. * @static
  51. * @return HTML_QuickForm_RuleRegistry
  52. */
  53. static function &singleton()
  54. {
  55. static $obj;
  56. if (!isset($obj)) {
  57. $obj = new HTML_QuickForm_RuleRegistry();
  58. }
  59. return $obj;
  60. } // end func singleton
  61. /**
  62. * Registers a new validation rule
  63. *
  64. * In order to use a custom rule in your form, you need to register it
  65. * first. For regular expressions, one can directly use the 'regex' type
  66. * rule in addRule(), this is faster than registering the rule.
  67. *
  68. * Functions and methods can be registered. Use the 'function' type.
  69. * When registering a method, specify the class name as second parameter.
  70. *
  71. * You can also register an HTML_QuickForm_Rule subclass with its own
  72. * validate() method.
  73. *
  74. * @param string $ruleName Name of validation rule
  75. * @param string $type Either: 'regex', 'function' or null
  76. * @param string $data1 Name of function, regular expression or
  77. * HTML_QuickForm_Rule object class name
  78. * @param string $data2 Object parent of above function or HTML_QuickForm_Rule file path
  79. * @access public
  80. * @return void
  81. */
  82. function registerRule($ruleName, $type, $data1, $data2 = null)
  83. {
  84. $type = strtolower($type);
  85. if ($type == 'regex') {
  86. // Regular expression
  87. $rule =& $this->getRule('regex');
  88. $rule->addData($ruleName, $data1);
  89. //$GLOBALS['_HTML_QuickForm_registered_rules'][$ruleName] = $GLOBALS['_HTML_QuickForm_registered_rules']['regex'];
  90. } elseif ($type == 'function' || $type == 'callback') {
  91. // Callback function
  92. $rule =& $this->getRule('callback');
  93. $rule->addData($ruleName, $data1, $data2, 'function' == $type);
  94. //$GLOBALS['_HTML_QuickForm_registered_rules'][$ruleName] = $GLOBALS['_HTML_QuickForm_registered_rules']['callback'];
  95. } elseif (is_object($data1)) {
  96. // An instance of HTML_QuickForm_Rule
  97. $this->_rules[strtolower(get_class($data1))] = $data1;
  98. //$GLOBALS['_HTML_QuickForm_registered_rules'][$ruleName] = array(strtolower(get_class($data1)), null);
  99. } else {
  100. // Rule class name
  101. //$GLOBALS['_HTML_QuickForm_registered_rules'][$ruleName] = array(strtolower($data1), $data2);
  102. }
  103. }
  104. /**
  105. * Returns a reference to the requested rule object
  106. *
  107. * @param string $ruleName Name of the requested rule
  108. * @access public
  109. * @return HTML_QuickForm_Rule
  110. */
  111. function &getRule($ruleName)
  112. {
  113. if (empty($ruleName)) {
  114. return false;
  115. }
  116. $rules = array(
  117. 'required' => 'HTML_QuickForm_Rule_Required',
  118. 'maxlength' => 'HTML_QuickForm_Rule_Range',
  119. 'minlength' => 'HTML_QuickForm_Rule_Range',
  120. 'rangelength' => 'HTML_QuickForm_Rule_Range',
  121. 'email' => 'HTML_QuickForm_Rule_Email',
  122. 'regex' => 'HTML_QuickForm_Rule_Regex',
  123. 'lettersonly' => 'HTML_QuickForm_Rule_Regex',
  124. 'alphanumeric' => 'HTML_QuickForm_Rule_Regex',
  125. 'numeric' => 'HTML_QuickForm_Rule_Regex',
  126. 'nopunctuation' => 'HTML_QuickForm_Rule_Regex',
  127. 'nonzero' => 'HTML_QuickForm_Rule_Regex',
  128. 'callback' => 'HTML_QuickForm_Rule_Callback',
  129. 'compare' => 'HTML_QuickForm_Rule_Compare',
  130. 'date_compare' => 'HTML_QuickForm_Rule_DateCompare',
  131. 'comparedate' => 'HTML_QuickForm_Rule_CompareDate',
  132. 'errordate' => 'Html_Quickform_Rule_Date',
  133. 'captcha' => 'HTML_QuickForm_Rule_CAPTCHA',
  134. 'filetype' => 'HTML_QuickForm_Rule_Filetype',
  135. 'mobile_phone_number' => 'HTML_QuickForm_Rule_Mobile_Phone_Number',
  136. 'url' => 'HTML_QuickForm_Rule_Url',
  137. 'username' => 'HTML_QuickForm_Rule_Username',
  138. 'multiple_required' => 'HTML_QuickForm_Rule_MultipleRequired',
  139. 'datetime' => 'DateTimeRule',
  140. 'username_available' => 'HTML_QuickForm_Rule_UsernameAvailable',
  141. 'compare_fields' => 'HTML_QuickForm_Compare_Fields',
  142. 'html' => 'HTML_QuickForm_Rule_HTML',
  143. 'CAPTCHA' => 'HTML_QuickForm_Rule_CAPTCHA',
  144. 'date' => 'HTML_QuickForm_Rule_Date',
  145. 'compare_datetime_text' => 'HTML_QuickForm_Rule_CompareDateTimeText',
  146. 'uploadedfile' => 'HTML_QuickForm_Rule_UploadFile',
  147. 'maxfilesize', 'HTML_QuickForm_Rule_MaxFileSize',
  148. 'mimetype', 'HTML_QuickForm_Rule_MimeType',
  149. 'filename', 'HTML_QuickForm_Rule_FileName'
  150. );
  151. $class = $rules[$ruleName];
  152. if (empty($class)) {
  153. return false;
  154. }
  155. if (!isset($this->_rules[$class])) {
  156. $this->_rules[$class] = new $class();
  157. }
  158. $this->_rules[$class]->setName($ruleName);
  159. return $this->_rules[$class];
  160. }
  161. /**
  162. * Performs validation on the given values
  163. *
  164. * @param string $ruleName Name of the rule to be used
  165. * @param mixed $values Can be a scalar or an array of values
  166. * to be validated
  167. * @param mixed $options Options used by the rule
  168. * @param mixed $multiple Whether to validate an array of values altogether
  169. * @access public
  170. * @return mixed true if no error found, int of valid values (when an array of values is given) or false if error
  171. */
  172. function validate($ruleName, $values, $options = null, $multiple = false)
  173. {
  174. $rule =& $this->getRule($ruleName);
  175. if (is_array($values) && !$multiple) {
  176. $result = 0;
  177. foreach ($values as $value) {
  178. if ($rule->validate($value, $options) === true) {
  179. $result++;
  180. }
  181. }
  182. return ($result == 0) ? false : $result;
  183. } else {
  184. return $rule->validate($values, $options);
  185. }
  186. } // end func validate
  187. /**
  188. * Returns the validation test in javascript code
  189. *
  190. * @param array|HTML_QuickForm_element Element(s) the rule applies to
  191. * @param string Element name, in case $element is
  192. * not an array
  193. * @param array Rule data
  194. * @access public
  195. * @return string JavaScript for the rule
  196. */
  197. function getValidationScript(&$element, $elementName, $ruleData)
  198. {
  199. $reset = (isset($ruleData['reset'])) ? $ruleData['reset'] : false;
  200. $rule =& $this->getRule($ruleData['type']);
  201. if (!is_array($element)) {
  202. list($jsValue, $jsReset) = $this->_getJsValue($element, $elementName, $reset, null);
  203. } else {
  204. $jsValue = " value = new Array();\n";
  205. $jsReset = '';
  206. for ($i = 0; $i < count($element); $i++) {
  207. list($tmp_value, $tmp_reset) = $this->_getJsValue($element[$i], $element[$i]->getName(), $reset, $i);
  208. $jsValue .= "\n" . $tmp_value;
  209. $jsReset .= $tmp_reset;
  210. }
  211. }
  212. $jsField = isset($ruleData['group'])? $ruleData['group']: $elementName;
  213. list ($jsPrefix, $jsCheck) = $rule->getValidationScript($ruleData['format']);
  214. if (!isset($ruleData['howmany'])) {
  215. $js = $jsValue . "\n" . $jsPrefix .
  216. " if (" . str_replace('{jsVar}', 'value', $jsCheck) . " && !errFlag['{$jsField}']) {\n" .
  217. " errFlag['{$jsField}'] = true;\n" .
  218. " _qfMsg = _qfMsg + '\\n - {$ruleData['message']}';\n" .
  219. $jsReset .
  220. " }\n";
  221. } else {
  222. $js = $jsValue . "\n" . $jsPrefix .
  223. " var res = 0;\n" .
  224. " for (var i = 0; i < value.length; i++) {\n" .
  225. " if (!(" . str_replace('{jsVar}', 'value[i]', $jsCheck) . ")) {\n" .
  226. " res++;\n" .
  227. " }\n" .
  228. " }\n" .
  229. " if (res < {$ruleData['howmany']} && !errFlag['{$jsField}']) {\n" .
  230. " errFlag['{$jsField}'] = true;\n" .
  231. " _qfMsg = _qfMsg + '\\n - {$ruleData['message']}';\n" .
  232. $jsReset .
  233. " }\n";
  234. }
  235. return $js;
  236. } // end func getValidationScript
  237. /**
  238. * Returns JavaScript to get and to reset the element's value
  239. *
  240. * @access private
  241. * @param HTML_QuickForm_element element being processed
  242. * @param string element's name
  243. * @param bool whether to generate JavaScript to reset
  244. * the value
  245. * @param integer value's index in the array (only used for
  246. * multielement rules)
  247. * @return array first item is value javascript, second is reset
  248. */
  249. function _getJsValue(&$element, $elementName, $reset = false, $index = null)
  250. {
  251. $jsIndex = isset($index)? '[' . $index . ']': '';
  252. $tmp_reset = $reset? " var field = frm.elements['$elementName'];\n": '';
  253. if (is_a($element, 'html_quickform_group')) {
  254. $value = " _qfGroups['{$elementName}'] = {";
  255. $elements =& $element->getElements();
  256. for ($i = 0, $count = count($elements); $i < $count; $i++) {
  257. $append = ($elements[$i]->getType() == 'select' && $elements[$i]->getMultiple())? '[]': '';
  258. $value .= "'" . $element->getElementName($i) . $append . "': true" .
  259. ($i < $count - 1? ', ': '');
  260. }
  261. $value .=
  262. "};\n" .
  263. " value{$jsIndex} = new Array();\n" .
  264. " var valueIdx = 0;\n" .
  265. " for (var i = 0; i < frm.elements.length; i++) {\n" .
  266. " var _element = frm.elements[i];\n" .
  267. " if (_element.name in _qfGroups['{$elementName}']) {\n" .
  268. " switch (_element.type) {\n" .
  269. " case 'checkbox':\n" .
  270. " case 'radio':\n" .
  271. " if (_element.checked) {\n" .
  272. " value{$jsIndex}[valueIdx++] = _element.value;\n" .
  273. " }\n" .
  274. " break;\n" .
  275. " case 'select-one':\n" .
  276. " if (-1 != _element.selectedIndex) {\n" .
  277. " value{$jsIndex}[valueIdx++] = _element.options[_element.selectedIndex].value;\n" .
  278. " }\n" .
  279. " break;\n" .
  280. " case 'select-multiple':\n" .
  281. " var tmpVal = new Array();\n" .
  282. " var tmpIdx = 0;\n" .
  283. " for (var j = 0; j < _element.options.length; j++) {\n" .
  284. " if (_element.options[j].selected) {\n" .
  285. " tmpVal[tmpIdx++] = _element.options[j].value;\n" .
  286. " }\n" .
  287. " }\n" .
  288. " if (tmpIdx > 0) {\n" .
  289. " value{$jsIndex}[valueIdx++] = tmpVal;\n" .
  290. " }\n" .
  291. " break;\n" .
  292. " default:\n" .
  293. " value{$jsIndex}[valueIdx++] = _element.value;\n" .
  294. " }\n" .
  295. " }\n" .
  296. " }\n";
  297. if ($reset) {
  298. $tmp_reset =
  299. " for (var i = 0; i < frm.elements.length; i++) {\n" .
  300. " var _element = frm.elements[i];\n" .
  301. " if (_element.name in _qfGroups['{$elementName}']) {\n" .
  302. " switch (_element.type) {\n" .
  303. " case 'checkbox':\n" .
  304. " case 'radio':\n" .
  305. " _element.checked = _element.defaultChecked;\n" .
  306. " break;\n" .
  307. " case 'select-one':\n" .
  308. " case 'select-multiple':\n" .
  309. " for (var j = 0; j < _element.options.length; j++) {\n" .
  310. " _element.options[j].selected = _element.options[j].defaultSelected;\n" .
  311. " }\n" .
  312. " break;\n" .
  313. " default:\n" .
  314. " _element.value = _element.defaultValue;\n" .
  315. " }\n" .
  316. " }\n" .
  317. " }\n";
  318. }
  319. } elseif ($element->getType() == 'select') {
  320. if ($element->getMultiple()) {
  321. $elementName .= '[]';
  322. $value =
  323. " value{$jsIndex} = new Array();\n" .
  324. " var valueIdx = 0;\n" .
  325. " for (var i = 0; i < frm.elements['{$elementName}'].options.length; i++) {\n" .
  326. " if (frm.elements['{$elementName}'].options[i].selected) {\n" .
  327. " value{$jsIndex}[valueIdx++] = frm.elements['{$elementName}'].options[i].value;\n" .
  328. " }\n" .
  329. " }\n";
  330. } else {
  331. $value = " value{$jsIndex} = frm.elements['{$elementName}'].selectedIndex == -1? '': frm.elements['{$elementName}'].options[frm.elements['{$elementName}'].selectedIndex].value;\n";
  332. }
  333. if ($reset) {
  334. $tmp_reset .=
  335. " for (var i = 0; i < field.options.length; i++) {\n" .
  336. " field.options[i].selected = field.options[i].defaultSelected;\n" .
  337. " }\n";
  338. }
  339. } elseif ($element->getType() == 'checkbox') {
  340. if (is_a($element, 'html_quickform_advcheckbox')) {
  341. $value = " value{$jsIndex} = frm.elements['$elementName'][1].checked? frm.elements['$elementName'][1].value: frm.elements['$elementName'][0].value;\n";
  342. $tmp_reset .= $reset ? " field[1].checked = field[1].defaultChecked;\n" : '';
  343. } else {
  344. $value = " value{$jsIndex} = frm.elements['$elementName'].checked? '1': '';\n";
  345. $tmp_reset .= $reset ? " field.checked = field.defaultChecked;\n" : '';
  346. }
  347. } elseif ($element->getType() == 'radio') {
  348. $value = " value{$jsIndex} = '';\n" .
  349. // Fix for bug #5644
  350. " var els = 'length' in frm.elements['$elementName']? frm.elements['$elementName']: [ frm.elements['$elementName'] ];\n" .
  351. " for (var i = 0; i < els.length; i++) {\n" .
  352. " if (els[i].checked) {\n" .
  353. " value{$jsIndex} = els[i].value;\n" .
  354. " }\n" .
  355. " }";
  356. if ($reset) {
  357. $tmp_reset .= " for (var i = 0; i < field.length; i++) {\n" .
  358. " field[i].checked = field[i].defaultChecked;\n" .
  359. " }";
  360. }
  361. } else {
  362. $value = " value{$jsIndex} = frm.elements['$elementName'].value;";
  363. $tmp_reset .= ($reset) ? " field.value = field.defaultValue;\n" : '';
  364. }
  365. return array($value, $tmp_reset);
  366. }
  367. } // end class HTML_QuickForm_RuleRegistry
  368. ?>