QuickForm.php 69 KB

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