QuickForm.php 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4: */
  3. // +----------------------------------------------------------------------+
  4. // | PHP version 4.0 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1997-2003 The PHP Group |
  7. // +----------------------------------------------------------------------+
  8. // | This source file is subject to version 2.0 of the PHP license, |
  9. // | that is bundled with this package in the file LICENSE, and is |
  10. // | available at through the world-wide-web at |
  11. // | http://www.php.net/license/2_02.txt. |
  12. // | If you did not receive a copy of the PHP license and are unable to |
  13. // | obtain it through the world-wide-web, please send a note to |
  14. // | license@php.net so we can mail you a copy immediately. |
  15. // +----------------------------------------------------------------------+
  16. // | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
  17. // | Bertrand Mansion <bmansion@mamasam.com> |
  18. // +----------------------------------------------------------------------+
  19. //
  20. // $Id: QuickForm.php 17296 2008-12-15 17:08:44Z cfasanando $
  21. require_once('PEAR.php');
  22. require_once('HTML/Common.php');
  23. $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] =
  24. array(
  25. 'group' =>array('HTML/QuickForm/group.php','HTML_QuickForm_group'),
  26. 'hidden' =>array('HTML/QuickForm/hidden.php','HTML_QuickForm_hidden'),
  27. 'reset' =>array('HTML/QuickForm/reset.php','HTML_QuickForm_reset'),
  28. 'checkbox' =>array('HTML/QuickForm/checkbox.php','HTML_QuickForm_checkbox'),
  29. 'file' =>array('HTML/QuickForm/file.php','HTML_QuickForm_file'),
  30. 'image' =>array('HTML/QuickForm/image.php','HTML_QuickForm_image'),
  31. 'password' =>array('HTML/QuickForm/password.php','HTML_QuickForm_password'),
  32. 'radio' =>array('HTML/QuickForm/radio.php','HTML_QuickForm_radio'),
  33. 'button' =>array('HTML/QuickForm/button.php','HTML_QuickForm_button'),
  34. 'submit' =>array('HTML/QuickForm/submit.php','HTML_QuickForm_submit'),
  35. 'select' =>array('HTML/QuickForm/select.php','HTML_QuickForm_select'),
  36. 'hiddenselect' =>array('HTML/QuickForm/hiddenselect.php','HTML_QuickForm_hiddenselect'),
  37. 'text' =>array('HTML/QuickForm/text.php','HTML_QuickForm_text'),
  38. 'textarea' =>array('HTML/QuickForm/textarea.php','HTML_QuickForm_textarea'),
  39. 'link' =>array('HTML/QuickForm/link.php','HTML_QuickForm_link'),
  40. 'advcheckbox' =>array('HTML/QuickForm/advcheckbox.php','HTML_QuickForm_advcheckbox'),
  41. 'date' =>array('HTML/QuickForm/date.php','HTML_QuickForm_date'),
  42. 'static' =>array('HTML/QuickForm/static.php','HTML_QuickForm_static'),
  43. 'header' =>array('HTML/QuickForm/header.php', 'HTML_QuickForm_header'),
  44. 'html' =>array('HTML/QuickForm/html.php', 'HTML_QuickForm_html'),
  45. 'hierselect' =>array('HTML/QuickForm/hierselect.php', 'HTML_QuickForm_hierselect'),
  46. 'autocomplete' =>array('HTML/QuickForm/autocomplete.php', 'HTML_QuickForm_autocomplete'),
  47. 'xbutton' =>array('HTML/QuickForm/xbutton.php','HTML_QuickForm_xbutton')
  48. );
  49. $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
  50. 'required' => array('html_quickform_rule_required', 'HTML/QuickForm/Rule/Required.php'),
  51. 'maxlength' => array('html_quickform_rule_range', 'HTML/QuickForm/Rule/Range.php'),
  52. 'minlength' => array('html_quickform_rule_range', 'HTML/QuickForm/Rule/Range.php'),
  53. 'rangelength' => array('html_quickform_rule_range', 'HTML/QuickForm/Rule/Range.php'),
  54. 'email' => array('html_quickform_rule_email', 'HTML/QuickForm/Rule/Email.php'),
  55. 'regex' => array('html_quickform_rule_regex', 'HTML/QuickForm/Rule/Regex.php'),
  56. 'lettersonly' => array('html_quickform_rule_regex', 'HTML/QuickForm/Rule/Regex.php'),
  57. 'alphanumeric' => array('html_quickform_rule_regex', 'HTML/QuickForm/Rule/Regex.php'),
  58. 'numeric' => array('html_quickform_rule_regex', 'HTML/QuickForm/Rule/Regex.php'),
  59. 'nopunctuation' => array('html_quickform_rule_regex', 'HTML/QuickForm/Rule/Regex.php'),
  60. 'nonzero' => array('html_quickform_rule_regex', 'HTML/QuickForm/Rule/Regex.php'),
  61. 'callback' => array('html_quickform_rule_callback', 'HTML/QuickForm/Rule/Callback.php'),
  62. 'compare' => array('html_quickform_rule_compare', 'HTML/QuickForm/Rule/Compare.php'),
  63. 'comparedate' => array('html_quickform_rule_comparedate', 'HTML/QuickForm/Rule/CompareDate.php'),
  64. 'errordate' => array('html_quickform_rule_date', 'HTML/QuickForm/Rule/Date.php')
  65. );
  66. // {{{ error codes
  67. /*
  68. * Error codes for the QuickForm interface, which will be mapped to textual messages
  69. * in the QuickForm::errorMessage() function. If you are to add a new error code, be
  70. * sure to add the textual messages to the QuickForm::errorMessage() function as well
  71. */
  72. define('QUICKFORM_OK', 1);
  73. define('QUICKFORM_ERROR', -1);
  74. define('QUICKFORM_INVALID_RULE', -2);
  75. define('QUICKFORM_NONEXIST_ELEMENT', -3);
  76. define('QUICKFORM_INVALID_FILTER', -4);
  77. define('QUICKFORM_UNREGISTERED_ELEMENT', -5);
  78. define('QUICKFORM_INVALID_ELEMENT_NAME', -6);
  79. define('QUICKFORM_INVALID_PROCESS', -7);
  80. define('QUICKFORM_DEPRECATED', -8);
  81. define('QUICKFORM_INVALID_DATASOURCE', -9);
  82. // }}}
  83. /**
  84. * Create, validate and process HTML forms
  85. *
  86. * @author Adam Daniel <adaniel1@eesus.jnj.com>
  87. * @author Bertrand Mansion <bmansion@mamasam.com>
  88. * @version 2.0
  89. * @since PHP 4.0.3pl1
  90. */
  91. class HTML_QuickForm extends HTML_Common {
  92. // {{{ properties
  93. /**
  94. * Array containing the form fields
  95. * @since 1.0
  96. * @var array
  97. * @access private
  98. */
  99. var $_elements = array();
  100. /**
  101. * Array containing element name to index map
  102. * @since 1.1
  103. * @var array
  104. * @access private
  105. */
  106. var $_elementIndex = array();
  107. /**
  108. * Array containing indexes of duplicate elements
  109. * @since 2.10
  110. * @var array
  111. * @access private
  112. */
  113. var $_duplicateIndex = array();
  114. /**
  115. * Array containing required field IDs
  116. * @since 1.0
  117. * @var array
  118. * @access private
  119. */
  120. var $_required = array();
  121. /**
  122. * Prefix message in javascript alert if error
  123. * @since 1.0
  124. * @var string
  125. * @access public
  126. */
  127. var $_jsPrefix = 'Invalid information entered.';
  128. /**
  129. * Postfix message in javascript alert if error
  130. * @since 1.0
  131. * @var string
  132. * @access public
  133. */
  134. var $_jsPostfix = 'Please correct these fields.';
  135. /**
  136. * Datasource object implementing the informal
  137. * datasource protocol
  138. * @since 3.3
  139. * @var object
  140. * @access private
  141. */
  142. var $_datasource;
  143. /**
  144. * Array of default form values
  145. * @since 2.0
  146. * @var array
  147. * @access private
  148. */
  149. var $_defaultValues = array();
  150. /**
  151. * Array of constant form values
  152. * @since 2.0
  153. * @var array
  154. * @access private
  155. */
  156. var $_constantValues = array();
  157. /**
  158. * Array of submitted form values
  159. * @since 1.0
  160. * @var array
  161. * @access private
  162. */
  163. var $_submitValues = array();
  164. /**
  165. * Array of submitted form files
  166. * @since 1.0
  167. * @var integer
  168. * @access public
  169. */
  170. var $_submitFiles = array();
  171. /**
  172. * Value for maxfilesize hidden element if form contains file input
  173. * @since 1.0
  174. * @var integer
  175. * @access public
  176. */
  177. var $_maxFileSize = 1048576; // 1 Mb = 1048576
  178. /**
  179. * Flag to know if all fields are frozen
  180. * @since 1.0
  181. * @var boolean
  182. * @access private
  183. */
  184. var $_freezeAll = false;
  185. /**
  186. * Array containing the form rules
  187. * @since 1.0
  188. * @var array
  189. * @access private
  190. */
  191. var $_rules = array();
  192. /**
  193. * Form rules, global variety
  194. * @var array
  195. * @access private
  196. */
  197. var $_formRules = array();
  198. /**
  199. * Array containing the validation errors
  200. * @since 1.0
  201. * @var array
  202. * @access private
  203. */
  204. var $_errors = array();
  205. /**
  206. * Note for required fields in the form
  207. * @var string
  208. * @since 1.0
  209. * @access private
  210. */
  211. var $_requiredNote = '<span style="font-size:80%; color:#ff0000;">*</span><span style="font-size:80%;"> denotes required field</span>';
  212. /**
  213. * Whether the form was submitted
  214. * @var boolean
  215. * @access private
  216. */
  217. var $_flagSubmitted = false;
  218. // }}}
  219. // {{{ constructor
  220. /**
  221. * Class constructor
  222. * @param string $formName Form's name.
  223. * @param string $method (optional)Form's method defaults to 'POST'
  224. * @param string $action (optional)Form's action
  225. * @param string $target (optional)Form's target defaults to '_self'
  226. * @param mixed $attributes (optional)Extra attributes for <form> tag
  227. * @param bool $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field
  228. * @access public
  229. */
  230. function HTML_QuickForm($formName='', $method='post', $action='', $target='', $attributes=null, $trackSubmit = false)
  231. {
  232. HTML_Common::HTML_Common($attributes);
  233. $method = (strtoupper($method) == 'GET') ? 'get' : 'post';
  234. $action = ($action == '') ? api_get_self() : $action;
  235. $target = empty($target) ? array() : array('target' => $target);
  236. $attributes = array('action'=>$action, 'method'=>$method, 'name'=>$formName, 'id'=>$formName) + $target;
  237. $this->updateAttributes($attributes);
  238. if (!$trackSubmit || isset($_REQUEST['_qf__' . $formName])) {
  239. if (1 == get_magic_quotes_gpc()) {
  240. $this->_submitValues = $this->_recursiveFilter('stripslashes', 'get' == $method? $_GET: $_POST);
  241. foreach ($_FILES as $keyFirst => $valFirst) {
  242. foreach ($valFirst as $keySecond => $valSecond) {
  243. if ('name' == $keySecond) {
  244. $this->_submitFiles[$keyFirst][$keySecond] = $this->_recursiveFilter('stripslashes', $valSecond);
  245. } else {
  246. $this->_submitFiles[$keyFirst][$keySecond] = $valSecond;
  247. }
  248. }
  249. }
  250. } else {
  251. $this->_submitValues = 'get' == $method? $_GET: $_POST;
  252. $this->_submitFiles = $_FILES;
  253. }
  254. $this->_flagSubmitted = count($this->_submitValues) > 0 || count($this->_submitFiles) > 0;
  255. }
  256. if ($trackSubmit) {
  257. unset($this->_submitValues['_qf__' . $formName]);
  258. $this->addElement('hidden', '_qf__' . $formName, null);
  259. }
  260. if (preg_match('/^([0-9]+)([a-zA-Z]*)$/', ini_get('upload_max_filesize'), $matches)) {
  261. // see http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
  262. switch (strtoupper($matches['2'])) {
  263. case 'G':
  264. $this->_maxFileSize = $matches['1'] * 1073741824;
  265. break;
  266. case 'M':
  267. $this->_maxFileSize = $matches['1'] * 1048576;
  268. break;
  269. case 'K':
  270. $this->_maxFileSize = $matches['1'] * 1024;
  271. break;
  272. default:
  273. $this->_maxFileSize = $matches['1'];
  274. }
  275. }
  276. } // end constructor
  277. // }}}
  278. // {{{ apiVersion()
  279. /**
  280. * Returns the current API version
  281. *
  282. * @since 1.0
  283. * @access public
  284. * @return float
  285. */
  286. function apiVersion()
  287. {
  288. return 3.2;
  289. } // end func apiVersion
  290. // }}}
  291. // {{{ registerElementType()
  292. /**
  293. * Registers a new element type
  294. *
  295. * @param string $typeName Name of element type
  296. * @param string $include Include path for element type
  297. * @param string $className Element class name
  298. * @since 1.0
  299. * @access public
  300. * @return void
  301. */
  302. function registerElementType($typeName, $include, $className)
  303. {
  304. $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'][strtolower($typeName)] = array($include, $className);
  305. } // end func registerElementType
  306. // }}}
  307. // {{{ registerRule()
  308. /**
  309. * Registers a new validation rule
  310. *
  311. * @param string $ruleName Name of validation rule
  312. * @param string $type Either: 'regex', 'function' or 'rule' for an HTML_QuickForm_Rule object
  313. * @param string $data1 Name of function, regular expression or HTML_QuickForm_Rule classname
  314. * @param string $data2 Object parent of above function or HTML_QuickForm_Rule file path
  315. * @since 1.0
  316. * @access public
  317. * @return void
  318. */
  319. function registerRule($ruleName, $type, $data1, $data2 = null)
  320. {
  321. include_once('HTML/QuickForm/RuleRegistry.php');
  322. $registry =& HTML_QuickForm_RuleRegistry::singleton();
  323. $registry->registerRule($ruleName, $type, $data1, $data2);
  324. } // end func registerRule
  325. // }}}
  326. // {{{ elementExists()
  327. /**
  328. * Returns true if element is in the form
  329. *
  330. * @param string $element form name of element to check
  331. * @since 1.0
  332. * @access public
  333. * @return boolean
  334. */
  335. function elementExists($element=null)
  336. {
  337. return isset($this->_elementIndex[$element]);
  338. } // end func elementExists
  339. // }}}
  340. // {{{ setDatasource()
  341. /**
  342. * Sets a datasource object for this form object
  343. *
  344. * Datasource default and constant values will feed the QuickForm object if
  345. * the datasource implements defaultValues() and constantValues() methods.
  346. *
  347. * @param object $datasource datasource object implementing the informal datasource protocol
  348. * @param mixed $defaultsFilter string or array of filter(s) to apply to default values
  349. * @param mixed $constantsFilter string or array of filter(s) to apply to constants values
  350. * @since 3.3
  351. * @access public
  352. * @return void
  353. */
  354. function setDatasource(&$datasource, $defaultsFilter = null, $constantsFilter = null)
  355. {
  356. if (is_object($datasource)) {
  357. $this->_datasource =& $datasource;
  358. if (is_callable(array($datasource, 'defaultValues'))) {
  359. $this->setDefaults($datasource->defaultValues($this), $defaultsFilter);
  360. }
  361. if (is_callable(array($datasource, 'constantValues'))) {
  362. $this->setConstants($datasource->constantValues($this), $constantsFilter);
  363. }
  364. } else {
  365. return PEAR::raiseError(null, QUICKFORM_INVALID_DATASOURCE, null, E_USER_WARNING, "Datasource is not an object in QuickForm::setDatasource()", 'HTML_QuickForm_Error', true);
  366. }
  367. } // end func setDatasource
  368. // }}}
  369. // {{{ setDefaults()
  370. /**
  371. * Initializes default form values
  372. *
  373. * @param array $defaultValues values used to fill the form
  374. * @param mixed $filter (optional) filter(s) to apply to all default values
  375. * @since 1.0
  376. * @access public
  377. * @return void
  378. */
  379. function setDefaults($defaultValues = null, $filter = null)
  380. {
  381. if (is_array($defaultValues)) {
  382. if (isset($filter)) {
  383. if (is_array($filter) && (2 != count($filter) || !is_callable($filter))) {
  384. foreach ($filter as $val) {
  385. if (!is_callable($val)) {
  386. return PEAR::raiseError(null, QUICKFORM_INVALID_FILTER, null, E_USER_WARNING, "Callback function does not exist in QuickForm::setDefaults()", 'HTML_QuickForm_Error', true);
  387. } else {
  388. $defaultValues = $this->_recursiveFilter($val, $defaultValues);
  389. }
  390. }
  391. } elseif (!is_callable($filter)) {
  392. return PEAR::raiseError(null, QUICKFORM_INVALID_FILTER, null, E_USER_WARNING, "Callback function does not exist in QuickForm::setDefaults()", 'HTML_QuickForm_Error', true);
  393. } else {
  394. $defaultValues = $this->_recursiveFilter($filter, $defaultValues);
  395. }
  396. }
  397. $this->_defaultValues = HTML_QuickForm::arrayMerge($this->_defaultValues, $defaultValues);
  398. foreach (array_keys($this->_elements) as $key) {
  399. $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
  400. }
  401. }
  402. } // end func setDefaults
  403. // }}}
  404. // {{{ setConstants()
  405. /**
  406. * Initializes constant form values.
  407. * These values won't get overridden by POST or GET vars
  408. *
  409. * @param array $constantValues values used to fill the form
  410. * @param mixed $filter (optional) filter(s) to apply to all default values
  411. *
  412. * @since 2.0
  413. * @access public
  414. * @return void
  415. */
  416. function setConstants($constantValues = null, $filter = null)
  417. {
  418. if (is_array($constantValues)) {
  419. if (isset($filter)) {
  420. if (is_array($filter) && (2 != count($filter) || !is_callable($filter))) {
  421. foreach ($filter as $val) {
  422. if (!is_callable($val)) {
  423. return PEAR::raiseError(null, QUICKFORM_INVALID_FILTER, null, E_USER_WARNING, "Callback function does not exist in QuickForm::setConstants()", 'HTML_QuickForm_Error', true);
  424. } else {
  425. $constantValues = $this->_recursiveFilter($val, $constantValues);
  426. }
  427. }
  428. } elseif (!is_callable($filter)) {
  429. return PEAR::raiseError(null, QUICKFORM_INVALID_FILTER, null, E_USER_WARNING, "Callback function does not exist in QuickForm::setConstants()", 'HTML_QuickForm_Error', true);
  430. } else {
  431. $constantValues = $this->_recursiveFilter($filter, $constantValues);
  432. }
  433. }
  434. $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, $constantValues);
  435. foreach (array_keys($this->_elements) as $key) {
  436. $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
  437. }
  438. }
  439. } // end func setConstants
  440. // }}}
  441. // {{{ setMaxFileSize()
  442. /**
  443. * Sets the value of MAX_FILE_SIZE hidden element
  444. *
  445. * @param int $bytes Size in bytes
  446. * @since 3.0
  447. * @access public
  448. * @return void
  449. */
  450. function setMaxFileSize($bytes = 0)
  451. {
  452. if ($bytes > 0) {
  453. $this->_maxFileSize = $bytes;
  454. }
  455. if (!$this->elementExists('MAX_FILE_SIZE')) {
  456. $this->addElement('hidden', 'MAX_FILE_SIZE', $this->_maxFileSize);
  457. } else {
  458. $el =& $this->getElement('MAX_FILE_SIZE');
  459. $el->updateAttributes(array('value' => $this->_maxFileSize));
  460. }
  461. } // end func setMaxFileSize
  462. // }}}
  463. // {{{ getMaxFileSize()
  464. /**
  465. * Returns the value of MAX_FILE_SIZE hidden element
  466. *
  467. * @since 3.0
  468. * @access public
  469. * @return int max file size in bytes
  470. */
  471. function getMaxFileSize()
  472. {
  473. return $this->_maxFileSize;
  474. } // end func getMaxFileSize
  475. // }}}
  476. // {{{ &createElement()
  477. /**
  478. * Creates a new form element of the given type.
  479. *
  480. * This method accepts variable number of parameters, their
  481. * meaning and count depending on $elementType
  482. *
  483. * @param string $elementType type of element to add (text, textarea, file...)
  484. * @since 1.0
  485. * @access public
  486. * @return object extended class of HTML_element
  487. * @throws HTML_QuickForm_Error
  488. */
  489. function &createElement($elementType)
  490. {
  491. $args = func_get_args();
  492. $element =& HTML_QuickForm::_loadElement('createElement', $elementType, array_slice($args, 1));
  493. return $element;
  494. } // end func createElement
  495. // }}}
  496. // {{{ _loadElement()
  497. /**
  498. * Returns a form element of the given type
  499. *
  500. * @param string $event event to send to newly created element ('createElement' or 'addElement')
  501. * @param string $type element type
  502. * @param array $args arguments for event
  503. * @since 2.0
  504. * @access private
  505. * @return object a new element
  506. * @throws HTML_QuickForm_Error
  507. */
  508. function &_loadElement($event, $type, $args)
  509. {
  510. $type = strtolower($type);
  511. if (!HTML_QuickForm::isTypeRegistered($type)) {
  512. $error = PEAR::raiseError(null, QUICKFORM_UNREGISTERED_ELEMENT, null, E_USER_WARNING, "Element '$type' does not exist in HTML_QuickForm::_loadElement()", 'HTML_QuickForm_Error', true);
  513. return $error;
  514. }
  515. $className = $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'][$type][1];
  516. $includeFile = $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'][$type][0];
  517. include_once($includeFile);
  518. // Suppressing a deprecation warning on PHP 5.3
  519. //$elementObject =& new $className();
  520. $elementObject = new $className();
  521. //
  522. for ($i = 0; $i < 5; $i++) {
  523. if (!isset($args[$i])) {
  524. $args[$i] = null;
  525. }
  526. }
  527. $err = $elementObject->onQuickFormEvent($event, $args, $this);
  528. if ($err !== true) {
  529. return $err;
  530. }
  531. return $elementObject;
  532. } // end func _loadElement
  533. // }}}
  534. // {{{ addElement()
  535. /**
  536. * Adds an element into the form
  537. *
  538. * If $element is a string representing element type, then this
  539. * method accepts variable number of parameters, their meaning
  540. * and count depending on $element
  541. *
  542. * @param mixed $element element object or type of element to add (text, textarea, file...)
  543. * @since 1.0
  544. * @return object reference to element
  545. * @access public
  546. * @throws HTML_QuickForm_Error
  547. */
  548. function &addElement($element)
  549. {
  550. if (is_object($element) && is_subclass_of($element, 'html_quickform_element')) {
  551. $elementObject = &$element;
  552. $elementObject->onQuickFormEvent('updateValue', null, $this);
  553. } else {
  554. $args = func_get_args();
  555. $elementObject =& $this->_loadElement('addElement', $element, array_slice($args, 1));
  556. if (PEAR::isError($elementObject)) {
  557. return $elementObject;
  558. }
  559. }
  560. $elementName = $elementObject->getName();
  561. // Add the element if it is not an incompatible duplicate
  562. if (!empty($elementName) && isset($this->_elementIndex[$elementName])) {
  563. if ($this->_elements[$this->_elementIndex[$elementName]]->getType() ==
  564. $elementObject->getType()) {
  565. $this->_elements[] =& $elementObject;
  566. $elKeys = array_keys($this->_elements);
  567. $this->_duplicateIndex[$elementName][] = end($elKeys);
  568. } else {
  569. $error = PEAR::raiseError(null, QUICKFORM_INVALID_ELEMENT_NAME, null, E_USER_WARNING, "Element '$elementName' already exists in HTML_QuickForm::addElement()", 'HTML_QuickForm_Error', true);
  570. return $error;
  571. }
  572. } else {
  573. $this->_elements[] =& $elementObject;
  574. $elKeys = array_keys($this->_elements);
  575. $this->_elementIndex[$elementName] = end($elKeys);
  576. }
  577. if ($this->_freezeAll) {
  578. $elementObject->freeze();
  579. }
  580. return $elementObject;
  581. } // end func addElement
  582. // }}}
  583. // {{{ insertElementBefore()
  584. /**
  585. * Inserts a new element right before the other element
  586. *
  587. * Warning: it is not possible to check whether the $element is already
  588. * added to the form, therefore if you want to move the existing form
  589. * element to a new position, you'll have to use removeElement():
  590. * $form->insertElementBefore($form->removeElement('foo', false), 'bar');
  591. *
  592. * @access public
  593. * @since 3.2.4
  594. * @param object HTML_QuickForm_element Element to insert
  595. * @param string Name of the element before which the new one is inserted
  596. * @return object HTML_QuickForm_element reference to inserted element
  597. * @throws HTML_QuickForm_Error
  598. */
  599. function &insertElementBefore(&$element, $nameAfter)
  600. {
  601. if (!empty($this->_duplicateIndex[$nameAfter])) {
  602. $error = PEAR::raiseError(null, QUICKFORM_INVALID_ELEMENT_NAME, null, E_USER_WARNING, 'Several elements named "' . $nameAfter . '" exist in HTML_QuickForm::insertElementBefore().', 'HTML_QuickForm_Error', true);
  603. return $error;
  604. } elseif (!$this->elementExists($nameAfter)) {
  605. $error = PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$nameAfter' does not exist in HTML_QuickForm::insertElementBefore()", 'HTML_QuickForm_Error', true);
  606. return $error;
  607. }
  608. $elementName = $element->getName();
  609. $targetIdx = $this->_elementIndex[$nameAfter];
  610. $duplicate = false;
  611. // Like in addElement(), check that it's not an incompatible duplicate
  612. if (!empty($elementName) && isset($this->_elementIndex[$elementName])) {
  613. if ($this->_elements[$this->_elementIndex[$elementName]]->getType() != $element->getType()) {
  614. $error = PEAR::raiseError(null, QUICKFORM_INVALID_ELEMENT_NAME, null, E_USER_WARNING, "Element '$elementName' already exists in HTML_QuickForm::insertElementBefore()", 'HTML_QuickForm_Error', true);
  615. return $error;
  616. }
  617. $duplicate = true;
  618. }
  619. // Move all the elements after added back one place, reindex _elementIndex and/or _duplicateIndex
  620. $elKeys = array_keys($this->_elements);
  621. for ($i = end($elKeys); $i >= $targetIdx; $i--) {
  622. if (isset($this->_elements[$i])) {
  623. $currentName = $this->_elements[$i]->getName();
  624. $this->_elements[$i + 1] =& $this->_elements[$i];
  625. if ($this->_elementIndex[$currentName] == $i) {
  626. $this->_elementIndex[$currentName] = $i + 1;
  627. } else
  628. {
  629. if (is_array($this->_duplicateIndex[$currentName]))
  630. {
  631. $dupIdx = array_search($i, $this->_duplicateIndex[$currentName]);
  632. $this->_duplicateIndex[$currentName][$dupIdx] = $i + 1;
  633. }
  634. }
  635. unset($this->_elements[$i]);
  636. }
  637. }
  638. // Put the element in place finally
  639. $this->_elements[$targetIdx] =& $element;
  640. if (!$duplicate) {
  641. $this->_elementIndex[$elementName] = $targetIdx;
  642. } else {
  643. $this->_duplicateIndex[$elementName][] = $targetIdx;
  644. }
  645. $element->onQuickFormEvent('updateValue', null, $this);
  646. if ($this->_freezeAll) {
  647. $element->freeze();
  648. }
  649. // If not done, the elements will appear in reverse order
  650. ksort($this->_elements);
  651. return $element;
  652. }
  653. // }}}
  654. // {{{ addGroup()
  655. /**
  656. * Adds an element group
  657. * @param array $elements array of elements composing the group
  658. * @param string $name (optional)group name
  659. * @param string $groupLabel (optional)group label
  660. * @param string $separator (optional)string to separate elements
  661. * @param string $appendName (optional)specify whether the group name should be
  662. * used in the form element name ex: group[element]
  663. * @return object reference to added group of elements
  664. * @since 2.8
  665. * @access public
  666. * @throws PEAR_Error
  667. */
  668. function &addGroup($elements, $name=null, $groupLabel='', $separator=null, $appendName = true)
  669. {
  670. static $anonGroups = 1;
  671. if (0 == strlen($name)) {
  672. $name = 'qf_group_' . $anonGroups++;
  673. $appendName = false;
  674. }
  675. $group =& $this->addElement('group', $name, $groupLabel, $elements, $separator, $appendName);
  676. return $group;
  677. } // end func addGroup
  678. // }}}
  679. // {{{ &getElement()
  680. /**
  681. * Returns a reference to the element
  682. *
  683. * @param string $element Element name
  684. * @since 2.0
  685. * @access public
  686. * @return object reference to element
  687. * @throws HTML_QuickForm_Error
  688. */
  689. function &getElement($element)
  690. {
  691. if (isset($this->_elementIndex[$element])) {
  692. return $this->_elements[$this->_elementIndex[$element]];
  693. } else {
  694. $error = PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$element' does not exist in HTML_QuickForm::getElement()", 'HTML_QuickForm_Error', true);
  695. return $error;
  696. }
  697. } // end func getElement
  698. // }}}
  699. // {{{ &getElementValue()
  700. /**
  701. * Returns the element's raw value
  702. *
  703. * This returns the value as submitted by the form (not filtered)
  704. * or set via setDefaults() or setConstants()
  705. *
  706. * @param string $element Element name
  707. * @since 2.0
  708. * @access public
  709. * @return mixed element value
  710. * @throws HTML_QuickForm_Error
  711. */
  712. function &getElementValue($element)
  713. {
  714. if (!isset($this->_elementIndex[$element])) {
  715. $error = PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$element' does not exist in HTML_QuickForm::getElementValue()", 'HTML_QuickForm_Error', true);
  716. return $error;
  717. }
  718. $value = $this->_elements[$this->_elementIndex[$element]]->getValue();
  719. if (isset($this->_duplicateIndex[$element])) {
  720. foreach ($this->_duplicateIndex[$element] as $index) {
  721. if (null !== ($v = $this->_elements[$index]->getValue())) {
  722. if (is_array($value)) {
  723. $value[] = $v;
  724. } else {
  725. $value = (null === $value)? $v: array($value, $v);
  726. }
  727. }
  728. }
  729. }
  730. return $value;
  731. } // end func getElementValue
  732. // }}}
  733. // {{{ getSubmitValue()
  734. /**
  735. * Returns the elements value after submit and filter
  736. *
  737. * @param string Element name
  738. * @since 2.0
  739. * @access public
  740. * @return mixed submitted element value or null if not set
  741. */
  742. function getSubmitValue($elementName)
  743. {
  744. $value = null;
  745. if (isset($this->_submitValues[$elementName]) || isset($this->_submitFiles[$elementName])) {
  746. $value = isset($this->_submitValues[$elementName])? $this->_submitValues[$elementName]: array();
  747. if (is_array($value) && isset($this->_submitFiles[$elementName])) {
  748. foreach ($this->_submitFiles[$elementName] as $k => $v) {
  749. $value = HTML_QuickForm::arrayMerge($value, $this->_reindexFiles($this->_submitFiles[$elementName][$k], $k));
  750. }
  751. }
  752. } elseif ('file' == $this->getElementType($elementName)) {
  753. return $this->getElementValue($elementName);
  754. } elseif (false !== ($pos = strpos($elementName, '['))) {
  755. $base = str_replace(
  756. array('\\', '\''), array('\\\\', '\\\''),
  757. substr($elementName, 0, $pos)
  758. );
  759. $idx = "['" . str_replace(
  760. array('\\', '\'', ']', '['), array('\\\\', '\\\'', '', "']['"),
  761. substr($elementName, $pos + 1, -1)
  762. ) . "']";
  763. if (isset($this->_submitValues[$base])) {
  764. $value = eval("return (isset(\$this->_submitValues['{$base}']{$idx})) ? \$this->_submitValues['{$base}']{$idx} : null;");
  765. }
  766. if ((is_array($value) || null === $value) && isset($this->_submitFiles[$base])) {
  767. $props = array('name', 'type', 'size', 'tmp_name', 'error');
  768. $code = "if (!isset(\$this->_submitFiles['{$base}']['name']{$idx})) {\n" .
  769. " return null;\n" .
  770. "} else {\n" .
  771. " \$v = array();\n";
  772. foreach ($props as $prop) {
  773. $code .= " \$v = HTML_QuickForm::arrayMerge(\$v, \$this->_reindexFiles(\$this->_submitFiles['{$base}']['{$prop}']{$idx}, '{$prop}'));\n";
  774. }
  775. $fileValue = eval($code . " return \$v;\n}\n");
  776. if (null !== $fileValue) {
  777. $value = null === $value? $fileValue: HTML_QuickForm::arrayMerge($value, $fileValue);
  778. }
  779. }
  780. }
  781. // This is only supposed to work for groups with appendName = false
  782. if (null === $value && 'group' == $this->getElementType($elementName)) {
  783. $group =& $this->getElement($elementName);
  784. $elements =& $group->getElements();
  785. foreach (array_keys($elements) as $key) {
  786. $name = $group->getElementName($key);
  787. // prevent endless recursion in case of radios and such
  788. if ($name != $elementName) {
  789. if (null !== ($v = $this->getSubmitValue($name))) {
  790. $value[$name] = $v;
  791. }
  792. }
  793. }
  794. }
  795. return $value;
  796. } // end func getSubmitValue
  797. // }}}
  798. // {{{ _reindexFiles()
  799. /**
  800. * A helper function to change the indexes in $_FILES array
  801. *
  802. * @param mixed Some value from the $_FILES array
  803. * @param string The key from the $_FILES array that should be appended
  804. * @return array
  805. */
  806. function _reindexFiles($value, $key)
  807. {
  808. if (!is_array($value)) {
  809. return array($key => $value);
  810. } else {
  811. $ret = array();
  812. foreach ($value as $k => $v) {
  813. $ret[$k] = $this->_reindexFiles($v, $key);
  814. }
  815. return $ret;
  816. }
  817. }
  818. // }}}
  819. // {{{ getElementError()
  820. /**
  821. * Returns error corresponding to validated element
  822. *
  823. * @param string $element Name of form element to check
  824. * @since 1.0
  825. * @access public
  826. * @return string error message corresponding to checked element
  827. */
  828. function getElementError($element)
  829. {
  830. if (isset($this->_errors[$element])) {
  831. return $this->_errors[$element];
  832. }
  833. } // end func getElementError
  834. // }}}
  835. // {{{ setElementError()
  836. /**
  837. * Set error message for a form element
  838. *
  839. * @param string $element Name of form element to set error for
  840. * @param string $message Error message, if empty then removes the current error message
  841. * @since 1.0
  842. * @access public
  843. * @return void
  844. */
  845. function setElementError($element, $message = null)
  846. {
  847. if (!empty($message)) {
  848. $this->_errors[$element] = $message;
  849. } else {
  850. unset($this->_errors[$element]);
  851. }
  852. } // end func setElementError
  853. // }}}
  854. // {{{ getElementType()
  855. /**
  856. * Returns the type of the given element
  857. *
  858. * @param string $element Name of form element
  859. * @since 1.1
  860. * @access public
  861. * @return string Type of the element, false if the element is not found
  862. */
  863. function getElementType($element)
  864. {
  865. if (isset($this->_elementIndex[$element])) {
  866. return $this->_elements[$this->_elementIndex[$element]]->getType();
  867. }
  868. return false;
  869. } // end func getElementType
  870. // }}}
  871. // {{{ updateElementAttr()
  872. /**
  873. * Updates Attributes for one or more elements
  874. *
  875. * @param mixed $elements Array of element names/objects or string of elements to be updated
  876. * @param mixed $attrs Array or sting of html attributes
  877. * @since 2.10
  878. * @access public
  879. * @return void
  880. */
  881. function updateElementAttr($elements, $attrs)
  882. {
  883. if (is_string($elements)) {
  884. $elements = split('[ ]?,[ ]?', $elements);
  885. }
  886. foreach (array_keys($elements) as $key) {
  887. if (is_object($elements[$key]) && is_a($elements[$key], 'HTML_QuickForm_element')) {
  888. $elements[$key]->updateAttributes($attrs);
  889. } elseif (isset($this->_elementIndex[$elements[$key]])) {
  890. $this->_elements[$this->_elementIndex[$elements[$key]]]->updateAttributes($attrs);
  891. if (isset($this->_duplicateIndex[$elements[$key]])) {
  892. foreach ($this->_duplicateIndex[$elements[$key]] as $index) {
  893. $this->_elements[$index]->updateAttributes($attrs);
  894. }
  895. }
  896. }
  897. }
  898. } // end func updateElementAttr
  899. // }}}
  900. // {{{ removeElement()
  901. /**
  902. * Removes an element
  903. *
  904. * The method "unlinks" an element from the form, returning the reference
  905. * to the element object. If several elements named $elementName exist,
  906. * it removes the first one, leaving the others intact.
  907. *
  908. * @param string $elementName The element name
  909. * @param boolean $removeRules True if rules for this element are to be removed too
  910. * @access public
  911. * @since 2.0
  912. * @return object HTML_QuickForm_element a reference to the removed element
  913. * @throws HTML_QuickForm_Error
  914. */
  915. function &removeElement($elementName, $removeRules = true)
  916. {
  917. if (!isset($this->_elementIndex[$elementName])) {
  918. $error = PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$elementName' does not exist in HTML_QuickForm::removeElement()", 'HTML_QuickForm_Error', true);
  919. return $error;
  920. }
  921. $el =& $this->_elements[$this->_elementIndex[$elementName]];
  922. unset($this->_elements[$this->_elementIndex[$elementName]]);
  923. if (empty($this->_duplicateIndex[$elementName])) {
  924. unset($this->_elementIndex[$elementName]);
  925. } else {
  926. $this->_elementIndex[$elementName] = array_shift($this->_duplicateIndex[$elementName]);
  927. }
  928. if ($removeRules) {
  929. unset($this->_rules[$elementName], $this->_errors[$elementName]);
  930. }
  931. return $el;
  932. } // end func removeElement
  933. // }}}
  934. // {{{ addRule()
  935. /**
  936. * Adds a validation rule for the given field
  937. *
  938. * If the element is in fact a group, it will be considered as a whole.
  939. * To validate grouped elements as separated entities,
  940. * use addGroupRule instead of addRule.
  941. *
  942. * @param string $element Form element name
  943. * @param string $message Message to display for invalid data
  944. * @param string $type Rule type, use getRegisteredRules() to get types
  945. * @param string $format (optional)Required for extra rule data
  946. * @param string $validation (optional)Where to perform validation: "server", "client"
  947. * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
  948. * @param boolean $force Force the rule to be applied, even if the target form element does not exist
  949. * @since 1.0
  950. * @access public
  951. * @throws HTML_QuickForm_Error
  952. */
  953. function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
  954. {
  955. if (!$force) {
  956. if (!is_array($element) && !$this->elementExists($element)) {
  957. return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$element' does not exist in HTML_QuickForm::addRule()", 'HTML_QuickForm_Error', true);
  958. } elseif (is_array($element)) {
  959. foreach ($element as $el) {
  960. if (!$this->elementExists($el)) {
  961. return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$el' does not exist in HTML_QuickForm::addRule()", 'HTML_QuickForm_Error', true);
  962. }
  963. }
  964. }
  965. }
  966. if (false === ($newName = $this->isRuleRegistered($type, true))) {
  967. return PEAR::raiseError(null, QUICKFORM_INVALID_RULE, null, E_USER_WARNING, "Rule '$type' is not registered in HTML_QuickForm::addRule()", 'HTML_QuickForm_Error', true);
  968. } elseif (is_string($newName)) {
  969. $type = $newName;
  970. }
  971. if (is_array($element)) {
  972. $dependent = $element;
  973. $element = array_shift($dependent);
  974. } else {
  975. $dependent = null;
  976. }
  977. if ($type == 'required' || $type == 'uploadedfile') {
  978. $this->_required[] = $element;
  979. }
  980. if (!isset($this->_rules[$element])) {
  981. $this->_rules[$element] = array();
  982. }
  983. if ($validation == 'client') {
  984. $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_attributes['id'] . '; } catch(e) { return true; } return myValidator(this);'));
  985. }
  986. $this->_rules[$element][] = array(
  987. 'type' => $type,
  988. 'format' => $format,
  989. 'message' => $message,
  990. 'validation' => $validation,
  991. 'reset' => $reset,
  992. 'dependent' => $dependent
  993. );
  994. } // end func addRule
  995. // }}}
  996. // {{{ addGroupRule()
  997. /**
  998. * Adds a validation rule for the given group of elements
  999. *
  1000. * Only groups with a name can be assigned a validation rule
  1001. * Use addGroupRule when you need to validate elements inside the group.
  1002. * Use addRule if you need to validate the group as a whole. In this case,
  1003. * the same rule will be applied to all elements in the group.
  1004. * Use addRule if you need to validate the group against a function.
  1005. *
  1006. * @param string $group Form group name
  1007. * @param mixed $arg1 Array for multiple elements or error message string for one element
  1008. * @param string $type (optional)Rule type use getRegisteredRules() to get types
  1009. * @param string $format (optional)Required for extra rule data
  1010. * @param int $howmany (optional)How many valid elements should be in the group
  1011. * @param string $validation (optional)Where to perform validation: "server", "client"
  1012. * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
  1013. * @since 2.5
  1014. * @access public
  1015. * @throws HTML_QuickForm_Error
  1016. */
  1017. function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
  1018. {
  1019. if (!$this->elementExists($group)) {
  1020. return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Group '$group' does not exist in HTML_QuickForm::addGroupRule()", 'HTML_QuickForm_Error', true);
  1021. }
  1022. $groupObj =& $this->getElement($group);
  1023. if (is_array($arg1)) {
  1024. $required = 0;
  1025. foreach ($arg1 as $elementIndex => $rules) {
  1026. $elementName = $groupObj->getElementName($elementIndex);
  1027. foreach ($rules as $rule) {
  1028. $format = (isset($rule[2])) ? $rule[2] : null;
  1029. $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
  1030. $reset = isset($rule[4]) && $rule[4];
  1031. $type = $rule[1];
  1032. if (false === ($newName = $this->isRuleRegistered($type, true))) {
  1033. return PEAR::raiseError(null, QUICKFORM_INVALID_RULE, null, E_USER_WARNING, "Rule '$type' is not registered in HTML_QuickForm::addGroupRule()", 'HTML_QuickForm_Error', true);
  1034. } elseif (is_string($newName)) {
  1035. $type = $newName;
  1036. }
  1037. $this->_rules[$elementName][] = array(
  1038. 'type' => $type,
  1039. 'format' => $format,
  1040. 'message' => $rule[0],
  1041. 'validation' => $validation,
  1042. 'reset' => $reset,
  1043. 'group' => $group);
  1044. if ('required' == $type || 'uploadedfile' == $type) {
  1045. $groupObj->_required[] = $elementName;
  1046. $this->_required[] = $elementName;
  1047. $required++;
  1048. }
  1049. if ('client' == $validation) {
  1050. $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_attributes['id'] . '; } catch(e) { return true; } return myValidator(this);'));
  1051. }
  1052. }
  1053. }
  1054. if ($required > 0 && count($groupObj->getElements()) == $required) {
  1055. $this->_required[] = $group;
  1056. }
  1057. } elseif (is_string($arg1)) {
  1058. if (false === ($newName = $this->isRuleRegistered($type, true))) {
  1059. return PEAR::raiseError(null, QUICKFORM_INVALID_RULE, null, E_USER_WARNING, "Rule '$type' is not registered in HTML_QuickForm::addGroupRule()", 'HTML_QuickForm_Error', true);
  1060. } elseif (is_string($newName)) {
  1061. $type = $newName;
  1062. }
  1063. // addGroupRule() should also handle <select multiple>
  1064. if (is_a($groupObj, 'html_quickform_group')) {
  1065. // Radios need to be handled differently when required
  1066. if ($type == 'required' && $groupObj->getGroupType() == 'radio') {
  1067. $howmany = ($howmany == 0) ? 1 : $howmany;
  1068. } else {
  1069. $howmany = ($howmany == 0) ? count($groupObj->getElements()) : $howmany;
  1070. }
  1071. }
  1072. $this->_rules[$group][] = array('type' => $type,
  1073. 'format' => $format,
  1074. 'message' => $arg1,
  1075. 'validation' => $validation,
  1076. 'howmany' => $howmany,
  1077. 'reset' => $reset);
  1078. if ($type == 'required') {
  1079. $this->_required[] = $group;
  1080. }
  1081. if ($validation == 'client') {
  1082. $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_attributes['id'] . '; } catch(e) { return true; } return myValidator(this);'));
  1083. }
  1084. }
  1085. } // end func addGroupRule
  1086. // }}}
  1087. // {{{ addFormRule()
  1088. /**
  1089. * Adds a global validation rule
  1090. *
  1091. * This should be used when for a rule involving several fields or if
  1092. * you want to use some completely custom validation for your form.
  1093. * The rule function/method should return true in case of successful
  1094. * validation and array('element name' => 'error') when there were errors.
  1095. *
  1096. * @access public
  1097. * @param mixed Callback, either function name or array(&$object, 'method')
  1098. * @throws HTML_QuickForm_Error
  1099. */
  1100. function addFormRule($rule)
  1101. {
  1102. if (!is_callable($rule)) {
  1103. return PEAR::raiseError(null, QUICKFORM_INVALID_RULE, null, E_USER_WARNING, 'Callback function does not exist in HTML_QuickForm::addFormRule()', 'HTML_QuickForm_Error', true);
  1104. }
  1105. $this->_formRules[] = $rule;
  1106. }
  1107. // }}}
  1108. // {{{ applyFilter()
  1109. /**
  1110. * Applies a data filter for the given field(s)
  1111. *
  1112. * @param mixed $element Form element name or array of such names
  1113. * @param mixed $filter Callback, either function name or array(&$object, 'method')
  1114. * @since 2.0
  1115. * @access public
  1116. */
  1117. function applyFilter($element, $filter)
  1118. {
  1119. if (!is_callable($filter)) {
  1120. return PEAR::raiseError(null, QUICKFORM_INVALID_FILTER, null, E_USER_WARNING, "Callback function does not exist in QuickForm::applyFilter()", 'HTML_QuickForm_Error', true);
  1121. }
  1122. if ($element == '__ALL__') {
  1123. $this->_submitValues = $this->_recursiveFilter($filter, $this->_submitValues);
  1124. } else {
  1125. if (!is_array($element)) {
  1126. $element = array($element);
  1127. }
  1128. foreach ($element as $elName) {
  1129. $value = $this->getSubmitValue($elName);
  1130. if (null !== $value) {
  1131. if (false === strpos($elName, '[')) {
  1132. $this->_submitValues[$elName] = $this->_recursiveFilter($filter, $value);
  1133. } else {
  1134. $idx = "['" . str_replace(
  1135. array('\\', '\'', ']', '['), array('\\\\', '\\\'', '', "']['"),
  1136. $elName
  1137. ) . "']";
  1138. eval("\$this->_submitValues{$idx} = \$this->_recursiveFilter(\$filter, \$value);");
  1139. }
  1140. }
  1141. }
  1142. }
  1143. } // end func applyFilter
  1144. // }}}
  1145. // {{{ _recursiveFilter()
  1146. /**
  1147. * Recursively apply a filter function
  1148. *
  1149. * @param string $filter filter to apply
  1150. * @param mixed $value submitted values
  1151. * @since 2.0
  1152. * @access private
  1153. * @return cleaned values
  1154. */
  1155. function _recursiveFilter($filter, $value)
  1156. {
  1157. if (is_array($value)) {
  1158. $cleanValues = array();
  1159. foreach ($value as $k => $v) {
  1160. $cleanValues[$k] = $this->_recursiveFilter($filter, $v);
  1161. }
  1162. return $cleanValues;
  1163. } else {
  1164. return call_user_func($filter, $value);
  1165. }
  1166. } // end func _recursiveFilter
  1167. // }}}
  1168. // {{{ arrayMerge()
  1169. /**
  1170. * Merges two arrays
  1171. *
  1172. * Merges two array like the PHP function array_merge but recursively.
  1173. * The main difference is that existing keys will not be renumbered
  1174. * if they are integers.
  1175. *
  1176. * @access puplic
  1177. * @param array $a original array
  1178. * @param array $b array which will be merged into first one
  1179. * @return array merged array
  1180. */
  1181. function arrayMerge($a, $b)
  1182. {
  1183. foreach ($b as $k => $v) {
  1184. if (is_array($v)) {
  1185. if (isset($a[$k]) && !is_array($a[$k])) {
  1186. $a[$k] = $v;
  1187. } else {
  1188. if (!isset($a[$k])) {
  1189. $a[$k] = array();
  1190. }
  1191. $a[$k] = HTML_QuickForm::arrayMerge($a[$k], $v);
  1192. }
  1193. } else {
  1194. $a[$k] = $v;
  1195. }
  1196. }
  1197. return $a;
  1198. } // end func arrayMerge
  1199. // }}}
  1200. // {{{ isTypeRegistered()
  1201. /**
  1202. * Returns whether or not the form element type is supported
  1203. *
  1204. * @param string $type Form element type
  1205. * @since 1.0
  1206. * @access public
  1207. * @return boolean
  1208. */
  1209. function isTypeRegistered($type)
  1210. {
  1211. return isset($GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'][strtolower($type)]);
  1212. } // end func isTypeRegistered
  1213. // }}}
  1214. // {{{ getRegisteredTypes()
  1215. /**
  1216. * Returns an array of registered element types
  1217. *
  1218. * @since 1.0
  1219. * @access public
  1220. * @return array
  1221. */
  1222. function getRegisteredTypes()
  1223. {
  1224. return array_keys($GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']);
  1225. } // end func getRegisteredTypes
  1226. // }}}
  1227. // {{{ isRuleRegistered()
  1228. /**
  1229. * Returns whether or not the given rule is supported
  1230. *
  1231. * @param string $name Validation rule name
  1232. * @param bool Whether to automatically register subclasses of HTML_QuickForm_Rule
  1233. * @since 1.0
  1234. * @access public
  1235. * @return mixed true if previously registered, false if not, new rule name if auto-registering worked
  1236. */
  1237. function isRuleRegistered($name, $autoRegister = false)
  1238. {
  1239. if (is_scalar($name) && isset($GLOBALS['_HTML_QuickForm_registered_rules'][$name])) {
  1240. return true;
  1241. } elseif (!$autoRegister) {
  1242. return false;
  1243. }
  1244. // automatically register the rule if requested
  1245. include_once 'HTML/QuickForm/RuleRegistry.php';
  1246. $ruleName = false;
  1247. if (is_object($name) && is_a($name, 'html_quickform_rule')) {
  1248. $ruleName = !empty($name->name)? $name->name: strtolower(get_class($name));
  1249. } elseif (is_string($name) && class_exists($name)) {
  1250. $parent = strtolower($name);
  1251. do {
  1252. if ('html_quickform_rule' == strtolower($parent)) {
  1253. $ruleName = strtolower($name);
  1254. break;
  1255. }
  1256. } while ($parent = get_parent_class($parent));
  1257. }
  1258. if ($ruleName) {
  1259. $registry =& HTML_QuickForm_RuleRegistry::singleton();
  1260. $registry->registerRule($ruleName, null, $name);
  1261. }
  1262. return $ruleName;
  1263. } // end func isRuleRegistered
  1264. // }}}
  1265. // {{{ getRegisteredRules()
  1266. /**
  1267. * Returns an array of registered validation rules
  1268. *
  1269. * @since 1.0
  1270. * @access public
  1271. * @return array
  1272. */
  1273. function getRegisteredRules()
  1274. {
  1275. return array_keys($GLOBALS['_HTML_QuickForm_registered_rules']);
  1276. } // end func getRegisteredRules
  1277. // }}}
  1278. // {{{ isElementRequired()
  1279. /**
  1280. * Returns whether or not the form element is required
  1281. *
  1282. * @param string $element Form element name
  1283. * @since 1.0
  1284. * @access public
  1285. * @return boolean
  1286. */
  1287. function isElementRequired($element)
  1288. {
  1289. return in_array($element, $this->_required, true);
  1290. } // end func isElementRequired
  1291. // }}}
  1292. // {{{ isElementFrozen()
  1293. /**
  1294. * Returns whether or not the form element is frozen
  1295. *
  1296. * @param string $element Form element name
  1297. * @since 1.0
  1298. * @access public
  1299. * @return boolean
  1300. */
  1301. function isElementFrozen($element)
  1302. {
  1303. if (isset($this->_elementIndex[$element])) {
  1304. return $this->_elements[$this->_elementIndex[$element]]->isFrozen();
  1305. }
  1306. return false;
  1307. } // end func isElementFrozen
  1308. // }}}
  1309. // {{{ setJsWarnings()
  1310. /**
  1311. * Sets JavaScript warning messages
  1312. *
  1313. * @param string $pref Prefix warning
  1314. * @param string $post Postfix warning
  1315. * @since 1.1
  1316. * @access public
  1317. * @return void
  1318. */
  1319. function setJsWarnings($pref, $post)
  1320. {
  1321. $this->_jsPrefix = $pref;
  1322. $this->_jsPostfix = $post;
  1323. } // end func setJsWarnings
  1324. // }}}
  1325. // {{{ setRequiredNote()
  1326. /**
  1327. * Sets required-note
  1328. *
  1329. * @param string $note Message indicating some elements are required
  1330. * @since 1.1
  1331. * @access public
  1332. * @return void
  1333. */
  1334. function setRequiredNote($note)
  1335. {
  1336. $this->_requiredNote = $note;
  1337. } // end func setRequiredNote
  1338. // }}}
  1339. // {{{ getRequiredNote()
  1340. /**
  1341. * Returns the required note
  1342. *
  1343. * @since 2.0
  1344. * @access public
  1345. * @return string
  1346. */
  1347. function getRequiredNote()
  1348. {
  1349. return $this->_requiredNote;
  1350. } // end func getRequiredNote
  1351. // }}}
  1352. // {{{ validate()
  1353. /**
  1354. * Performs the server side validation
  1355. * @access public
  1356. * @since 1.0
  1357. * @return boolean true if no error found
  1358. */
  1359. function validate()
  1360. {
  1361. if (count($this->_rules) == 0 && count($this->_formRules) == 0 &&
  1362. $this->isSubmitted()) {
  1363. return (0 == count($this->_errors));
  1364. } elseif (!$this->isSubmitted()) {
  1365. return false;
  1366. }
  1367. include_once('HTML/QuickForm/RuleRegistry.php');
  1368. $registry =& HTML_QuickForm_RuleRegistry::singleton();
  1369. foreach ($this->_rules as $target => $rules) {
  1370. $submitValue = $this->getSubmitValue($target);
  1371. foreach ($rules as $rule) {
  1372. if ((isset($rule['group']) && isset($this->_errors[$rule['group']])) ||
  1373. isset($this->_errors[$target])) {
  1374. continue 2;
  1375. }
  1376. // If element is not required and is empty, we shouldn't validate it
  1377. if (!$this->isElementRequired($target)) {
  1378. if (!isset($submitValue) || '' == $submitValue) {
  1379. continue 2;
  1380. // Fix for bug #3501: we shouldn't validate not uploaded files, either.
  1381. // Unfortunately, we can't just use $element->isUploadedFile() since
  1382. // the element in question can be buried in group. Thus this hack.
  1383. } elseif (is_array($submitValue)) {
  1384. if (false === ($pos = strpos($target, '['))) {
  1385. $isUpload = !empty($this->_submitFiles[$target]);
  1386. } else {
  1387. $base = str_replace(
  1388. array('\\', '\''), array('\\\\', '\\\''),
  1389. substr($target, 0, $pos)
  1390. );
  1391. $idx = "['" . str_replace(
  1392. array('\\', '\'', ']', '['), array('\\\\', '\\\'', '', "']['"),
  1393. substr($target, $pos + 1, -1)
  1394. ) . "']";
  1395. eval("\$isUpload = isset(\$this->_submitFiles['{$base}']['name']{$idx});");
  1396. }
  1397. if ($isUpload && (!isset($submitValue['error']) || 0 != $submitValue['error'])) {
  1398. continue 2;
  1399. }
  1400. }
  1401. }
  1402. if (isset($rule['dependent']) && is_array($rule['dependent'])) {
  1403. $values = array($submitValue);
  1404. foreach ($rule['dependent'] as $elName) {
  1405. $values[] = $this->getSubmitValue($elName);
  1406. }
  1407. $result = $registry->validate($rule['type'], $values, $rule['format'], true);
  1408. } elseif (is_array($submitValue) && !isset($rule['howmany'])) {
  1409. $result = $registry->validate($rule['type'], $submitValue, $rule['format'], true);
  1410. } else {
  1411. $result = $registry->validate($rule['type'], $submitValue, $rule['format'], false);
  1412. }
  1413. if (!$result || (!empty($rule['howmany']) && $rule['howmany'] > (int)$result)) {
  1414. if (isset($rule['group'])) {
  1415. $this->_errors[$rule['group']] = $rule['message'];
  1416. } else {
  1417. $this->_errors[$target] = $rule['message'];
  1418. }
  1419. }
  1420. }
  1421. }
  1422. // process the global rules now
  1423. foreach ($this->_formRules as $rule) {
  1424. if (true !== ($res = call_user_func($rule, $this->_submitValues, $this->_submitFiles))) {
  1425. if (is_array($res)) {
  1426. $this->_errors += $res;
  1427. } else {
  1428. return PEAR::raiseError(null, QUICKFORM_ERROR, null, E_USER_WARNING, 'Form rule callback returned invalid value in HTML_QuickForm::validate()', 'HTML_QuickForm_Error', true);
  1429. }
  1430. }
  1431. }
  1432. return (0 == count($this->_errors));
  1433. } // end func validate
  1434. // }}}
  1435. // {{{ freeze()
  1436. /**
  1437. * Displays elements without HTML input tags
  1438. *
  1439. * @param mixed $elementList array or string of element(s) to be frozen
  1440. * @since 1.0
  1441. * @access public
  1442. * @throws HTML_QuickForm_Error
  1443. */
  1444. function freeze($elementList=null)
  1445. {
  1446. if (!isset($elementList)) {
  1447. $this->_freezeAll = true;
  1448. $elementList = array();
  1449. } else {
  1450. if (!is_array($elementList)) {
  1451. $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
  1452. }
  1453. $elementList = array_flip($elementList);
  1454. }
  1455. foreach (array_keys($this->_elements) as $key) {
  1456. $name = $this->_elements[$key]->getName();
  1457. if ($this->_freezeAll || isset($elementList[$name])) {
  1458. $this->_elements[$key]->freeze();
  1459. unset($elementList[$name]);
  1460. }
  1461. }
  1462. if (!empty($elementList)) {
  1463. return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Nonexistant element(s): '" . implode("', '", array_keys($elementList)) . "' in HTML_QuickForm::freeze()", 'HTML_QuickForm_Error', true);
  1464. }
  1465. return true;
  1466. } // end func freeze
  1467. // }}}
  1468. // {{{ isFrozen()
  1469. /**
  1470. * Returns whether or not the whole form is frozen
  1471. *
  1472. * @since 3.0
  1473. * @access public
  1474. * @return boolean
  1475. */
  1476. function isFrozen()
  1477. {
  1478. return $this->_freezeAll;
  1479. } // end func isFrozen
  1480. // }}}
  1481. // {{{ process()
  1482. /**
  1483. * Performs the form data processing
  1484. *
  1485. * @param mixed $callback Callback, either function name or array(&$object, 'method')
  1486. * @param bool $mergeFiles Whether uploaded files should be processed too
  1487. * @since 1.0
  1488. * @access public
  1489. * @throws HTML_QuickForm_Error
  1490. */
  1491. function process($callback, $mergeFiles = true)
  1492. {
  1493. if (!is_callable($callback)) {
  1494. return PEAR::raiseError(null, QUICKFORM_INVALID_PROCESS, null, E_USER_WARNING, "Callback function does not exist in QuickForm::process()", 'HTML_QuickForm_Error', true);
  1495. }
  1496. $values = ($mergeFiles === true) ? HTML_QuickForm::arrayMerge($this->_submitValues, $this->_submitFiles) : $this->_submitValues;
  1497. return call_user_func($callback, $values);
  1498. } // end func process
  1499. // }}}
  1500. // {{{ accept()
  1501. /**
  1502. * Accepts a renderer
  1503. *
  1504. * @param object An HTML_QuickForm_Renderer object
  1505. * @since 3.0
  1506. * @access public
  1507. * @return void
  1508. */
  1509. function accept(&$renderer)
  1510. {
  1511. $renderer->startForm($this);
  1512. foreach (array_keys($this->_elements) as $key) {
  1513. $element =& $this->_elements[$key];
  1514. $elementName = $element->getName();
  1515. $required = ($this->isElementRequired($elementName) && !$element->isFrozen());
  1516. $error = $this->getElementError($elementName);
  1517. $element->accept($renderer, $required, $error);
  1518. }
  1519. $renderer->finishForm($this);
  1520. } // end func accept
  1521. // }}}
  1522. // {{{ defaultRenderer()
  1523. /**
  1524. * Returns a reference to default renderer object
  1525. *
  1526. * @access public
  1527. * @since 3.0
  1528. * @return object a default renderer object
  1529. */
  1530. function &defaultRenderer()
  1531. {
  1532. if (!isset($GLOBALS['_HTML_QuickForm_default_renderer'])) {
  1533. include_once('HTML/QuickForm/Renderer/Default.php');
  1534. // Suppressing a deprecation warning on PHP 5.3
  1535. //$GLOBALS['_HTML_QuickForm_default_renderer'] =& new HTML_QuickForm_Renderer_Default();
  1536. $GLOBALS['_HTML_QuickForm_default_renderer'] = new HTML_QuickForm_Renderer_Default();
  1537. //
  1538. }
  1539. return $GLOBALS['_HTML_QuickForm_default_renderer'];
  1540. } // end func defaultRenderer
  1541. // }}}
  1542. // {{{ toHtml ()
  1543. /**
  1544. * Returns an HTML version of the form
  1545. *
  1546. * @param string $in_data (optional) Any extra data to insert right
  1547. * before form is rendered. Useful when using templates.
  1548. *
  1549. * @return string Html version of the form
  1550. * @since 1.0
  1551. * @access public
  1552. */
  1553. function toHtml ($in_data = null)
  1554. {
  1555. if (!is_null($in_data)) {
  1556. $this->addElement('html', $in_data);
  1557. }
  1558. $renderer =& $this->defaultRenderer();
  1559. $this->accept($renderer);
  1560. return $renderer->toHtml();
  1561. } // end func toHtml
  1562. // }}}
  1563. // {{{ getValidationScript()
  1564. /**
  1565. * Returns the client side validation script
  1566. *
  1567. * @since 2.0
  1568. * @access public
  1569. * @return string Javascript to perform validation, empty string if no 'client' rules were added
  1570. */
  1571. function getValidationScript()
  1572. {
  1573. if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
  1574. return '';
  1575. }
  1576. include_once('HTML/QuickForm/RuleRegistry.php');
  1577. $registry =& HTML_QuickForm_RuleRegistry::singleton();
  1578. $test = array();
  1579. $js_escape = array(
  1580. "\r" => '\r',
  1581. "\n" => '\n',
  1582. "\t" => '\t',
  1583. "'" => "\\'",
  1584. '"' => '\"',
  1585. '\\' => '\\\\'
  1586. );
  1587. foreach ($this->_rules as $elementName => $rules) {
  1588. foreach ($rules as $rule) {
  1589. if ('client' == $rule['validation']) {
  1590. unset($element);
  1591. $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
  1592. $rule['message'] = strtr($rule['message'], $js_escape);
  1593. if (isset($rule['group'])) {
  1594. $group =& $this->getElement($rule['group']);
  1595. // No JavaScript validation for frozen elements
  1596. if ($group->isFrozen()) {
  1597. continue 2;
  1598. }
  1599. $elements =& $group->getElements();
  1600. foreach (array_keys($elements) as $key) {
  1601. if ($elementName == $group->getElementName($key)) {
  1602. $element =& $elements[$key];
  1603. break;
  1604. }
  1605. }
  1606. } elseif ($dependent) {
  1607. $element = array();
  1608. $element[] =& $this->getElement($elementName);
  1609. foreach ($rule['dependent'] as $elName) {
  1610. $element[] =& $this->getElement($elName);
  1611. }
  1612. } else {
  1613. $element =& $this->getElement($elementName);
  1614. }
  1615. // No JavaScript validation for frozen elements
  1616. if (is_object($element) && $element->isFrozen()) {
  1617. continue 2;
  1618. } elseif (is_array($element)) {
  1619. foreach (array_keys($element) as $key) {
  1620. if ($element[$key]->isFrozen()) {
  1621. continue 3;
  1622. }
  1623. }
  1624. }
  1625. $test[] = $registry->getValidationScript($element, $elementName, $rule);
  1626. }
  1627. }
  1628. }
  1629. if (count($test) > 0) {
  1630. return
  1631. "\n<script type=\"text/javascript\">\n" .
  1632. "//<![CDATA[\n" .
  1633. "function validate_" . $this->_attributes['id'] . "(frm) {\n" .
  1634. " var value = '';\n" .
  1635. " var errFlag = new Array();\n" .
  1636. " var _qfGroups = {};\n" .
  1637. " _qfMsg = '';\n\n" .
  1638. join("\n", $test) .
  1639. "\n if (_qfMsg != '') {\n" .
  1640. " _qfMsg = '" . strtr($this->_jsPrefix, $js_escape) . "' + _qfMsg;\n" .
  1641. " _qfMsg = _qfMsg + '\\n" . strtr($this->_jsPostfix, $js_escape) . "';\n" .
  1642. " alert(_qfMsg);\n" .
  1643. " return false;\n" .
  1644. " }\n" .
  1645. " return true;\n" .
  1646. "}\n" .
  1647. "//]]>\n" .
  1648. "</script>";
  1649. }
  1650. return '';
  1651. } // end func getValidationScript
  1652. // }}}
  1653. // {{{ getSubmitValues()
  1654. /**
  1655. * Returns the values submitted by the form
  1656. *
  1657. * @since 2.0
  1658. * @access public
  1659. * @param bool Whether uploaded files should be returned too
  1660. * @return array
  1661. */
  1662. function getSubmitValues($mergeFiles = false)
  1663. {
  1664. return $mergeFiles? HTML_QuickForm::arrayMerge($this->_submitValues, $this->_submitFiles): $this->_submitValues;
  1665. } // end func getSubmitValues
  1666. // }}}
  1667. // {{{ toArray()
  1668. /**
  1669. * Returns the form's contents in an array.
  1670. *
  1671. * The description of the array structure is in HTML_QuickForm_Renderer_Array docs
  1672. *
  1673. * @since 2.0
  1674. * @access public
  1675. * @param bool Whether to collect hidden elements (passed to the Renderer's constructor)
  1676. * @return array of form contents
  1677. */
  1678. function toArray($collectHidden = false)
  1679. {
  1680. include_once 'HTML/QuickForm/Renderer/Array.php';
  1681. // Suppressing a deprecation warning on PHP 5.3
  1682. //$renderer =& new HTML_QuickForm_Renderer_Array($collectHidden);
  1683. $renderer = new HTML_QuickForm_Renderer_Array($collectHidden);
  1684. //
  1685. $this->accept($renderer);
  1686. return $renderer->toArray();
  1687. } // end func toArray
  1688. // }}}
  1689. // {{{ exportValue()
  1690. /**
  1691. * Returns a 'safe' element's value
  1692. *
  1693. * This method first tries to find a cleaned-up submitted value,
  1694. * it will return a value set by setValue()/setDefaults()/setConstants()
  1695. * if submitted value does not exist for the given element.
  1696. *
  1697. * @param string Name of an element
  1698. * @access public
  1699. * @return mixed
  1700. */
  1701. function exportValue($element)
  1702. {
  1703. if (!isset($this->_elementIndex[$element])) {
  1704. return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$element' does not exist in HTML_QuickForm::getElementValue()", 'HTML_QuickForm_Error', true);
  1705. }
  1706. $value = $this->_elements[$this->_elementIndex[$element]]->exportValue($this->_submitValues, false);
  1707. if (isset($this->_duplicateIndex[$element])) {
  1708. foreach ($this->_duplicateIndex[$element] as $index) {
  1709. if (null !== ($v = $this->_elements[$index]->exportValue($this->_submitValues, false))) {
  1710. if (is_array($value)) {
  1711. $value[] = $v;
  1712. } else {
  1713. $value = (null === $value)? $v: array($value, $v);
  1714. }
  1715. }
  1716. }
  1717. }
  1718. return $value;
  1719. }
  1720. // }}}
  1721. // {{{ exportValues()
  1722. /**
  1723. * Returns 'safe' elements' values
  1724. *
  1725. * Unlike getSubmitValues(), this will return only the values
  1726. * corresponding to the elements present in the form.
  1727. *
  1728. * @param mixed Array/string of element names, whose values we want. If not set then return all elements.
  1729. * @access public
  1730. * @return array An assoc array of elements' values
  1731. * @throws HTML_QuickForm_Error
  1732. */
  1733. function exportValues($elementList = null)
  1734. {
  1735. $values = array();
  1736. if (null === $elementList) {
  1737. // iterate over all elements, calling their exportValue() methods
  1738. foreach (array_keys($this->_elements) as $key) {
  1739. $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
  1740. if (is_array($value)) {
  1741. // This shit throws a bogus warning in PHP 4.3.x
  1742. $values = HTML_QuickForm::arrayMerge($values, $value);
  1743. }
  1744. }
  1745. } else {
  1746. if (!is_array($elementList)) {
  1747. $elementList = array_map('trim', explode(',', $elementList));
  1748. }
  1749. foreach ($elementList as $elementName) {
  1750. $value = $this->exportValue($elementName);
  1751. if (PEAR::isError($value)) {
  1752. return $value;
  1753. }
  1754. $values[$elementName] = $value;
  1755. }
  1756. }
  1757. return $values;
  1758. }
  1759. // }}}
  1760. // {{{ isSubmitted()
  1761. /**
  1762. * Tells whether the form was already submitted
  1763. *
  1764. * This is useful since the _submitFiles and _submitValues arrays
  1765. * may be completely empty after the trackSubmit value is removed.
  1766. *
  1767. * @access public
  1768. * @return bool
  1769. */
  1770. function isSubmitted()
  1771. {
  1772. return $this->_flagSubmitted;
  1773. }
  1774. // }}}
  1775. // {{{ isError()
  1776. /**
  1777. * Tell whether a result from a QuickForm method is an error (an instance of HTML_QuickForm_Error)
  1778. *
  1779. * @access public
  1780. * @param mixed result code
  1781. * @return bool whether $value is an error
  1782. */
  1783. function isError($value)
  1784. {
  1785. return (is_object($value) && is_a($value, 'html_quickform_error'));
  1786. } // end func isError
  1787. // }}}
  1788. // {{{ errorMessage()
  1789. /**
  1790. * Return a textual error message for an QuickForm error code
  1791. *
  1792. * @access public
  1793. * @param int error code
  1794. * @return string error message
  1795. */
  1796. function errorMessage($value)
  1797. {
  1798. // make the variable static so that it only has to do the defining on the first call
  1799. static $errorMessages;
  1800. // define the varies error messages
  1801. if (!isset($errorMessages)) {
  1802. $errorMessages = array(
  1803. QUICKFORM_OK => 'no error',
  1804. QUICKFORM_ERROR => 'unknown error',
  1805. QUICKFORM_INVALID_RULE => 'the rule does not exist as a registered rule',
  1806. QUICKFORM_NONEXIST_ELEMENT => 'nonexistent html element',
  1807. QUICKFORM_INVALID_FILTER => 'invalid filter',
  1808. QUICKFORM_UNREGISTERED_ELEMENT => 'unregistered element',
  1809. QUICKFORM_INVALID_ELEMENT_NAME => 'element already exists',
  1810. QUICKFORM_INVALID_PROCESS => 'process callback does not exist',
  1811. QUICKFORM_DEPRECATED => 'method is deprecated',
  1812. QUICKFORM_INVALID_DATASOURCE => 'datasource is not an object'
  1813. );
  1814. }
  1815. // If this is an error object, then grab the corresponding error code
  1816. if (HTML_QuickForm::isError($value)) {
  1817. $value = $value->getCode();
  1818. }
  1819. // return the textual error message corresponding to the code
  1820. return isset($errorMessages[$value]) ? $errorMessages[$value] : $errorMessages[QUICKFORM_ERROR];
  1821. } // end func errorMessage
  1822. // }}}
  1823. } // end class HTML_QuickForm
  1824. class HTML_QuickForm_Error extends PEAR_Error {
  1825. // {{{ properties
  1826. /**
  1827. * Prefix for all error messages
  1828. * @var string
  1829. */
  1830. var $error_message_prefix = 'QuickForm Error: ';
  1831. // }}}
  1832. // {{{ constructor
  1833. /**
  1834. * Creates a quickform error object, extending the PEAR_Error class
  1835. *
  1836. * @param int $code the error code
  1837. * @param int $mode the reaction to the error, either return, die or trigger/callback
  1838. * @param int $level intensity of the error (PHP error code)
  1839. * @param mixed $debuginfo any information that can inform user as to nature of the error
  1840. */
  1841. function HTML_QuickForm_Error($code = QUICKFORM_ERROR, $mode = PEAR_ERROR_RETURN,
  1842. $level = E_USER_NOTICE, $debuginfo = null)
  1843. {
  1844. if (is_int($code)) {
  1845. $this->PEAR_Error(HTML_QuickForm::errorMessage($code), $code, $mode, $level, $debuginfo);
  1846. } else {
  1847. $this->PEAR_Error("Invalid error code: $code", QUICKFORM_ERROR, $mode, $level, $debuginfo);
  1848. }
  1849. }
  1850. // }}}
  1851. } // end class HTML_QuickForm_Error
  1852. ?>