RuleRegistry.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. } // end func registerRule
  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. list($class, $path) = $GLOBALS['_HTML_QuickForm_registered_rules'][$ruleName];
  114. if (!isset($this->_rules[$class])) {
  115. if (!empty($path)) {
  116. include_once($path);
  117. }
  118. // Modified by Ivan Tcholakov, 16-MAR-2010. Suppressing a deprecation warning on PHP 5.3
  119. //$this->_rules[$class] =& new $class();
  120. $this->_rules[$class] = new $class();
  121. //
  122. }
  123. $this->_rules[$class]->setName($ruleName);
  124. return $this->_rules[$class];
  125. } // end func getRule
  126. /**
  127. * Performs validation on the given values
  128. *
  129. * @param string $ruleName Name of the rule to be used
  130. * @param mixed $values Can be a scalar or an array of values
  131. * to be validated
  132. * @param mixed $options Options used by the rule
  133. * @param mixed $multiple Whether to validate an array of values altogether
  134. * @access public
  135. * @return mixed true if no error found, int of valid values (when an array of values is given) or false if error
  136. */
  137. function validate($ruleName, $values, $options = null, $multiple = false)
  138. {
  139. $rule =& $this->getRule($ruleName);
  140. if (is_array($values) && !$multiple) {
  141. $result = 0;
  142. foreach ($values as $value) {
  143. if ($rule->validate($value, $options) === true) {
  144. $result++;
  145. }
  146. }
  147. return ($result == 0) ? false : $result;
  148. } else {
  149. return $rule->validate($values, $options);
  150. }
  151. } // end func validate
  152. /**
  153. * Returns the validation test in javascript code
  154. *
  155. * @param array|HTML_QuickForm_element Element(s) the rule applies to
  156. * @param string Element name, in case $element is
  157. * not an array
  158. * @param array Rule data
  159. * @access public
  160. * @return string JavaScript for the rule
  161. */
  162. function getValidationScript(&$element, $elementName, $ruleData)
  163. {
  164. $reset = (isset($ruleData['reset'])) ? $ruleData['reset'] : false;
  165. $rule =& $this->getRule($ruleData['type']);
  166. if (!is_array($element)) {
  167. list($jsValue, $jsReset) = $this->_getJsValue($element, $elementName, $reset, null);
  168. } else {
  169. $jsValue = " value = new Array();\n";
  170. $jsReset = '';
  171. for ($i = 0; $i < count($element); $i++) {
  172. list($tmp_value, $tmp_reset) = $this->_getJsValue($element[$i], $element[$i]->getName(), $reset, $i);
  173. $jsValue .= "\n" . $tmp_value;
  174. $jsReset .= $tmp_reset;
  175. }
  176. }
  177. $jsField = isset($ruleData['group'])? $ruleData['group']: $elementName;
  178. list ($jsPrefix, $jsCheck) = $rule->getValidationScript($ruleData['format']);
  179. if (!isset($ruleData['howmany'])) {
  180. $js = $jsValue . "\n" . $jsPrefix .
  181. " if (" . str_replace('{jsVar}', 'value', $jsCheck) . " && !errFlag['{$jsField}']) {\n" .
  182. " errFlag['{$jsField}'] = true;\n" .
  183. " _qfMsg = _qfMsg + '\\n - {$ruleData['message']}';\n" .
  184. $jsReset .
  185. " }\n";
  186. } else {
  187. $js = $jsValue . "\n" . $jsPrefix .
  188. " var res = 0;\n" .
  189. " for (var i = 0; i < value.length; i++) {\n" .
  190. " if (!(" . str_replace('{jsVar}', 'value[i]', $jsCheck) . ")) {\n" .
  191. " res++;\n" .
  192. " }\n" .
  193. " }\n" .
  194. " if (res < {$ruleData['howmany']} && !errFlag['{$jsField}']) {\n" .
  195. " errFlag['{$jsField}'] = true;\n" .
  196. " _qfMsg = _qfMsg + '\\n - {$ruleData['message']}';\n" .
  197. $jsReset .
  198. " }\n";
  199. }
  200. return $js;
  201. } // end func getValidationScript
  202. /**
  203. * Returns JavaScript to get and to reset the element's value
  204. *
  205. * @access private
  206. * @param HTML_QuickForm_element element being processed
  207. * @param string element's name
  208. * @param bool whether to generate JavaScript to reset
  209. * the value
  210. * @param integer value's index in the array (only used for
  211. * multielement rules)
  212. * @return array first item is value javascript, second is reset
  213. */
  214. function _getJsValue(&$element, $elementName, $reset = false, $index = null)
  215. {
  216. $jsIndex = isset($index)? '[' . $index . ']': '';
  217. $tmp_reset = $reset? " var field = frm.elements['$elementName'];\n": '';
  218. if (is_a($element, 'html_quickform_group')) {
  219. $value = " _qfGroups['{$elementName}'] = {";
  220. $elements =& $element->getElements();
  221. for ($i = 0, $count = count($elements); $i < $count; $i++) {
  222. $append = ($elements[$i]->getType() == 'select' && $elements[$i]->getMultiple())? '[]': '';
  223. $value .= "'" . $element->getElementName($i) . $append . "': true" .
  224. ($i < $count - 1? ', ': '');
  225. }
  226. $value .=
  227. "};\n" .
  228. " value{$jsIndex} = new Array();\n" .
  229. " var valueIdx = 0;\n" .
  230. " for (var i = 0; i < frm.elements.length; i++) {\n" .
  231. " var _element = frm.elements[i];\n" .
  232. " if (_element.name in _qfGroups['{$elementName}']) {\n" .
  233. " switch (_element.type) {\n" .
  234. " case 'checkbox':\n" .
  235. " case 'radio':\n" .
  236. " if (_element.checked) {\n" .
  237. " value{$jsIndex}[valueIdx++] = _element.value;\n" .
  238. " }\n" .
  239. " break;\n" .
  240. " case 'select-one':\n" .
  241. " if (-1 != _element.selectedIndex) {\n" .
  242. " value{$jsIndex}[valueIdx++] = _element.options[_element.selectedIndex].value;\n" .
  243. " }\n" .
  244. " break;\n" .
  245. " case 'select-multiple':\n" .
  246. " var tmpVal = new Array();\n" .
  247. " var tmpIdx = 0;\n" .
  248. " for (var j = 0; j < _element.options.length; j++) {\n" .
  249. " if (_element.options[j].selected) {\n" .
  250. " tmpVal[tmpIdx++] = _element.options[j].value;\n" .
  251. " }\n" .
  252. " }\n" .
  253. " if (tmpIdx > 0) {\n" .
  254. " value{$jsIndex}[valueIdx++] = tmpVal;\n" .
  255. " }\n" .
  256. " break;\n" .
  257. " default:\n" .
  258. " value{$jsIndex}[valueIdx++] = _element.value;\n" .
  259. " }\n" .
  260. " }\n" .
  261. " }\n";
  262. if ($reset) {
  263. $tmp_reset =
  264. " for (var i = 0; i < frm.elements.length; i++) {\n" .
  265. " var _element = frm.elements[i];\n" .
  266. " if (_element.name in _qfGroups['{$elementName}']) {\n" .
  267. " switch (_element.type) {\n" .
  268. " case 'checkbox':\n" .
  269. " case 'radio':\n" .
  270. " _element.checked = _element.defaultChecked;\n" .
  271. " break;\n" .
  272. " case 'select-one':\n" .
  273. " case 'select-multiple':\n" .
  274. " for (var j = 0; j < _element.options.length; j++) {\n" .
  275. " _element.options[j].selected = _element.options[j].defaultSelected;\n" .
  276. " }\n" .
  277. " break;\n" .
  278. " default:\n" .
  279. " _element.value = _element.defaultValue;\n" .
  280. " }\n" .
  281. " }\n" .
  282. " }\n";
  283. }
  284. } elseif ($element->getType() == 'select') {
  285. if ($element->getMultiple()) {
  286. $elementName .= '[]';
  287. $value =
  288. " value{$jsIndex} = new Array();\n" .
  289. " var valueIdx = 0;\n" .
  290. " for (var i = 0; i < frm.elements['{$elementName}'].options.length; i++) {\n" .
  291. " if (frm.elements['{$elementName}'].options[i].selected) {\n" .
  292. " value{$jsIndex}[valueIdx++] = frm.elements['{$elementName}'].options[i].value;\n" .
  293. " }\n" .
  294. " }\n";
  295. } else {
  296. $value = " value{$jsIndex} = frm.elements['{$elementName}'].selectedIndex == -1? '': frm.elements['{$elementName}'].options[frm.elements['{$elementName}'].selectedIndex].value;\n";
  297. }
  298. if ($reset) {
  299. $tmp_reset .=
  300. " for (var i = 0; i < field.options.length; i++) {\n" .
  301. " field.options[i].selected = field.options[i].defaultSelected;\n" .
  302. " }\n";
  303. }
  304. } elseif ($element->getType() == 'checkbox') {
  305. if (is_a($element, 'html_quickform_advcheckbox')) {
  306. $value = " value{$jsIndex} = frm.elements['$elementName'][1].checked? frm.elements['$elementName'][1].value: frm.elements['$elementName'][0].value;\n";
  307. $tmp_reset .= $reset ? " field[1].checked = field[1].defaultChecked;\n" : '';
  308. } else {
  309. $value = " value{$jsIndex} = frm.elements['$elementName'].checked? '1': '';\n";
  310. $tmp_reset .= $reset ? " field.checked = field.defaultChecked;\n" : '';
  311. }
  312. } elseif ($element->getType() == 'radio') {
  313. $value = " value{$jsIndex} = '';\n" .
  314. // Fix for bug #5644
  315. " var els = 'length' in frm.elements['$elementName']? frm.elements['$elementName']: [ frm.elements['$elementName'] ];\n" .
  316. " for (var i = 0; i < els.length; i++) {\n" .
  317. " if (els[i].checked) {\n" .
  318. " value{$jsIndex} = els[i].value;\n" .
  319. " }\n" .
  320. " }";
  321. if ($reset) {
  322. $tmp_reset .= " for (var i = 0; i < field.length; i++) {\n" .
  323. " field[i].checked = field[i].defaultChecked;\n" .
  324. " }";
  325. }
  326. } else {
  327. $value = " value{$jsIndex} = frm.elements['$elementName'].value;";
  328. $tmp_reset .= ($reset) ? " field.value = field.defaultValue;\n" : '';
  329. }
  330. return array($value, $tmp_reset);
  331. }
  332. } // end class HTML_QuickForm_RuleRegistry
  333. ?>