QuickForm.php 68 KB

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