RuleRegistry.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. public 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. } elseif ($type == 'function' || $type == 'callback') {
  90. // Callback function
  91. $rule = $this->getRule('callback');
  92. $rule->addData($ruleName, $data1, $data2, 'function' == $type);
  93. } elseif (is_object($data1)) {
  94. // An instance of HTML_QuickForm_Rule
  95. $this->_rules[strtolower(get_class($data1))] = $data1;
  96. }
  97. }
  98. /**
  99. * Returns a reference to the requested rule object
  100. *
  101. * @param string $ruleName Name of the requested rule
  102. * @access public
  103. * @return HTML_QuickForm_Rule
  104. */
  105. public function getRule($ruleName)
  106. {
  107. if (empty($ruleName)) {
  108. return false;
  109. }
  110. $rules = array(
  111. 'required' => 'HTML_QuickForm_Rule_Required',
  112. 'maxlength' => 'HTML_QuickForm_Rule_Range',
  113. 'minlength' => 'HTML_QuickForm_Rule_Range',
  114. 'max_numeric_length' => 'HTML_QuickForm_Rule_Range',
  115. 'min_numeric_length' => 'HTML_QuickForm_Rule_Range',
  116. 'rangelength' => 'HTML_QuickForm_Rule_Range',
  117. 'email' => 'HTML_QuickForm_Rule_Email',
  118. 'regex' => 'HTML_QuickForm_Rule_Regex',
  119. 'lettersonly' => 'HTML_QuickForm_Rule_Regex',
  120. 'alphanumeric' => 'HTML_QuickForm_Rule_Regex',
  121. 'numeric' => 'HTML_QuickForm_Rule_Regex',
  122. 'nopunctuation' => 'HTML_QuickForm_Rule_Regex',
  123. 'nonzero' => 'HTML_QuickForm_Rule_Regex',
  124. 'callback' => 'HTML_QuickForm_Rule_Callback',
  125. 'compare' => 'HTML_QuickForm_Rule_Compare',
  126. 'date_compare' => 'HTML_QuickForm_Rule_DateCompare',
  127. 'comparedate' => 'HTML_QuickForm_Rule_CompareDate',
  128. 'errordate' => 'Html_Quickform_Rule_Date',
  129. 'captcha' => 'HTML_QuickForm_Rule_CAPTCHA',
  130. 'filetype' => 'HTML_QuickForm_Rule_Filetype',
  131. 'mobile_phone_number' => 'HTML_QuickForm_Rule_Mobile_Phone_Number',
  132. 'url' => 'HTML_QuickForm_Rule_Url',
  133. 'username' => 'HTML_QuickForm_Rule_Username',
  134. 'multiple_required' => 'HTML_QuickForm_Rule_MultipleRequired',
  135. 'datetime' => 'DateTimeRule',
  136. 'username_available' => 'HTML_QuickForm_Rule_UsernameAvailable',
  137. 'compare_fields' => 'HTML_QuickForm_Compare_Fields',
  138. 'html' => 'HTML_QuickForm_Rule_HTML',
  139. 'CAPTCHA' => 'HTML_QuickForm_Rule_CAPTCHA',
  140. 'date' => 'HTML_QuickForm_Rule_Date',
  141. 'compare_datetime_text' => 'HTML_QuickForm_Rule_CompareDateTimeText',
  142. 'uploadedfile' => 'HTML_QuickForm_Rule_UploadFile',
  143. 'maxfilesize', 'HTML_QuickForm_Rule_MaxFileSize',
  144. 'mimetype', 'HTML_QuickForm_Rule_MimeType',
  145. 'filename', 'HTML_QuickForm_Rule_FileName',
  146. 'validquestiontype' => 'HTML_QuickForm_Rule_QuestionType',
  147. 'mintext' => 'Html_Quickform_Rule_MinText'
  148. );
  149. $class = $rules[$ruleName];
  150. if (empty($class)) {
  151. return false;
  152. }
  153. if (!isset($this->_rules[$class])) {
  154. $this->_rules[$class] = new $class();
  155. }
  156. $this->_rules[$class]->setName($ruleName);
  157. return $this->_rules[$class];
  158. }
  159. /**
  160. * Performs validation on the given values
  161. *
  162. * @param string $ruleName Name of the rule to be used
  163. * @param mixed $values Can be a scalar or an array of values
  164. * to be validated
  165. * @param mixed $options Options used by the rule
  166. * @param mixed $multiple Whether to validate an array of values altogether
  167. * @access public
  168. * @return mixed true if no error found, int of valid values (when an array of values is given) or false if error
  169. */
  170. function validate($ruleName, $values, $options = null, $multiple = false)
  171. {
  172. $rule = $this->getRule($ruleName);
  173. if (is_array($values) && !$multiple) {
  174. $result = 0;
  175. foreach ($values as $value) {
  176. if ($rule->validate($value, $options) === true) {
  177. $result++;
  178. }
  179. }
  180. return ($result == 0) ? false : $result;
  181. } else {
  182. return $rule->validate($values, $options);
  183. }
  184. } // end func validate
  185. /**
  186. * Returns the validation test in javascript code
  187. *
  188. * @param array|HTML_QuickForm_element Element(s) the rule applies to
  189. * @param string Element name, in case $element is
  190. * not an array
  191. * @param array Rule data
  192. * @access public
  193. * @return string JavaScript for the rule
  194. */
  195. function getValidationScript(&$element, $elementName, $ruleData)
  196. {
  197. $reset = (isset($ruleData['reset'])) ? $ruleData['reset'] : false;
  198. $rule = $this->getRule($ruleData['type']);
  199. if (!is_array($element)) {
  200. list($jsValue, $jsReset) = $this->_getJsValue($element, $elementName, $reset, null);
  201. } else {
  202. $jsValue = " value = new Array();\n";
  203. $jsReset = '';
  204. for ($i = 0; $i < count($element); $i++) {
  205. list($tmp_value, $tmp_reset) = $this->_getJsValue($element[$i], $element[$i]->getName(), $reset, $i);
  206. $jsValue .= "\n" . $tmp_value;
  207. $jsReset .= $tmp_reset;
  208. }
  209. }
  210. $jsField = isset($ruleData['group'])? $ruleData['group']: $elementName;
  211. list ($jsPrefix, $jsCheck) = $rule->getValidationScript($ruleData['format']);
  212. if (!isset($ruleData['howmany'])) {
  213. $js = $jsValue . "\n" . $jsPrefix .
  214. " if (" . str_replace('{jsVar}', 'value', $jsCheck) . " && !errFlag['{$jsField}']) {\n" .
  215. " errFlag['{$jsField}'] = true;\n" .
  216. " _qfMsg = _qfMsg + '\\n - {$ruleData['message']}';\n" .
  217. $jsReset .
  218. " }\n";
  219. } else {
  220. $js = $jsValue . "\n" . $jsPrefix .
  221. " var res = 0;\n" .
  222. " for (var i = 0; i < value.length; i++) {\n" .
  223. " if (!(" . str_replace('{jsVar}', 'value[i]', $jsCheck) . ")) {\n" .
  224. " res++;\n" .
  225. " }\n" .
  226. " }\n" .
  227. " if (res < {$ruleData['howmany']} && !errFlag['{$jsField}']) {\n" .
  228. " errFlag['{$jsField}'] = true;\n" .
  229. " _qfMsg = _qfMsg + '\\n - {$ruleData['message']}';\n" .
  230. $jsReset .
  231. " }\n";
  232. }
  233. return $js;
  234. } // end func getValidationScript
  235. /**
  236. * Returns JavaScript to get and to reset the element's value
  237. *
  238. * @access private
  239. * @param HTML_QuickForm_element element being processed
  240. * @param string element's name
  241. * @param bool whether to generate JavaScript to reset
  242. * the value
  243. * @param integer value's index in the array (only used for
  244. * multielement rules)
  245. * @return array first item is value javascript, second is reset
  246. */
  247. function _getJsValue(&$element, $elementName, $reset = false, $index = null)
  248. {
  249. $jsIndex = isset($index)? '[' . $index . ']': '';
  250. $tmp_reset = $reset? " var field = frm.elements['$elementName'];\n": '';
  251. if (is_a($element, 'html_quickform_group')) {
  252. $value = " _qfGroups['{$elementName}'] = {";
  253. $elements =& $element->getElements();
  254. for ($i = 0, $count = count($elements); $i < $count; $i++) {
  255. $append = ($elements[$i]->getType() == 'select' && $elements[$i]->getMultiple())? '[]': '';
  256. $value .= "'" . $element->getElementName($i) . $append . "': true" .
  257. ($i < $count - 1? ', ': '');
  258. }
  259. $value .=
  260. "};\n" .
  261. " value{$jsIndex} = new Array();\n" .
  262. " var valueIdx = 0;\n" .
  263. " for (var i = 0; i < frm.elements.length; i++) {\n" .
  264. " var _element = frm.elements[i];\n" .
  265. " if (_element.name in _qfGroups['{$elementName}']) {\n" .
  266. " switch (_element.type) {\n" .
  267. " case 'checkbox':\n" .
  268. " case 'radio':\n" .
  269. " if (_element.checked) {\n" .
  270. " value{$jsIndex}[valueIdx++] = _element.value;\n" .
  271. " }\n" .
  272. " break;\n" .
  273. " case 'select-one':\n" .
  274. " if (-1 != _element.selectedIndex) {\n" .
  275. " value{$jsIndex}[valueIdx++] = _element.options[_element.selectedIndex].value;\n" .
  276. " }\n" .
  277. " break;\n" .
  278. " case 'select-multiple':\n" .
  279. " var tmpVal = new Array();\n" .
  280. " var tmpIdx = 0;\n" .
  281. " for (var j = 0; j < _element.options.length; j++) {\n" .
  282. " if (_element.options[j].selected) {\n" .
  283. " tmpVal[tmpIdx++] = _element.options[j].value;\n" .
  284. " }\n" .
  285. " }\n" .
  286. " if (tmpIdx > 0) {\n" .
  287. " value{$jsIndex}[valueIdx++] = tmpVal;\n" .
  288. " }\n" .
  289. " break;\n" .
  290. " default:\n" .
  291. " value{$jsIndex}[valueIdx++] = _element.value;\n" .
  292. " }\n" .
  293. " }\n" .
  294. " }\n";
  295. if ($reset) {
  296. $tmp_reset =
  297. " for (var i = 0; i < frm.elements.length; i++) {\n" .
  298. " var _element = frm.elements[i];\n" .
  299. " if (_element.name in _qfGroups['{$elementName}']) {\n" .
  300. " switch (_element.type) {\n" .
  301. " case 'checkbox':\n" .
  302. " case 'radio':\n" .
  303. " _element.checked = _element.defaultChecked;\n" .
  304. " break;\n" .
  305. " case 'select-one':\n" .
  306. " case 'select-multiple':\n" .
  307. " for (var j = 0; j < _element.options.length; j++) {\n" .
  308. " _element.options[j].selected = _element.options[j].defaultSelected;\n" .
  309. " }\n" .
  310. " break;\n" .
  311. " default:\n" .
  312. " _element.value = _element.defaultValue;\n" .
  313. " }\n" .
  314. " }\n" .
  315. " }\n";
  316. }
  317. } elseif ($element->getType() == 'select') {
  318. if ($element->getMultiple()) {
  319. $elementName .= '[]';
  320. $value =
  321. " value{$jsIndex} = new Array();\n" .
  322. " var valueIdx = 0;\n" .
  323. " for (var i = 0; i < frm.elements['{$elementName}'].options.length; i++) {\n" .
  324. " if (frm.elements['{$elementName}'].options[i].selected) {\n" .
  325. " value{$jsIndex}[valueIdx++] = frm.elements['{$elementName}'].options[i].value;\n" .
  326. " }\n" .
  327. " }\n";
  328. } else {
  329. $value = " value{$jsIndex} = frm.elements['{$elementName}'].selectedIndex == -1? '': frm.elements['{$elementName}'].options[frm.elements['{$elementName}'].selectedIndex].value;\n";
  330. }
  331. if ($reset) {
  332. $tmp_reset .=
  333. " for (var i = 0; i < field.options.length; i++) {\n" .
  334. " field.options[i].selected = field.options[i].defaultSelected;\n" .
  335. " }\n";
  336. }
  337. } elseif ($element->getType() == 'checkbox') {
  338. if (is_a($element, 'html_quickform_advcheckbox')) {
  339. $value = " value{$jsIndex} = frm.elements['$elementName'][1].checked? frm.elements['$elementName'][1].value: frm.elements['$elementName'][0].value;\n";
  340. $tmp_reset .= $reset ? " field[1].checked = field[1].defaultChecked;\n" : '';
  341. } else {
  342. $value = " value{$jsIndex} = frm.elements['$elementName'].checked? '1': '';\n";
  343. $tmp_reset .= $reset ? " field.checked = field.defaultChecked;\n" : '';
  344. }
  345. } elseif ($element->getType() == 'radio') {
  346. $value = " value{$jsIndex} = '';\n" .
  347. // Fix for bug #5644
  348. " var els = 'length' in frm.elements['$elementName']? frm.elements['$elementName']: [ frm.elements['$elementName'] ];\n" .
  349. " for (var i = 0; i < els.length; i++) {\n" .
  350. " if (els[i].checked) {\n" .
  351. " value{$jsIndex} = els[i].value;\n" .
  352. " }\n" .
  353. " }";
  354. if ($reset) {
  355. $tmp_reset .= " for (var i = 0; i < field.length; i++) {\n" .
  356. " field[i].checked = field[i].defaultChecked;\n" .
  357. " }";
  358. }
  359. } else {
  360. $value = " value{$jsIndex} = frm.elements['$elementName'].value;";
  361. $tmp_reset .= ($reset) ? " field.value = field.defaultValue;\n" : '';
  362. }
  363. return array($value, $tmp_reset);
  364. }
  365. }