QuickForm.php 67 KB

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