QuickForm.php 75 KB

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