QuickForm.php 78 KB

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