QuickForm.php 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013
  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. $elementObject =& new $className();
  519. for ($i = 0; $i < 5; $i++) {
  520. if (!isset($args[$i])) {
  521. $args[$i] = null;
  522. }
  523. }
  524. $err = $elementObject->onQuickFormEvent($event, $args, $this);
  525. if ($err !== true) {
  526. return $err;
  527. }
  528. return $elementObject;
  529. } // end func _loadElement
  530. // }}}
  531. // {{{ addElement()
  532. /**
  533. * Adds an element into the form
  534. *
  535. * If $element is a string representing element type, then this
  536. * method accepts variable number of parameters, their meaning
  537. * and count depending on $element
  538. *
  539. * @param mixed $element element object or type of element to add (text, textarea, file...)
  540. * @since 1.0
  541. * @return object reference to element
  542. * @access public
  543. * @throws HTML_QuickForm_Error
  544. */
  545. function &addElement($element)
  546. {
  547. if (is_object($element) && is_subclass_of($element, 'html_quickform_element')) {
  548. $elementObject = &$element;
  549. $elementObject->onQuickFormEvent('updateValue', null, $this);
  550. } else {
  551. $args = func_get_args();
  552. $elementObject =& $this->_loadElement('addElement', $element, array_slice($args, 1));
  553. if (PEAR::isError($elementObject)) {
  554. return $elementObject;
  555. }
  556. }
  557. $elementName = $elementObject->getName();
  558. // Add the element if it is not an incompatible duplicate
  559. if (!empty($elementName) && isset($this->_elementIndex[$elementName])) {
  560. if ($this->_elements[$this->_elementIndex[$elementName]]->getType() ==
  561. $elementObject->getType()) {
  562. $this->_elements[] =& $elementObject;
  563. $elKeys = array_keys($this->_elements);
  564. $this->_duplicateIndex[$elementName][] = end($elKeys);
  565. } else {
  566. $error = PEAR::raiseError(null, QUICKFORM_INVALID_ELEMENT_NAME, null, E_USER_WARNING, "Element '$elementName' already exists in HTML_QuickForm::addElement()", 'HTML_QuickForm_Error', true);
  567. return $error;
  568. }
  569. } else {
  570. $this->_elements[] =& $elementObject;
  571. $elKeys = array_keys($this->_elements);
  572. $this->_elementIndex[$elementName] = end($elKeys);
  573. }
  574. if ($this->_freezeAll) {
  575. $elementObject->freeze();
  576. }
  577. return $elementObject;
  578. } // end func addElement
  579. // }}}
  580. // {{{ insertElementBefore()
  581. /**
  582. * Inserts a new element right before the other element
  583. *
  584. * Warning: it is not possible to check whether the $element is already
  585. * added to the form, therefore if you want to move the existing form
  586. * element to a new position, you'll have to use removeElement():
  587. * $form->insertElementBefore($form->removeElement('foo', false), 'bar');
  588. *
  589. * @access public
  590. * @since 3.2.4
  591. * @param object HTML_QuickForm_element Element to insert
  592. * @param string Name of the element before which the new one is inserted
  593. * @return object HTML_QuickForm_element reference to inserted element
  594. * @throws HTML_QuickForm_Error
  595. */
  596. function &insertElementBefore(&$element, $nameAfter)
  597. {
  598. if (!empty($this->_duplicateIndex[$nameAfter])) {
  599. $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);
  600. return $error;
  601. } elseif (!$this->elementExists($nameAfter)) {
  602. $error = PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$nameAfter' does not exist in HTML_QuickForm::insertElementBefore()", 'HTML_QuickForm_Error', true);
  603. return $error;
  604. }
  605. $elementName = $element->getName();
  606. $targetIdx = $this->_elementIndex[$nameAfter];
  607. $duplicate = false;
  608. // Like in addElement(), check that it's not an incompatible duplicate
  609. if (!empty($elementName) && isset($this->_elementIndex[$elementName])) {
  610. if ($this->_elements[$this->_elementIndex[$elementName]]->getType() != $element->getType()) {
  611. $error = PEAR::raiseError(null, QUICKFORM_INVALID_ELEMENT_NAME, null, E_USER_WARNING, "Element '$elementName' already exists in HTML_QuickForm::insertElementBefore()", 'HTML_QuickForm_Error', true);
  612. return $error;
  613. }
  614. $duplicate = true;
  615. }
  616. // Move all the elements after added back one place, reindex _elementIndex and/or _duplicateIndex
  617. $elKeys = array_keys($this->_elements);
  618. for ($i = end($elKeys); $i >= $targetIdx; $i--) {
  619. if (isset($this->_elements[$i])) {
  620. $currentName = $this->_elements[$i]->getName();
  621. $this->_elements[$i + 1] =& $this->_elements[$i];
  622. if ($this->_elementIndex[$currentName] == $i) {
  623. $this->_elementIndex[$currentName] = $i + 1;
  624. } else
  625. {
  626. if (is_array($this->_duplicateIndex[$currentName]))
  627. {
  628. $dupIdx = array_search($i, $this->_duplicateIndex[$currentName]);
  629. $this->_duplicateIndex[$currentName][$dupIdx] = $i + 1;
  630. }
  631. }
  632. unset($this->_elements[$i]);
  633. }
  634. }
  635. // Put the element in place finally
  636. $this->_elements[$targetIdx] =& $element;
  637. if (!$duplicate) {
  638. $this->_elementIndex[$elementName] = $targetIdx;
  639. } else {
  640. $this->_duplicateIndex[$elementName][] = $targetIdx;
  641. }
  642. $element->onQuickFormEvent('updateValue', null, $this);
  643. if ($this->_freezeAll) {
  644. $element->freeze();
  645. }
  646. // If not done, the elements will appear in reverse order
  647. ksort($this->_elements);
  648. return $element;
  649. }
  650. // }}}
  651. // {{{ addGroup()
  652. /**
  653. * Adds an element group
  654. * @param array $elements array of elements composing the group
  655. * @param string $name (optional)group name
  656. * @param string $groupLabel (optional)group label
  657. * @param string $separator (optional)string to separate elements
  658. * @param string $appendName (optional)specify whether the group name should be
  659. * used in the form element name ex: group[element]
  660. * @return object reference to added group of elements
  661. * @since 2.8
  662. * @access public
  663. * @throws PEAR_Error
  664. */
  665. function &addGroup($elements, $name=null, $groupLabel='', $separator=null, $appendName = true)
  666. {
  667. static $anonGroups = 1;
  668. if (0 == strlen($name)) {
  669. $name = 'qf_group_' . $anonGroups++;
  670. $appendName = false;
  671. }
  672. $group =& $this->addElement('group', $name, $groupLabel, $elements, $separator, $appendName);
  673. return $group;
  674. } // end func addGroup
  675. // }}}
  676. // {{{ &getElement()
  677. /**
  678. * Returns a reference to the element
  679. *
  680. * @param string $element Element name
  681. * @since 2.0
  682. * @access public
  683. * @return object reference to element
  684. * @throws HTML_QuickForm_Error
  685. */
  686. function &getElement($element)
  687. {
  688. if (isset($this->_elementIndex[$element])) {
  689. return $this->_elements[$this->_elementIndex[$element]];
  690. } else {
  691. $error = PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$element' does not exist in HTML_QuickForm::getElement()", 'HTML_QuickForm_Error', true);
  692. return $error;
  693. }
  694. } // end func getElement
  695. // }}}
  696. // {{{ &getElementValue()
  697. /**
  698. * Returns the element's raw value
  699. *
  700. * This returns the value as submitted by the form (not filtered)
  701. * or set via setDefaults() or setConstants()
  702. *
  703. * @param string $element Element name
  704. * @since 2.0
  705. * @access public
  706. * @return mixed element value
  707. * @throws HTML_QuickForm_Error
  708. */
  709. function &getElementValue($element)
  710. {
  711. if (!isset($this->_elementIndex[$element])) {
  712. $error = PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$element' does not exist in HTML_QuickForm::getElementValue()", 'HTML_QuickForm_Error', true);
  713. return $error;
  714. }
  715. $value = $this->_elements[$this->_elementIndex[$element]]->getValue();
  716. if (isset($this->_duplicateIndex[$element])) {
  717. foreach ($this->_duplicateIndex[$element] as $index) {
  718. if (null !== ($v = $this->_elements[$index]->getValue())) {
  719. if (is_array($value)) {
  720. $value[] = $v;
  721. } else {
  722. $value = (null === $value)? $v: array($value, $v);
  723. }
  724. }
  725. }
  726. }
  727. return $value;
  728. } // end func getElementValue
  729. // }}}
  730. // {{{ getSubmitValue()
  731. /**
  732. * Returns the elements value after submit and filter
  733. *
  734. * @param string Element name
  735. * @since 2.0
  736. * @access public
  737. * @return mixed submitted element value or null if not set
  738. */
  739. function getSubmitValue($elementName)
  740. {
  741. $value = null;
  742. if (isset($this->_submitValues[$elementName]) || isset($this->_submitFiles[$elementName])) {
  743. $value = isset($this->_submitValues[$elementName])? $this->_submitValues[$elementName]: array();
  744. if (is_array($value) && isset($this->_submitFiles[$elementName])) {
  745. foreach ($this->_submitFiles[$elementName] as $k => $v) {
  746. $value = HTML_QuickForm::arrayMerge($value, $this->_reindexFiles($this->_submitFiles[$elementName][$k], $k));
  747. }
  748. }
  749. } elseif ('file' == $this->getElementType($elementName)) {
  750. return $this->getElementValue($elementName);
  751. } elseif (false !== ($pos = strpos($elementName, '['))) {
  752. $base = str_replace(
  753. array('\\', '\''), array('\\\\', '\\\''),
  754. substr($elementName, 0, $pos)
  755. );
  756. $idx = "['" . str_replace(
  757. array('\\', '\'', ']', '['), array('\\\\', '\\\'', '', "']['"),
  758. substr($elementName, $pos + 1, -1)
  759. ) . "']";
  760. if (isset($this->_submitValues[$base])) {
  761. $value = eval("return (isset(\$this->_submitValues['{$base}']{$idx})) ? \$this->_submitValues['{$base}']{$idx} : null;");
  762. }
  763. if ((is_array($value) || null === $value) && isset($this->_submitFiles[$base])) {
  764. $props = array('name', 'type', 'size', 'tmp_name', 'error');
  765. $code = "if (!isset(\$this->_submitFiles['{$base}']['name']{$idx})) {\n" .
  766. " return null;\n" .
  767. "} else {\n" .
  768. " \$v = array();\n";
  769. foreach ($props as $prop) {
  770. $code .= " \$v = HTML_QuickForm::arrayMerge(\$v, \$this->_reindexFiles(\$this->_submitFiles['{$base}']['{$prop}']{$idx}, '{$prop}'));\n";
  771. }
  772. $fileValue = eval($code . " return \$v;\n}\n");
  773. if (null !== $fileValue) {
  774. $value = null === $value? $fileValue: HTML_QuickForm::arrayMerge($value, $fileValue);
  775. }
  776. }
  777. }
  778. // This is only supposed to work for groups with appendName = false
  779. if (null === $value && 'group' == $this->getElementType($elementName)) {
  780. $group =& $this->getElement($elementName);
  781. $elements =& $group->getElements();
  782. foreach (array_keys($elements) as $key) {
  783. $name = $group->getElementName($key);
  784. // prevent endless recursion in case of radios and such
  785. if ($name != $elementName) {
  786. if (null !== ($v = $this->getSubmitValue($name))) {
  787. $value[$name] = $v;
  788. }
  789. }
  790. }
  791. }
  792. return $value;
  793. } // end func getSubmitValue
  794. // }}}
  795. // {{{ _reindexFiles()
  796. /**
  797. * A helper function to change the indexes in $_FILES array
  798. *
  799. * @param mixed Some value from the $_FILES array
  800. * @param string The key from the $_FILES array that should be appended
  801. * @return array
  802. */
  803. function _reindexFiles($value, $key)
  804. {
  805. if (!is_array($value)) {
  806. return array($key => $value);
  807. } else {
  808. $ret = array();
  809. foreach ($value as $k => $v) {
  810. $ret[$k] = $this->_reindexFiles($v, $key);
  811. }
  812. return $ret;
  813. }
  814. }
  815. // }}}
  816. // {{{ getElementError()
  817. /**
  818. * Returns error corresponding to validated element
  819. *
  820. * @param string $element Name of form element to check
  821. * @since 1.0
  822. * @access public
  823. * @return string error message corresponding to checked element
  824. */
  825. function getElementError($element)
  826. {
  827. if (isset($this->_errors[$element])) {
  828. return $this->_errors[$element];
  829. }
  830. } // end func getElementError
  831. // }}}
  832. // {{{ setElementError()
  833. /**
  834. * Set error message for a form element
  835. *
  836. * @param string $element Name of form element to set error for
  837. * @param string $message Error message, if empty then removes the current error message
  838. * @since 1.0
  839. * @access public
  840. * @return void
  841. */
  842. function setElementError($element, $message = null)
  843. {
  844. if (!empty($message)) {
  845. $this->_errors[$element] = $message;
  846. } else {
  847. unset($this->_errors[$element]);
  848. }
  849. } // end func setElementError
  850. // }}}
  851. // {{{ getElementType()
  852. /**
  853. * Returns the type of the given element
  854. *
  855. * @param string $element Name of form element
  856. * @since 1.1
  857. * @access public
  858. * @return string Type of the element, false if the element is not found
  859. */
  860. function getElementType($element)
  861. {
  862. if (isset($this->_elementIndex[$element])) {
  863. return $this->_elements[$this->_elementIndex[$element]]->getType();
  864. }
  865. return false;
  866. } // end func getElementType
  867. // }}}
  868. // {{{ updateElementAttr()
  869. /**
  870. * Updates Attributes for one or more elements
  871. *
  872. * @param mixed $elements Array of element names/objects or string of elements to be updated
  873. * @param mixed $attrs Array or sting of html attributes
  874. * @since 2.10
  875. * @access public
  876. * @return void
  877. */
  878. function updateElementAttr($elements, $attrs)
  879. {
  880. if (is_string($elements)) {
  881. $elements = split('[ ]?,[ ]?', $elements);
  882. }
  883. foreach (array_keys($elements) as $key) {
  884. if (is_object($elements[$key]) && is_a($elements[$key], 'HTML_QuickForm_element')) {
  885. $elements[$key]->updateAttributes($attrs);
  886. } elseif (isset($this->_elementIndex[$elements[$key]])) {
  887. $this->_elements[$this->_elementIndex[$elements[$key]]]->updateAttributes($attrs);
  888. if (isset($this->_duplicateIndex[$elements[$key]])) {
  889. foreach ($this->_duplicateIndex[$elements[$key]] as $index) {
  890. $this->_elements[$index]->updateAttributes($attrs);
  891. }
  892. }
  893. }
  894. }
  895. } // end func updateElementAttr
  896. // }}}
  897. // {{{ removeElement()
  898. /**
  899. * Removes an element
  900. *
  901. * The method "unlinks" an element from the form, returning the reference
  902. * to the element object. If several elements named $elementName exist,
  903. * it removes the first one, leaving the others intact.
  904. *
  905. * @param string $elementName The element name
  906. * @param boolean $removeRules True if rules for this element are to be removed too
  907. * @access public
  908. * @since 2.0
  909. * @return object HTML_QuickForm_element a reference to the removed element
  910. * @throws HTML_QuickForm_Error
  911. */
  912. function &removeElement($elementName, $removeRules = true)
  913. {
  914. if (!isset($this->_elementIndex[$elementName])) {
  915. $error = PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$elementName' does not exist in HTML_QuickForm::removeElement()", 'HTML_QuickForm_Error', true);
  916. return $error;
  917. }
  918. $el =& $this->_elements[$this->_elementIndex[$elementName]];
  919. unset($this->_elements[$this->_elementIndex[$elementName]]);
  920. if (empty($this->_duplicateIndex[$elementName])) {
  921. unset($this->_elementIndex[$elementName]);
  922. } else {
  923. $this->_elementIndex[$elementName] = array_shift($this->_duplicateIndex[$elementName]);
  924. }
  925. if ($removeRules) {
  926. unset($this->_rules[$elementName], $this->_errors[$elementName]);
  927. }
  928. return $el;
  929. } // end func removeElement
  930. // }}}
  931. // {{{ addRule()
  932. /**
  933. * Adds a validation rule for the given field
  934. *
  935. * If the element is in fact a group, it will be considered as a whole.
  936. * To validate grouped elements as separated entities,
  937. * use addGroupRule instead of addRule.
  938. *
  939. * @param string $element Form element name
  940. * @param string $message Message to display for invalid data
  941. * @param string $type Rule type, use getRegisteredRules() to get types
  942. * @param string $format (optional)Required for extra rule data
  943. * @param string $validation (optional)Where to perform validation: "server", "client"
  944. * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
  945. * @param boolean $force Force the rule to be applied, even if the target form element does not exist
  946. * @since 1.0
  947. * @access public
  948. * @throws HTML_QuickForm_Error
  949. */
  950. function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
  951. {
  952. if (!$force) {
  953. if (!is_array($element) && !$this->elementExists($element)) {
  954. return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$element' does not exist in HTML_QuickForm::addRule()", 'HTML_QuickForm_Error', true);
  955. } elseif (is_array($element)) {
  956. foreach ($element as $el) {
  957. if (!$this->elementExists($el)) {
  958. return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$el' does not exist in HTML_QuickForm::addRule()", 'HTML_QuickForm_Error', true);
  959. }
  960. }
  961. }
  962. }
  963. if (false === ($newName = $this->isRuleRegistered($type, true))) {
  964. return PEAR::raiseError(null, QUICKFORM_INVALID_RULE, null, E_USER_WARNING, "Rule '$type' is not registered in HTML_QuickForm::addRule()", 'HTML_QuickForm_Error', true);
  965. } elseif (is_string($newName)) {
  966. $type = $newName;
  967. }
  968. if (is_array($element)) {
  969. $dependent = $element;
  970. $element = array_shift($dependent);
  971. } else {
  972. $dependent = null;
  973. }
  974. if ($type == 'required' || $type == 'uploadedfile') {
  975. $this->_required[] = $element;
  976. }
  977. if (!isset($this->_rules[$element])) {
  978. $this->_rules[$element] = array();
  979. }
  980. if ($validation == 'client') {
  981. $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_attributes['id'] . '; } catch(e) { return true; } return myValidator(this);'));
  982. }
  983. $this->_rules[$element][] = array(
  984. 'type' => $type,
  985. 'format' => $format,
  986. 'message' => $message,
  987. 'validation' => $validation,
  988. 'reset' => $reset,
  989. 'dependent' => $dependent
  990. );
  991. } // end func addRule
  992. // }}}
  993. // {{{ addGroupRule()
  994. /**
  995. * Adds a validation rule for the given group of elements
  996. *
  997. * Only groups with a name can be assigned a validation rule
  998. * Use addGroupRule when you need to validate elements inside the group.
  999. * Use addRule if you need to validate the group as a whole. In this case,
  1000. * the same rule will be applied to all elements in the group.
  1001. * Use addRule if you need to validate the group against a function.
  1002. *
  1003. * @param string $group Form group name
  1004. * @param mixed $arg1 Array for multiple elements or error message string for one element
  1005. * @param string $type (optional)Rule type use getRegisteredRules() to get types
  1006. * @param string $format (optional)Required for extra rule data
  1007. * @param int $howmany (optional)How many valid elements should be in the group
  1008. * @param string $validation (optional)Where to perform validation: "server", "client"
  1009. * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
  1010. * @since 2.5
  1011. * @access public
  1012. * @throws HTML_QuickForm_Error
  1013. */
  1014. function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
  1015. {
  1016. if (!$this->elementExists($group)) {
  1017. return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Group '$group' does not exist in HTML_QuickForm::addGroupRule()", 'HTML_QuickForm_Error', true);
  1018. }
  1019. $groupObj =& $this->getElement($group);
  1020. if (is_array($arg1)) {
  1021. $required = 0;
  1022. foreach ($arg1 as $elementIndex => $rules) {
  1023. $elementName = $groupObj->getElementName($elementIndex);
  1024. foreach ($rules as $rule) {
  1025. $format = (isset($rule[2])) ? $rule[2] : null;
  1026. $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
  1027. $reset = isset($rule[4]) && $rule[4];
  1028. $type = $rule[1];
  1029. if (false === ($newName = $this->isRuleRegistered($type, true))) {
  1030. return PEAR::raiseError(null, QUICKFORM_INVALID_RULE, null, E_USER_WARNING, "Rule '$type' is not registered in HTML_QuickForm::addGroupRule()", 'HTML_QuickForm_Error', true);
  1031. } elseif (is_string($newName)) {
  1032. $type = $newName;
  1033. }
  1034. $this->_rules[$elementName][] = array(
  1035. 'type' => $type,
  1036. 'format' => $format,
  1037. 'message' => $rule[0],
  1038. 'validation' => $validation,
  1039. 'reset' => $reset,
  1040. 'group' => $group);
  1041. if ('required' == $type || 'uploadedfile' == $type) {
  1042. $groupObj->_required[] = $elementName;
  1043. $this->_required[] = $elementName;
  1044. $required++;
  1045. }
  1046. if ('client' == $validation) {
  1047. $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_attributes['id'] . '; } catch(e) { return true; } return myValidator(this);'));
  1048. }
  1049. }
  1050. }
  1051. if ($required > 0 && count($groupObj->getElements()) == $required) {
  1052. $this->_required[] = $group;
  1053. }
  1054. } elseif (is_string($arg1)) {
  1055. if (false === ($newName = $this->isRuleRegistered($type, true))) {
  1056. return PEAR::raiseError(null, QUICKFORM_INVALID_RULE, null, E_USER_WARNING, "Rule '$type' is not registered in HTML_QuickForm::addGroupRule()", 'HTML_QuickForm_Error', true);
  1057. } elseif (is_string($newName)) {
  1058. $type = $newName;
  1059. }
  1060. // addGroupRule() should also handle <select multiple>
  1061. if (is_a($groupObj, 'html_quickform_group')) {
  1062. // Radios need to be handled differently when required
  1063. if ($type == 'required' && $groupObj->getGroupType() == 'radio') {
  1064. $howmany = ($howmany == 0) ? 1 : $howmany;
  1065. } else {
  1066. $howmany = ($howmany == 0) ? count($groupObj->getElements()) : $howmany;
  1067. }
  1068. }
  1069. $this->_rules[$group][] = array('type' => $type,
  1070. 'format' => $format,
  1071. 'message' => $arg1,
  1072. 'validation' => $validation,
  1073. 'howmany' => $howmany,
  1074. 'reset' => $reset);
  1075. if ($type == 'required') {
  1076. $this->_required[] = $group;
  1077. }
  1078. if ($validation == 'client') {
  1079. $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_attributes['id'] . '; } catch(e) { return true; } return myValidator(this);'));
  1080. }
  1081. }
  1082. } // end func addGroupRule
  1083. // }}}
  1084. // {{{ addFormRule()
  1085. /**
  1086. * Adds a global validation rule
  1087. *
  1088. * This should be used when for a rule involving several fields or if
  1089. * you want to use some completely custom validation for your form.
  1090. * The rule function/method should return true in case of successful
  1091. * validation and array('element name' => 'error') when there were errors.
  1092. *
  1093. * @access public
  1094. * @param mixed Callback, either function name or array(&$object, 'method')
  1095. * @throws HTML_QuickForm_Error
  1096. */
  1097. function addFormRule($rule)
  1098. {
  1099. if (!is_callable($rule)) {
  1100. return PEAR::raiseError(null, QUICKFORM_INVALID_RULE, null, E_USER_WARNING, 'Callback function does not exist in HTML_QuickForm::addFormRule()', 'HTML_QuickForm_Error', true);
  1101. }
  1102. $this->_formRules[] = $rule;
  1103. }
  1104. // }}}
  1105. // {{{ applyFilter()
  1106. /**
  1107. * Applies a data filter for the given field(s)
  1108. *
  1109. * @param mixed $element Form element name or array of such names
  1110. * @param mixed $filter Callback, either function name or array(&$object, 'method')
  1111. * @since 2.0
  1112. * @access public
  1113. */
  1114. function applyFilter($element, $filter)
  1115. {
  1116. if (!is_callable($filter)) {
  1117. return PEAR::raiseError(null, QUICKFORM_INVALID_FILTER, null, E_USER_WARNING, "Callback function does not exist in QuickForm::applyFilter()", 'HTML_QuickForm_Error', true);
  1118. }
  1119. if ($element == '__ALL__') {
  1120. $this->_submitValues = $this->_recursiveFilter($filter, $this->_submitValues);
  1121. } else {
  1122. if (!is_array($element)) {
  1123. $element = array($element);
  1124. }
  1125. foreach ($element as $elName) {
  1126. $value = $this->getSubmitValue($elName);
  1127. if (null !== $value) {
  1128. if (false === strpos($elName, '[')) {
  1129. $this->_submitValues[$elName] = $this->_recursiveFilter($filter, $value);
  1130. } else {
  1131. $idx = "['" . str_replace(
  1132. array('\\', '\'', ']', '['), array('\\\\', '\\\'', '', "']['"),
  1133. $elName
  1134. ) . "']";
  1135. eval("\$this->_submitValues{$idx} = \$this->_recursiveFilter(\$filter, \$value);");
  1136. }
  1137. }
  1138. }
  1139. }
  1140. } // end func applyFilter
  1141. // }}}
  1142. // {{{ _recursiveFilter()
  1143. /**
  1144. * Recursively apply a filter function
  1145. *
  1146. * @param string $filter filter to apply
  1147. * @param mixed $value submitted values
  1148. * @since 2.0
  1149. * @access private
  1150. * @return cleaned values
  1151. */
  1152. function _recursiveFilter($filter, $value)
  1153. {
  1154. if (is_array($value)) {
  1155. $cleanValues = array();
  1156. foreach ($value as $k => $v) {
  1157. $cleanValues[$k] = $this->_recursiveFilter($filter, $v);
  1158. }
  1159. return $cleanValues;
  1160. } else {
  1161. return call_user_func($filter, $value);
  1162. }
  1163. } // end func _recursiveFilter
  1164. // }}}
  1165. // {{{ arrayMerge()
  1166. /**
  1167. * Merges two arrays
  1168. *
  1169. * Merges two array like the PHP function array_merge but recursively.
  1170. * The main difference is that existing keys will not be renumbered
  1171. * if they are integers.
  1172. *
  1173. * @access puplic
  1174. * @param array $a original array
  1175. * @param array $b array which will be merged into first one
  1176. * @return array merged array
  1177. */
  1178. function arrayMerge($a, $b)
  1179. {
  1180. foreach ($b as $k => $v) {
  1181. if (is_array($v)) {
  1182. if (isset($a[$k]) && !is_array($a[$k])) {
  1183. $a[$k] = $v;
  1184. } else {
  1185. if (!isset($a[$k])) {
  1186. $a[$k] = array();
  1187. }
  1188. $a[$k] = HTML_QuickForm::arrayMerge($a[$k], $v);
  1189. }
  1190. } else {
  1191. $a[$k] = $v;
  1192. }
  1193. }
  1194. return $a;
  1195. } // end func arrayMerge
  1196. // }}}
  1197. // {{{ isTypeRegistered()
  1198. /**
  1199. * Returns whether or not the form element type is supported
  1200. *
  1201. * @param string $type Form element type
  1202. * @since 1.0
  1203. * @access public
  1204. * @return boolean
  1205. */
  1206. function isTypeRegistered($type)
  1207. {
  1208. return isset($GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'][strtolower($type)]);
  1209. } // end func isTypeRegistered
  1210. // }}}
  1211. // {{{ getRegisteredTypes()
  1212. /**
  1213. * Returns an array of registered element types
  1214. *
  1215. * @since 1.0
  1216. * @access public
  1217. * @return array
  1218. */
  1219. function getRegisteredTypes()
  1220. {
  1221. return array_keys($GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']);
  1222. } // end func getRegisteredTypes
  1223. // }}}
  1224. // {{{ isRuleRegistered()
  1225. /**
  1226. * Returns whether or not the given rule is supported
  1227. *
  1228. * @param string $name Validation rule name
  1229. * @param bool Whether to automatically register subclasses of HTML_QuickForm_Rule
  1230. * @since 1.0
  1231. * @access public
  1232. * @return mixed true if previously registered, false if not, new rule name if auto-registering worked
  1233. */
  1234. function isRuleRegistered($name, $autoRegister = false)
  1235. {
  1236. if (is_scalar($name) && isset($GLOBALS['_HTML_QuickForm_registered_rules'][$name])) {
  1237. return true;
  1238. } elseif (!$autoRegister) {
  1239. return false;
  1240. }
  1241. // automatically register the rule if requested
  1242. include_once 'HTML/QuickForm/RuleRegistry.php';
  1243. $ruleName = false;
  1244. if (is_object($name) && is_a($name, 'html_quickform_rule')) {
  1245. $ruleName = !empty($name->name)? $name->name: strtolower(get_class($name));
  1246. } elseif (is_string($name) && class_exists($name)) {
  1247. $parent = strtolower($name);
  1248. do {
  1249. if ('html_quickform_rule' == strtolower($parent)) {
  1250. $ruleName = strtolower($name);
  1251. break;
  1252. }
  1253. } while ($parent = get_parent_class($parent));
  1254. }
  1255. if ($ruleName) {
  1256. $registry =& HTML_QuickForm_RuleRegistry::singleton();
  1257. $registry->registerRule($ruleName, null, $name);
  1258. }
  1259. return $ruleName;
  1260. } // end func isRuleRegistered
  1261. // }}}
  1262. // {{{ getRegisteredRules()
  1263. /**
  1264. * Returns an array of registered validation rules
  1265. *
  1266. * @since 1.0
  1267. * @access public
  1268. * @return array
  1269. */
  1270. function getRegisteredRules()
  1271. {
  1272. return array_keys($GLOBALS['_HTML_QuickForm_registered_rules']);
  1273. } // end func getRegisteredRules
  1274. // }}}
  1275. // {{{ isElementRequired()
  1276. /**
  1277. * Returns whether or not the form element is required
  1278. *
  1279. * @param string $element Form element name
  1280. * @since 1.0
  1281. * @access public
  1282. * @return boolean
  1283. */
  1284. function isElementRequired($element)
  1285. {
  1286. return in_array($element, $this->_required, true);
  1287. } // end func isElementRequired
  1288. // }}}
  1289. // {{{ isElementFrozen()
  1290. /**
  1291. * Returns whether or not the form element is frozen
  1292. *
  1293. * @param string $element Form element name
  1294. * @since 1.0
  1295. * @access public
  1296. * @return boolean
  1297. */
  1298. function isElementFrozen($element)
  1299. {
  1300. if (isset($this->_elementIndex[$element])) {
  1301. return $this->_elements[$this->_elementIndex[$element]]->isFrozen();
  1302. }
  1303. return false;
  1304. } // end func isElementFrozen
  1305. // }}}
  1306. // {{{ setJsWarnings()
  1307. /**
  1308. * Sets JavaScript warning messages
  1309. *
  1310. * @param string $pref Prefix warning
  1311. * @param string $post Postfix warning
  1312. * @since 1.1
  1313. * @access public
  1314. * @return void
  1315. */
  1316. function setJsWarnings($pref, $post)
  1317. {
  1318. $this->_jsPrefix = $pref;
  1319. $this->_jsPostfix = $post;
  1320. } // end func setJsWarnings
  1321. // }}}
  1322. // {{{ setRequiredNote()
  1323. /**
  1324. * Sets required-note
  1325. *
  1326. * @param string $note Message indicating some elements are required
  1327. * @since 1.1
  1328. * @access public
  1329. * @return void
  1330. */
  1331. function setRequiredNote($note)
  1332. {
  1333. $this->_requiredNote = $note;
  1334. } // end func setRequiredNote
  1335. // }}}
  1336. // {{{ getRequiredNote()
  1337. /**
  1338. * Returns the required note
  1339. *
  1340. * @since 2.0
  1341. * @access public
  1342. * @return string
  1343. */
  1344. function getRequiredNote()
  1345. {
  1346. return $this->_requiredNote;
  1347. } // end func getRequiredNote
  1348. // }}}
  1349. // {{{ validate()
  1350. /**
  1351. * Performs the server side validation
  1352. * @access public
  1353. * @since 1.0
  1354. * @return boolean true if no error found
  1355. */
  1356. function validate()
  1357. {
  1358. if (count($this->_rules) == 0 && count($this->_formRules) == 0 &&
  1359. $this->isSubmitted()) {
  1360. return (0 == count($this->_errors));
  1361. } elseif (!$this->isSubmitted()) {
  1362. return false;
  1363. }
  1364. include_once('HTML/QuickForm/RuleRegistry.php');
  1365. $registry =& HTML_QuickForm_RuleRegistry::singleton();
  1366. foreach ($this->_rules as $target => $rules) {
  1367. $submitValue = $this->getSubmitValue($target);
  1368. foreach ($rules as $rule) {
  1369. if ((isset($rule['group']) && isset($this->_errors[$rule['group']])) ||
  1370. isset($this->_errors[$target])) {
  1371. continue 2;
  1372. }
  1373. // If element is not required and is empty, we shouldn't validate it
  1374. if (!$this->isElementRequired($target)) {
  1375. if (!isset($submitValue) || '' == $submitValue) {
  1376. continue 2;
  1377. // Fix for bug #3501: we shouldn't validate not uploaded files, either.
  1378. // Unfortunately, we can't just use $element->isUploadedFile() since
  1379. // the element in question can be buried in group. Thus this hack.
  1380. } elseif (is_array($submitValue)) {
  1381. if (false === ($pos = strpos($target, '['))) {
  1382. $isUpload = !empty($this->_submitFiles[$target]);
  1383. } else {
  1384. $base = str_replace(
  1385. array('\\', '\''), array('\\\\', '\\\''),
  1386. substr($target, 0, $pos)
  1387. );
  1388. $idx = "['" . str_replace(
  1389. array('\\', '\'', ']', '['), array('\\\\', '\\\'', '', "']['"),
  1390. substr($target, $pos + 1, -1)
  1391. ) . "']";
  1392. eval("\$isUpload = isset(\$this->_submitFiles['{$base}']['name']{$idx});");
  1393. }
  1394. if ($isUpload && (!isset($submitValue['error']) || 0 != $submitValue['error'])) {
  1395. continue 2;
  1396. }
  1397. }
  1398. }
  1399. if (isset($rule['dependent']) && is_array($rule['dependent'])) {
  1400. $values = array($submitValue);
  1401. foreach ($rule['dependent'] as $elName) {
  1402. $values[] = $this->getSubmitValue($elName);
  1403. }
  1404. $result = $registry->validate($rule['type'], $values, $rule['format'], true);
  1405. } elseif (is_array($submitValue) && !isset($rule['howmany'])) {
  1406. $result = $registry->validate($rule['type'], $submitValue, $rule['format'], true);
  1407. } else {
  1408. $result = $registry->validate($rule['type'], $submitValue, $rule['format'], false);
  1409. }
  1410. if (!$result || (!empty($rule['howmany']) && $rule['howmany'] > (int)$result)) {
  1411. if (isset($rule['group'])) {
  1412. $this->_errors[$rule['group']] = $rule['message'];
  1413. } else {
  1414. $this->_errors[$target] = $rule['message'];
  1415. }
  1416. }
  1417. }
  1418. }
  1419. // process the global rules now
  1420. foreach ($this->_formRules as $rule) {
  1421. if (true !== ($res = call_user_func($rule, $this->_submitValues, $this->_submitFiles))) {
  1422. if (is_array($res)) {
  1423. $this->_errors += $res;
  1424. } else {
  1425. return PEAR::raiseError(null, QUICKFORM_ERROR, null, E_USER_WARNING, 'Form rule callback returned invalid value in HTML_QuickForm::validate()', 'HTML_QuickForm_Error', true);
  1426. }
  1427. }
  1428. }
  1429. return (0 == count($this->_errors));
  1430. } // end func validate
  1431. // }}}
  1432. // {{{ freeze()
  1433. /**
  1434. * Displays elements without HTML input tags
  1435. *
  1436. * @param mixed $elementList array or string of element(s) to be frozen
  1437. * @since 1.0
  1438. * @access public
  1439. * @throws HTML_QuickForm_Error
  1440. */
  1441. function freeze($elementList=null)
  1442. {
  1443. if (!isset($elementList)) {
  1444. $this->_freezeAll = true;
  1445. $elementList = array();
  1446. } else {
  1447. if (!is_array($elementList)) {
  1448. $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
  1449. }
  1450. $elementList = array_flip($elementList);
  1451. }
  1452. foreach (array_keys($this->_elements) as $key) {
  1453. $name = $this->_elements[$key]->getName();
  1454. if ($this->_freezeAll || isset($elementList[$name])) {
  1455. $this->_elements[$key]->freeze();
  1456. unset($elementList[$name]);
  1457. }
  1458. }
  1459. if (!empty($elementList)) {
  1460. 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);
  1461. }
  1462. return true;
  1463. } // end func freeze
  1464. // }}}
  1465. // {{{ isFrozen()
  1466. /**
  1467. * Returns whether or not the whole form is frozen
  1468. *
  1469. * @since 3.0
  1470. * @access public
  1471. * @return boolean
  1472. */
  1473. function isFrozen()
  1474. {
  1475. return $this->_freezeAll;
  1476. } // end func isFrozen
  1477. // }}}
  1478. // {{{ process()
  1479. /**
  1480. * Performs the form data processing
  1481. *
  1482. * @param mixed $callback Callback, either function name or array(&$object, 'method')
  1483. * @param bool $mergeFiles Whether uploaded files should be processed too
  1484. * @since 1.0
  1485. * @access public
  1486. * @throws HTML_QuickForm_Error
  1487. */
  1488. function process($callback, $mergeFiles = true)
  1489. {
  1490. if (!is_callable($callback)) {
  1491. return PEAR::raiseError(null, QUICKFORM_INVALID_PROCESS, null, E_USER_WARNING, "Callback function does not exist in QuickForm::process()", 'HTML_QuickForm_Error', true);
  1492. }
  1493. $values = ($mergeFiles === true) ? HTML_QuickForm::arrayMerge($this->_submitValues, $this->_submitFiles) : $this->_submitValues;
  1494. return call_user_func($callback, $values);
  1495. } // end func process
  1496. // }}}
  1497. // {{{ accept()
  1498. /**
  1499. * Accepts a renderer
  1500. *
  1501. * @param object An HTML_QuickForm_Renderer object
  1502. * @since 3.0
  1503. * @access public
  1504. * @return void
  1505. */
  1506. function accept(&$renderer)
  1507. {
  1508. $renderer->startForm($this);
  1509. foreach (array_keys($this->_elements) as $key) {
  1510. $element =& $this->_elements[$key];
  1511. $elementName = $element->getName();
  1512. $required = ($this->isElementRequired($elementName) && !$element->isFrozen());
  1513. $error = $this->getElementError($elementName);
  1514. $element->accept($renderer, $required, $error);
  1515. }
  1516. $renderer->finishForm($this);
  1517. } // end func accept
  1518. // }}}
  1519. // {{{ defaultRenderer()
  1520. /**
  1521. * Returns a reference to default renderer object
  1522. *
  1523. * @access public
  1524. * @since 3.0
  1525. * @return object a default renderer object
  1526. */
  1527. function &defaultRenderer()
  1528. {
  1529. if (!isset($GLOBALS['_HTML_QuickForm_default_renderer'])) {
  1530. include_once('HTML/QuickForm/Renderer/Default.php');
  1531. $GLOBALS['_HTML_QuickForm_default_renderer'] =& new HTML_QuickForm_Renderer_Default();
  1532. }
  1533. return $GLOBALS['_HTML_QuickForm_default_renderer'];
  1534. } // end func defaultRenderer
  1535. // }}}
  1536. // {{{ toHtml ()
  1537. /**
  1538. * Returns an HTML version of the form
  1539. *
  1540. * @param string $in_data (optional) Any extra data to insert right
  1541. * before form is rendered. Useful when using templates.
  1542. *
  1543. * @return string Html version of the form
  1544. * @since 1.0
  1545. * @access public
  1546. */
  1547. function toHtml ($in_data = null)
  1548. {
  1549. if (!is_null($in_data)) {
  1550. $this->addElement('html', $in_data);
  1551. }
  1552. $renderer =& $this->defaultRenderer();
  1553. $this->accept($renderer);
  1554. return $renderer->toHtml();
  1555. } // end func toHtml
  1556. // }}}
  1557. // {{{ getValidationScript()
  1558. /**
  1559. * Returns the client side validation script
  1560. *
  1561. * @since 2.0
  1562. * @access public
  1563. * @return string Javascript to perform validation, empty string if no 'client' rules were added
  1564. */
  1565. function getValidationScript()
  1566. {
  1567. if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
  1568. return '';
  1569. }
  1570. include_once('HTML/QuickForm/RuleRegistry.php');
  1571. $registry =& HTML_QuickForm_RuleRegistry::singleton();
  1572. $test = array();
  1573. $js_escape = array(
  1574. "\r" => '\r',
  1575. "\n" => '\n',
  1576. "\t" => '\t',
  1577. "'" => "\\'",
  1578. '"' => '\"',
  1579. '\\' => '\\\\'
  1580. );
  1581. foreach ($this->_rules as $elementName => $rules) {
  1582. foreach ($rules as $rule) {
  1583. if ('client' == $rule['validation']) {
  1584. unset($element);
  1585. $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
  1586. $rule['message'] = strtr($rule['message'], $js_escape);
  1587. if (isset($rule['group'])) {
  1588. $group =& $this->getElement($rule['group']);
  1589. // No JavaScript validation for frozen elements
  1590. if ($group->isFrozen()) {
  1591. continue 2;
  1592. }
  1593. $elements =& $group->getElements();
  1594. foreach (array_keys($elements) as $key) {
  1595. if ($elementName == $group->getElementName($key)) {
  1596. $element =& $elements[$key];
  1597. break;
  1598. }
  1599. }
  1600. } elseif ($dependent) {
  1601. $element = array();
  1602. $element[] =& $this->getElement($elementName);
  1603. foreach ($rule['dependent'] as $elName) {
  1604. $element[] =& $this->getElement($elName);
  1605. }
  1606. } else {
  1607. $element =& $this->getElement($elementName);
  1608. }
  1609. // No JavaScript validation for frozen elements
  1610. if (is_object($element) && $element->isFrozen()) {
  1611. continue 2;
  1612. } elseif (is_array($element)) {
  1613. foreach (array_keys($element) as $key) {
  1614. if ($element[$key]->isFrozen()) {
  1615. continue 3;
  1616. }
  1617. }
  1618. }
  1619. $test[] = $registry->getValidationScript($element, $elementName, $rule);
  1620. }
  1621. }
  1622. }
  1623. if (count($test) > 0) {
  1624. return
  1625. "\n<script type=\"text/javascript\">\n" .
  1626. "//<![CDATA[\n" .
  1627. "function validate_" . $this->_attributes['id'] . "(frm) {\n" .
  1628. " var value = '';\n" .
  1629. " var errFlag = new Array();\n" .
  1630. " var _qfGroups = {};\n" .
  1631. " _qfMsg = '';\n\n" .
  1632. join("\n", $test) .
  1633. "\n if (_qfMsg != '') {\n" .
  1634. " _qfMsg = '" . strtr($this->_jsPrefix, $js_escape) . "' + _qfMsg;\n" .
  1635. " _qfMsg = _qfMsg + '\\n" . strtr($this->_jsPostfix, $js_escape) . "';\n" .
  1636. " alert(_qfMsg);\n" .
  1637. " return false;\n" .
  1638. " }\n" .
  1639. " return true;\n" .
  1640. "}\n" .
  1641. "//]]>\n" .
  1642. "</script>";
  1643. }
  1644. return '';
  1645. } // end func getValidationScript
  1646. // }}}
  1647. // {{{ getSubmitValues()
  1648. /**
  1649. * Returns the values submitted by the form
  1650. *
  1651. * @since 2.0
  1652. * @access public
  1653. * @param bool Whether uploaded files should be returned too
  1654. * @return array
  1655. */
  1656. function getSubmitValues($mergeFiles = false)
  1657. {
  1658. return $mergeFiles? HTML_QuickForm::arrayMerge($this->_submitValues, $this->_submitFiles): $this->_submitValues;
  1659. } // end func getSubmitValues
  1660. // }}}
  1661. // {{{ toArray()
  1662. /**
  1663. * Returns the form's contents in an array.
  1664. *
  1665. * The description of the array structure is in HTML_QuickForm_Renderer_Array docs
  1666. *
  1667. * @since 2.0
  1668. * @access public
  1669. * @param bool Whether to collect hidden elements (passed to the Renderer's constructor)
  1670. * @return array of form contents
  1671. */
  1672. function toArray($collectHidden = false)
  1673. {
  1674. include_once 'HTML/QuickForm/Renderer/Array.php';
  1675. $renderer =& new HTML_QuickForm_Renderer_Array($collectHidden);
  1676. $this->accept($renderer);
  1677. return $renderer->toArray();
  1678. } // end func toArray
  1679. // }}}
  1680. // {{{ exportValue()
  1681. /**
  1682. * Returns a 'safe' element's value
  1683. *
  1684. * This method first tries to find a cleaned-up submitted value,
  1685. * it will return a value set by setValue()/setDefaults()/setConstants()
  1686. * if submitted value does not exist for the given element.
  1687. *
  1688. * @param string Name of an element
  1689. * @access public
  1690. * @return mixed
  1691. */
  1692. function exportValue($element)
  1693. {
  1694. if (!isset($this->_elementIndex[$element])) {
  1695. return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$element' does not exist in HTML_QuickForm::getElementValue()", 'HTML_QuickForm_Error', true);
  1696. }
  1697. $value = $this->_elements[$this->_elementIndex[$element]]->exportValue($this->_submitValues, false);
  1698. if (isset($this->_duplicateIndex[$element])) {
  1699. foreach ($this->_duplicateIndex[$element] as $index) {
  1700. if (null !== ($v = $this->_elements[$index]->exportValue($this->_submitValues, false))) {
  1701. if (is_array($value)) {
  1702. $value[] = $v;
  1703. } else {
  1704. $value = (null === $value)? $v: array($value, $v);
  1705. }
  1706. }
  1707. }
  1708. }
  1709. return $value;
  1710. }
  1711. // }}}
  1712. // {{{ exportValues()
  1713. /**
  1714. * Returns 'safe' elements' values
  1715. *
  1716. * Unlike getSubmitValues(), this will return only the values
  1717. * corresponding to the elements present in the form.
  1718. *
  1719. * @param mixed Array/string of element names, whose values we want. If not set then return all elements.
  1720. * @access public
  1721. * @return array An assoc array of elements' values
  1722. * @throws HTML_QuickForm_Error
  1723. */
  1724. function exportValues($elementList = null)
  1725. {
  1726. $values = array();
  1727. if (null === $elementList) {
  1728. // iterate over all elements, calling their exportValue() methods
  1729. foreach (array_keys($this->_elements) as $key) {
  1730. $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
  1731. if (is_array($value)) {
  1732. // This shit throws a bogus warning in PHP 4.3.x
  1733. $values = HTML_QuickForm::arrayMerge($values, $value);
  1734. }
  1735. }
  1736. } else {
  1737. if (!is_array($elementList)) {
  1738. $elementList = array_map('trim', explode(',', $elementList));
  1739. }
  1740. foreach ($elementList as $elementName) {
  1741. $value = $this->exportValue($elementName);
  1742. if (PEAR::isError($value)) {
  1743. return $value;
  1744. }
  1745. $values[$elementName] = $value;
  1746. }
  1747. }
  1748. return $values;
  1749. }
  1750. // }}}
  1751. // {{{ isSubmitted()
  1752. /**
  1753. * Tells whether the form was already submitted
  1754. *
  1755. * This is useful since the _submitFiles and _submitValues arrays
  1756. * may be completely empty after the trackSubmit value is removed.
  1757. *
  1758. * @access public
  1759. * @return bool
  1760. */
  1761. function isSubmitted()
  1762. {
  1763. return $this->_flagSubmitted;
  1764. }
  1765. // }}}
  1766. // {{{ isError()
  1767. /**
  1768. * Tell whether a result from a QuickForm method is an error (an instance of HTML_QuickForm_Error)
  1769. *
  1770. * @access public
  1771. * @param mixed result code
  1772. * @return bool whether $value is an error
  1773. */
  1774. function isError($value)
  1775. {
  1776. return (is_object($value) && is_a($value, 'html_quickform_error'));
  1777. } // end func isError
  1778. // }}}
  1779. // {{{ errorMessage()
  1780. /**
  1781. * Return a textual error message for an QuickForm error code
  1782. *
  1783. * @access public
  1784. * @param int error code
  1785. * @return string error message
  1786. */
  1787. function errorMessage($value)
  1788. {
  1789. // make the variable static so that it only has to do the defining on the first call
  1790. static $errorMessages;
  1791. // define the varies error messages
  1792. if (!isset($errorMessages)) {
  1793. $errorMessages = array(
  1794. QUICKFORM_OK => 'no error',
  1795. QUICKFORM_ERROR => 'unknown error',
  1796. QUICKFORM_INVALID_RULE => 'the rule does not exist as a registered rule',
  1797. QUICKFORM_NONEXIST_ELEMENT => 'nonexistent html element',
  1798. QUICKFORM_INVALID_FILTER => 'invalid filter',
  1799. QUICKFORM_UNREGISTERED_ELEMENT => 'unregistered element',
  1800. QUICKFORM_INVALID_ELEMENT_NAME => 'element already exists',
  1801. QUICKFORM_INVALID_PROCESS => 'process callback does not exist',
  1802. QUICKFORM_DEPRECATED => 'method is deprecated',
  1803. QUICKFORM_INVALID_DATASOURCE => 'datasource is not an object'
  1804. );
  1805. }
  1806. // If this is an error object, then grab the corresponding error code
  1807. if (HTML_QuickForm::isError($value)) {
  1808. $value = $value->getCode();
  1809. }
  1810. // return the textual error message corresponding to the code
  1811. return isset($errorMessages[$value]) ? $errorMessages[$value] : $errorMessages[QUICKFORM_ERROR];
  1812. } // end func errorMessage
  1813. // }}}
  1814. } // end class HTML_QuickForm
  1815. class HTML_QuickForm_Error extends PEAR_Error {
  1816. // {{{ properties
  1817. /**
  1818. * Prefix for all error messages
  1819. * @var string
  1820. */
  1821. var $error_message_prefix = 'QuickForm Error: ';
  1822. // }}}
  1823. // {{{ constructor
  1824. /**
  1825. * Creates a quickform error object, extending the PEAR_Error class
  1826. *
  1827. * @param int $code the error code
  1828. * @param int $mode the reaction to the error, either return, die or trigger/callback
  1829. * @param int $level intensity of the error (PHP error code)
  1830. * @param mixed $debuginfo any information that can inform user as to nature of the error
  1831. */
  1832. function HTML_QuickForm_Error($code = QUICKFORM_ERROR, $mode = PEAR_ERROR_RETURN,
  1833. $level = E_USER_NOTICE, $debuginfo = null)
  1834. {
  1835. if (is_int($code)) {
  1836. $this->PEAR_Error(HTML_QuickForm::errorMessage($code), $code, $mode, $level, $debuginfo);
  1837. } else {
  1838. $this->PEAR_Error("Invalid error code: $code", QUICKFORM_ERROR, $mode, $level, $debuginfo);
  1839. }
  1840. }
  1841. // }}}
  1842. } // end class HTML_QuickForm_Error
  1843. ?>