FormValidator.class.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Class FormValidator
  5. * create/manipulate/validate user input.
  6. */
  7. class FormValidator extends HTML_QuickForm
  8. {
  9. const LAYOUT_HORIZONTAL = 'horizontal';
  10. const LAYOUT_INLINE = 'inline';
  11. const LAYOUT_BOX = 'box';
  12. const LAYOUT_BOX_NO_LABEL = 'box-no-label';
  13. public $with_progress_bar = false;
  14. private $layout;
  15. /**
  16. * Constructor
  17. * @param string $name Name of the form
  18. * @param string $method (optional Method ('post' (default) or 'get')
  19. * @param string $action (optional Action (default is $PHP_SELF)
  20. * @param string $target (optional Form's target defaults to '_self'
  21. * @param mixed $attributes (optional) Extra attributes for <form> tag
  22. * @param string $layout
  23. * @param bool $trackSubmit (optional) Whether to track if the form was
  24. * submitted by adding a special hidden field (default = true)
  25. */
  26. public function __construct(
  27. $name,
  28. $method = 'post',
  29. $action = '',
  30. $target = '',
  31. $attributes = array(),
  32. $layout = self::LAYOUT_HORIZONTAL,
  33. $trackSubmit = true
  34. ) {
  35. // Default form class.
  36. if (is_array($attributes) && !isset($attributes['class']) || empty($attributes)) {
  37. $attributes['class'] = 'form-horizontal';
  38. }
  39. if (isset($attributes['class']) && strpos($attributes['class'], 'form-search') !== false) {
  40. $layout = 'inline';
  41. }
  42. $this->setLayout($layout);
  43. switch ($layout) {
  44. case self::LAYOUT_HORIZONTAL:
  45. $attributes['class'] = 'form-horizontal';
  46. break;
  47. case self::LAYOUT_INLINE:
  48. case self::LAYOUT_BOX:
  49. $attributes['class'] = 'form-inline';
  50. break;
  51. }
  52. parent::__construct($name, $method, $action, $target, $attributes, $trackSubmit);
  53. // Modify the default templates
  54. $renderer = & $this->defaultRenderer();
  55. // Form template
  56. $formTemplate = $this->getFormTemplate();
  57. $renderer->setFormTemplate($formTemplate);
  58. // Element template
  59. if (isset($attributes['class']) && $attributes['class'] == 'form-inline') {
  60. $elementTemplate = ' {label} {element} ';
  61. $renderer->setElementTemplate($elementTemplate);
  62. } elseif (isset($attributes['class']) && $attributes['class'] == 'form-search') {
  63. $elementTemplate = ' {label} {element} ';
  64. $renderer->setElementTemplate($elementTemplate);
  65. } else {
  66. $renderer->setElementTemplate($this->getDefaultElementTemplate());
  67. // Display a gray div in the buttons
  68. $templateSimple = '<div class="form-actions">{label} {element}</div>';
  69. $renderer->setElementTemplate($templateSimple, 'submit_in_actions');
  70. //Display a gray div in the buttons + makes the button available when scrolling
  71. $templateBottom = '<div class="form-actions bottom_actions bg-form">{label} {element}</div>';
  72. $renderer->setElementTemplate($templateBottom, 'submit_fixed_in_bottom');
  73. //When you want to group buttons use something like this
  74. /* $group = array();
  75. $group[] = $form->createElement('button', 'mark_all', get_lang('MarkAll'));
  76. $group[] = $form->createElement('button', 'unmark_all', get_lang('UnmarkAll'));
  77. $form->addGroup($group, 'buttons_in_action');
  78. */
  79. $renderer->setElementTemplate($templateSimple, 'buttons_in_action');
  80. $templateSimpleRight = '<div class="form-actions"> <div class="pull-right">{label} {element}</div></div>';
  81. $renderer->setElementTemplate($templateSimpleRight, 'buttons_in_action_right');
  82. }
  83. //Set Header template
  84. $renderer->setHeaderTemplate('<legend>{header}</legend>');
  85. //Set required field template
  86. $this->setRequiredNote('<span class="form_required">*</span> <small>' . get_lang('ThisFieldIsRequired') . '</small>');
  87. $noteTemplate = <<<EOT
  88. <div class="form-group">
  89. <div class="col-sm-offset-2 col-sm-10">{requiredNote}</div>
  90. </div>
  91. EOT;
  92. $renderer->setRequiredNoteTemplate($noteTemplate);
  93. }
  94. /**
  95. * @return string
  96. */
  97. public function getFormTemplate()
  98. {
  99. return '<form{attributes}>
  100. <fieldset>
  101. {content}
  102. </fieldset>
  103. {hidden}
  104. </form>';
  105. }
  106. /**
  107. * @return string
  108. */
  109. public function getDefaultElementTemplate()
  110. {
  111. return '
  112. <div class="form-group {error_class}">
  113. <label {label-for} class="col-sm-2 control-label {extra_label_class}" >
  114. <!-- BEGIN required --><span class="form_required">*</span><!-- END required -->
  115. {label}
  116. </label>
  117. <div class="col-sm-8">
  118. {icon}
  119. {element}
  120. <!-- BEGIN label_2 -->
  121. <p class="help-block">{label_2}</p>
  122. <!-- END label_2 -->
  123. <!-- BEGIN error -->
  124. <span class="help-inline">{error}</span>
  125. <!-- END error -->
  126. </div>
  127. <div class="col-sm-2">
  128. <!-- BEGIN label_3 -->
  129. {label_3}
  130. <!-- END label_3 -->
  131. </div>
  132. </div>';
  133. }
  134. /**
  135. * @return string
  136. */
  137. public function getLayout()
  138. {
  139. return $this->layout;
  140. }
  141. /**
  142. * @param string $layout
  143. */
  144. public function setLayout($layout)
  145. {
  146. $this->layout = $layout;
  147. }
  148. /**
  149. * Adds a text field to the form.
  150. * A trim-filter is attached to the field.
  151. * @param string $label The label for the form-element
  152. * @param string $name The element name
  153. * @param bool $required (optional) Is the form-element required (default=true)
  154. * @param array $attributes (optional) List of attributes for the form-element
  155. */
  156. public function addText($name, $label, $required = true, $attributes = array())
  157. {
  158. $this->addElement('text', $name, $label, $attributes);
  159. $this->applyFilter($name, 'trim');
  160. if ($required) {
  161. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  162. }
  163. }
  164. /**
  165. * The "date_range_picker" element creates 2 hidden fields
  166. * "elementName" + "_start" and "elementName" + "_end"
  167. * For example if the name is "range", you will have 2 new fields
  168. * when executing $form->getSubmitValues()
  169. * "range_start" and "range_end"
  170. *
  171. * @param string $name
  172. * @param string $label
  173. * @param bool $required
  174. * @param array $attributes
  175. */
  176. public function addDateRangePicker($name, $label, $required = true, $attributes = array())
  177. {
  178. $this->addElement('date_range_picker', $name, $label, $attributes);
  179. $this->addElement('hidden', $name.'_start');
  180. $this->addElement('hidden', $name.'_end');
  181. if ($required) {
  182. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  183. }
  184. }
  185. /**
  186. * @param string $name
  187. * @param string $label
  188. * @param array $attributes
  189. *
  190. * @return mixed
  191. */
  192. public function addDatePicker($name, $label, $attributes = [])
  193. {
  194. return $this->addElement('DatePicker', $name, $label, $attributes);
  195. }
  196. /**
  197. * @param string $name
  198. * @param string $label
  199. * @param array $attributes
  200. *
  201. * @return mixed
  202. */
  203. public function addSelectLanguage($name, $label, $options = [], $attributes = [])
  204. {
  205. return $this->addElement('SelectLanguage', $name, $label, $options, $attributes);
  206. }
  207. /**
  208. * @param $name
  209. * @param $label
  210. * @param array $options
  211. * @param array $attributes
  212. * @throws
  213. */
  214. public function addSelectAjax($name, $label, $options = [], $attributes = [])
  215. {
  216. if (!isset($attributes['url'])) {
  217. throw new \Exception('select_ajax needs an URL');
  218. }
  219. $this->addElement(
  220. 'select_ajax',
  221. $name,
  222. $label,
  223. $options,
  224. $attributes
  225. );
  226. }
  227. /**
  228. * @param string $name
  229. * @param string $label
  230. * @param array $attributes
  231. *
  232. * @return mixed
  233. */
  234. public function addDateTimePicker($name, $label, $attributes = [])
  235. {
  236. return $this->addElement('DateTimePicker', $name, $label, $attributes);
  237. }
  238. /**
  239. * @param string $name
  240. * @param string $value
  241. */
  242. public function addHidden($name, $value)
  243. {
  244. $this->addElement('hidden', $name, $value);
  245. }
  246. /**
  247. * @param string $name
  248. * @param string $label
  249. * @param array $attributes
  250. *
  251. * @return HTML_QuickForm_textarea
  252. */
  253. public function addTextarea($name, $label, $attributes = array())
  254. {
  255. return $this->addElement('textarea', $name, $label, $attributes);
  256. }
  257. /**
  258. * @param string $name
  259. * @param string $label
  260. * @param string $icon font-awesome
  261. * @param string $style default|primary|success|info|warning|danger|link
  262. * @param string $size large|default|small|extra-small
  263. * @param string $class Example plus is transformed to icon fa fa-plus
  264. * @param array $attributes
  265. *
  266. * @return HTML_QuickForm_button
  267. */
  268. public function addButton(
  269. $name,
  270. $label,
  271. $icon = 'check',
  272. $style = 'default',
  273. $size = 'default',
  274. $class = null,
  275. $attributes = array(),
  276. $createElement = false
  277. ) {
  278. if ($createElement) {
  279. return $this->createElement(
  280. 'button',
  281. $name,
  282. $label,
  283. $icon,
  284. $style,
  285. $size,
  286. $class,
  287. $attributes
  288. );
  289. }
  290. return $this->addElement(
  291. 'button',
  292. $name,
  293. $label,
  294. $icon,
  295. $style,
  296. $size,
  297. $class,
  298. $attributes
  299. );
  300. }
  301. /**
  302. * Returns a button with the primary color and a check mark
  303. * @param string $label Text appearing on the button
  304. * @param string $name Element name (for form treatment purposes)
  305. * @param bool $createElement Whether to use the create or add method
  306. *
  307. * @return HTML_QuickForm_button
  308. */
  309. public function addButtonSave($label, $name = 'submit', $createElement = false)
  310. {
  311. return $this->addButton(
  312. $name,
  313. $label,
  314. 'check',
  315. 'primary',
  316. null,
  317. null,
  318. array(),
  319. $createElement
  320. );
  321. }
  322. /**
  323. * Returns a cancel button
  324. * @param string $label Text appearing on the button
  325. * @param string $name Element name (for form treatment purposes)
  326. * @param bool $createElement Whether to use the create or add method
  327. *
  328. * @return HTML_QuickForm_button
  329. */
  330. public function addButtonCancel($label, $name = 'submit', $createElement = false)
  331. {
  332. return $this->addButton(
  333. $name,
  334. $label,
  335. 'times',
  336. 'danger',
  337. null,
  338. null,
  339. array(),
  340. $createElement
  341. );
  342. }
  343. /**
  344. * Returns a button with the primary color and a "plus" icon
  345. * @param string $label Text appearing on the button
  346. * @param string $name Element name (for form treatment purposes)
  347. * @param bool $createElement Whether to use the create or add method
  348. * @param array $attributes Additional attributes
  349. *
  350. * @return HTML_QuickForm_button
  351. */
  352. public function addButtonCreate($label, $name = 'submit', $createElement = false, $attributes = array())
  353. {
  354. return $this->addButton(
  355. $name,
  356. $label,
  357. 'plus',
  358. 'primary',
  359. null,
  360. null,
  361. $attributes,
  362. $createElement
  363. );
  364. }
  365. /**
  366. * Returns a button with the primary color and a pencil icon
  367. * @param string $label Text appearing on the button
  368. * @param string $name Element name (for form treatment purposes)
  369. * @param bool $createElement Whether to use the create or add method
  370. * @return HTML_QuickForm_button
  371. */
  372. public function addButtonUpdate($label, $name = 'submit', $createElement = false)
  373. {
  374. return $this->addButton(
  375. $name,
  376. $label,
  377. 'pencil',
  378. 'primary',
  379. null,
  380. null,
  381. array(),
  382. $createElement
  383. );
  384. }
  385. /**
  386. * Returns a button with the danger color and a trash icon
  387. * @param string $label Text appearing on the button
  388. * @param string $name Element name (for form treatment purposes)
  389. * @param bool $createElement Whether to use the create or add method
  390. *
  391. * @return HTML_QuickForm_button
  392. */
  393. public function addButtonDelete($label, $name = 'submit', $createElement = false)
  394. {
  395. return $this->addButton(
  396. $name,
  397. $label,
  398. 'trash',
  399. 'danger',
  400. null,
  401. null,
  402. array(),
  403. $createElement
  404. );
  405. }
  406. /**
  407. * Returns a button with the primary color and a paper-plane icon
  408. * @param string $label Text appearing on the button
  409. * @param string $name Element name (for form treatment purposes)
  410. * @param bool $createElement Whether to use the create or add method
  411. *
  412. * @return HTML_QuickForm_button
  413. */
  414. public function addButtonSend($label, $name = 'submit', $createElement = false, $attributes = array())
  415. {
  416. return $this->addButton(
  417. $name,
  418. $label,
  419. 'paper-plane',
  420. 'primary',
  421. null,
  422. null,
  423. $attributes,
  424. $createElement
  425. );
  426. }
  427. /**
  428. * Returns a button with the default (grey?) color and a magnifier icon
  429. * @param string $label Text appearing on the button
  430. * @param string $name Element name (for form treatment purposes)
  431. *
  432. * @return HTML_QuickForm_button
  433. */
  434. public function addButtonSearch($label = null, $name = 'submit')
  435. {
  436. if (empty($label)) {
  437. $label = get_lang('Search');
  438. }
  439. return $this->addButton($name, $label, 'search', 'default');
  440. }
  441. /**
  442. * Returns a button with the primary color and a right-pointing arrow icon
  443. * @param string $label Text appearing on the button
  444. * @param string $name Element name (for form treatment purposes)
  445. * @param array $attributes Additional attributes
  446. * @return HTML_QuickForm_button
  447. */
  448. public function addButtonNext($label, $name = 'submit', $attributes = array())
  449. {
  450. return $this->addButton($name, $label, 'arrow-right', 'primary', null, null, $attributes);
  451. }
  452. /**
  453. * Returns a button with the primary color and a check mark icon
  454. * @param string $label Text appearing on the button
  455. * @param string $name Element name (for form treatment purposes)
  456. * @param bool $createElement Whether to use the create or add method
  457. * @return HTML_QuickForm_button
  458. */
  459. public function addButtonImport($label, $name = 'submit', $createElement = false)
  460. {
  461. return $this->addButton(
  462. $name,
  463. $label,
  464. 'check',
  465. 'primary',
  466. null,
  467. null,
  468. array(),
  469. $createElement
  470. );
  471. }
  472. /**
  473. * Returns a button with the primary color and a check-mark icon
  474. * @param string $label Text appearing on the button
  475. * @param string $name Element name (for form treatment purposes)
  476. * @param bool $createElement Whether to use the create or add method
  477. * @return HTML_QuickForm_button
  478. */
  479. public function addButtonExport($label, $name = 'submit', $createElement = false)
  480. {
  481. return $this->addButton(
  482. $name,
  483. $label,
  484. 'check',
  485. 'primary',
  486. null,
  487. null,
  488. array(),
  489. $createElement
  490. );
  491. }
  492. /**
  493. * Shortcut to filter button
  494. * @param string $label Text appearing on the button
  495. * @param string $name Element name (for form treatment purposes)
  496. * @param bool $createElement Whether to use the create or add method
  497. * @return HTML_QuickForm_button
  498. */
  499. public function addButtonFilter($label, $name = 'submit', $createElement = false)
  500. {
  501. return $this->addButton(
  502. $name,
  503. $label,
  504. 'filter',
  505. 'primary',
  506. null,
  507. null,
  508. array(),
  509. $createElement
  510. );
  511. }
  512. /**
  513. * Shortcut to reset button
  514. * @param string $label Text appearing on the button
  515. * @param string $name Element name (for form treatment purposes)
  516. * @param bool $createElement Whether to use the create or add method
  517. * @return HTML_QuickForm_button
  518. */
  519. public function addButtonReset($label, $name = 'reset', $createElement = false)
  520. {
  521. $icon = 'eraser';
  522. $style = 'default';
  523. $size = 'default';
  524. $class = null;
  525. $attributes = array();
  526. if ($createElement) {
  527. return $this->createElement(
  528. 'reset',
  529. $name,
  530. $label,
  531. $icon,
  532. $style,
  533. $size,
  534. $class,
  535. $attributes
  536. );
  537. }
  538. return $this->addElement(
  539. 'reset',
  540. $name,
  541. $label,
  542. $icon,
  543. $style,
  544. $size,
  545. $class,
  546. $attributes
  547. );
  548. }
  549. /**
  550. * Returns a button with the primary color and an upload icon
  551. * @param string $label Text appearing on the button
  552. * @param string $name Element name (for form treatment purposes)
  553. * @param bool $createElement Whether to use the create or add method
  554. *
  555. * @return HTML_QuickForm_button
  556. */
  557. public function addButtonUpload($label, $name = 'submit', $createElement = false)
  558. {
  559. return $this->addButton(
  560. $name,
  561. $label,
  562. 'upload',
  563. 'primary',
  564. null,
  565. null,
  566. array(),
  567. $createElement
  568. );
  569. }
  570. /**
  571. * Returns a button with the primary color and a download icon
  572. * @param string $label Text appearing on the button
  573. * @param string $name Element name (for form treatment purposes)
  574. * @param bool $createElement Whether to use the create or add method
  575. *
  576. * @return HTML_QuickForm_button
  577. */
  578. public function addButtonDownload($label, $name = 'submit', $createElement = false)
  579. {
  580. return $this->addButton(
  581. $name,
  582. $label,
  583. 'download',
  584. 'primary',
  585. null,
  586. null,
  587. array(),
  588. $createElement
  589. );
  590. }
  591. /**
  592. * Returns a button with the primary color and a magnifier icon
  593. * @param string $label Text appearing on the button
  594. * @param string $name Element name (for form treatment purposes)
  595. * @param bool $createElement Whether to use the create or add method
  596. *
  597. * @return HTML_QuickForm_button
  598. */
  599. public function addButtonPreview($label, $name = 'submit', $createElement = false)
  600. {
  601. return $this->addButton(
  602. $name,
  603. $label,
  604. 'search',
  605. 'primary',
  606. null,
  607. null,
  608. array(),
  609. $createElement
  610. );
  611. }
  612. /**
  613. * Returns a button with the primary color and a copy (double sheet) icon
  614. * @param string $label Text appearing on the button
  615. * @param string $name Element name (for form treatment purposes)
  616. * @param bool $createElement Whether to use the create or add method
  617. *
  618. * @return HTML_QuickForm_button
  619. */
  620. public function addButtonCopy($label, $name = 'submit', $createElement = false)
  621. {
  622. return $this->addButton(
  623. $name,
  624. $label,
  625. 'copy',
  626. 'primary',
  627. null,
  628. null,
  629. array(),
  630. $createElement
  631. );
  632. }
  633. /**
  634. * @param string $name
  635. * @param string $label
  636. * @param string $text
  637. * @param array $attributes
  638. *
  639. * @return HTML_QuickForm_checkbox
  640. */
  641. public function addCheckBox($name, $label, $text = '', $attributes = array())
  642. {
  643. return $this->addElement('checkbox', $name, $label, $text, $attributes);
  644. }
  645. /**
  646. * @param string $name
  647. * @param string $label
  648. * @param array $options
  649. * @param array $attributes
  650. *
  651. * @return HTML_QuickForm_group
  652. */
  653. public function addCheckBoxGroup($name, $label, $options = array(), $attributes = array())
  654. {
  655. $group = array();
  656. foreach ($options as $value => $text) {
  657. $attributes['value'] = $value;
  658. $group[] = $this->createElement('checkbox', $value, null, $text, $attributes);
  659. }
  660. return $this->addGroup($group, $name, $label);
  661. }
  662. /**
  663. * @param string $name
  664. * @param string $label
  665. * @param array $options
  666. * @param array $attributes
  667. *
  668. * @return HTML_QuickForm_radio
  669. */
  670. public function addRadio($name, $label, $options = array(), $attributes = array())
  671. {
  672. $group = array();
  673. foreach ($options as $key => $value) {
  674. $group[] = $this->createElement('radio', null, null, $value, $key, $attributes);
  675. }
  676. return $this->addGroup($group, $name, $label);
  677. }
  678. /**
  679. * @param string $name
  680. * @param string $label
  681. * @param array $options
  682. * @param array $attributes
  683. *
  684. * @return HTML_QuickForm_select
  685. */
  686. public function addSelect($name, $label, $options = array(), $attributes = array())
  687. {
  688. return $this->addElement('select', $name, $label, $options, $attributes);
  689. }
  690. /**
  691. * @param $name
  692. * @param $label
  693. * @param $collection
  694. * @param array $attributes
  695. * @param bool $addNoneOption
  696. * @param string $textCallable set a function getStringValue() by default __toString()
  697. *
  698. * @return HTML_QuickForm_element
  699. */
  700. public function addSelectFromCollection(
  701. $name,
  702. $label,
  703. $collection,
  704. $attributes = array(),
  705. $addNoneOption = false,
  706. $textCallable = ''
  707. ) {
  708. $options = [];
  709. if ($addNoneOption) {
  710. $options[0] = get_lang('None');
  711. }
  712. if (!empty($collection)) {
  713. foreach ($collection as $item) {
  714. $text = $item;
  715. if (!empty($textCallable)) {
  716. $text = $item->$textCallable();
  717. }
  718. $options[$item->getId()] = $text;
  719. }
  720. }
  721. return $this->addElement('select', $name, $label, $options, $attributes);
  722. }
  723. /**
  724. * @param string $label
  725. * @param string $text
  726. *
  727. * @return HTML_QuickForm_label
  728. */
  729. public function addLabel($label, $text)
  730. {
  731. return $this->addElement('label', $label, $text);
  732. }
  733. /**
  734. * @param string $text
  735. */
  736. public function addHeader($text)
  737. {
  738. $this->addElement('header', $text);
  739. }
  740. /**
  741. * @param string $name
  742. * @param string $label
  743. * @param array $attributes
  744. * @throws Exception if the file doesn't have an id
  745. */
  746. public function addFile($name, $label, $attributes = array())
  747. {
  748. $element = $this->addElement('file', $name, $label, $attributes);
  749. if (isset($attributes['crop_image'])) {
  750. $id = $element->getAttribute('id');
  751. if (empty($id)) {
  752. throw new Exception('If you use the crop functionality the element must have an id');
  753. }
  754. $this->addHtml('
  755. <div class="form-group">
  756. <label for="cropImage" id="'.$id.'_label_crop_image" class="col-sm-2 control-label"></label>
  757. <div class="col-sm-8">
  758. <div id="'.$id.'_crop_image" class="cropCanvas">
  759. <img id="'.$id.'_preview_image">
  760. </div>
  761. <div>
  762. <button class="btn btn-primary hidden" name="cropButton" id="'.$id.'_crop_button" >
  763. <em class="fa fa-crop"></em> '.
  764. get_lang('CropYourPicture').'
  765. </button>
  766. </div>
  767. </div>
  768. </div>'
  769. );
  770. $this->addHidden($id.'_crop_result', '');
  771. $this->addHidden($id.'_crop_image_base_64', '');
  772. }
  773. }
  774. /**
  775. * @param string $snippet
  776. */
  777. public function addHtml($snippet)
  778. {
  779. $this->addElement('html', $snippet);
  780. }
  781. /**
  782. * Adds a HTML-editor to the form
  783. * @param string $name
  784. * @param string $label The label for the form-element
  785. * @param bool $required (optional) Is the form-element required (default=true)
  786. * @param bool $fullPage (optional) When it is true, the editor loads completed html code for a full page.
  787. * @param array $config (optional) Configuration settings for the online editor.
  788. * @param bool $style
  789. */
  790. public function addHtmlEditor($name, $label, $required = true, $fullPage = false, $config = array(), $style = false)
  791. {
  792. $config['rows'] = isset($config['rows']) ? $config['rows'] : 15;
  793. $config['cols'] = isset($config['cols']) ? $config['cols'] : 80;
  794. $this->addElement('html_editor', $name, $label, $config, $style);
  795. $this->applyFilter($name, 'trim');
  796. if ($required) {
  797. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  798. }
  799. /** @var HtmlEditor $element */
  800. $element = $this->getElement($name);
  801. if ($style) {
  802. $config['style'] = true;
  803. }
  804. if ($fullPage) {
  805. $config['fullPage'] = true;
  806. }
  807. if ($element->editor) {
  808. $element->editor->processConfig($config);
  809. }
  810. }
  811. /**
  812. * @param string $name
  813. * @param string $label
  814. *
  815. * @return mixed
  816. */
  817. public function addButtonAdvancedSettings($name, $label = '')
  818. {
  819. $label = !empty($label) ? $label : get_lang('AdvancedParameters');
  820. return $this->addElement('advanced_settings', $name, $label);
  821. }
  822. /**
  823. * Adds a progress loading image to the form.
  824. *
  825. */
  826. public function addProgress($delay = 2, $label = '')
  827. {
  828. if (empty($label)) {
  829. $label = get_lang('PleaseStandBy');
  830. }
  831. $this->with_progress_bar = true;
  832. $id = $this->getAttribute('id');
  833. $this->updateAttributes("onsubmit=\"javascript: addProgress('" . $id . "')\"");
  834. $this->addHtml('<script language="javascript" src="' . api_get_path(WEB_LIBRARY_PATH) . 'javascript/upload.js" type="text/javascript"></script>');
  835. }
  836. /**
  837. * This function has been created for avoiding changes directly within QuickForm class.
  838. * When we use it, the element is threated as 'required' to be dealt during validation.
  839. * @param array $element The array of elements
  840. * @param string $message The message displayed
  841. */
  842. public function add_multiple_required_rule($elements, $message)
  843. {
  844. $this->_required[] = $elements[0];
  845. $this->addRule($elements, $message, 'multiple_required');
  846. }
  847. /**
  848. * Displays the form.
  849. * If an element in the form didn't validate, an error message is showed
  850. * asking the user to complete the form.
  851. */
  852. public function display()
  853. {
  854. echo $this->returnForm();
  855. }
  856. /**
  857. * Returns the HTML code of the form.
  858. * @return string $return_value HTML code of the form
  859. */
  860. public function returnForm()
  861. {
  862. $returnValue = '';
  863. /** @var HTML_QuickForm_element $element */
  864. foreach ($this->_elements as $element) {
  865. $elementError = parent::getElementError($element->getName());
  866. if (!is_null($elementError)) {
  867. $returnValue .= Display::return_message($elementError, 'warning').'<br />';
  868. break;
  869. }
  870. }
  871. $returnValue .= parent::toHtml();
  872. // Add div-element which is to hold the progress bar
  873. $id = $this->getAttribute('id');
  874. if (isset($this->with_progress_bar) && $this->with_progress_bar) {
  875. $icon = Display::return_icon('progress_bar.gif');
  876. // @todo improve UI
  877. $returnValue .= '<br />
  878. <div id="loading_div_'.$id.'" class="loading_div" style="display:none;margin-left:40%; margin-top:10px; height:50px;">
  879. '.$icon.'
  880. </div>
  881. ';
  882. }
  883. return $returnValue;
  884. }
  885. /**
  886. * Returns the HTML code of the form.
  887. * If an element in the form didn't validate, an error message is showed
  888. * asking the user to complete the form.
  889. *
  890. * @return string $return_value HTML code of the form
  891. *
  892. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, august 2006
  893. * @author Julio Montoya
  894. * @deprecated use returnForm()
  895. */
  896. public function return_form()
  897. {
  898. return $this->returnForm();
  899. }
  900. /**
  901. * Create a form validator based on an array of form data:
  902. *
  903. * array(
  904. * 'name' => 'zombie_report_parameters', //optional
  905. * 'method' => 'GET', //optional
  906. * 'items' => array(
  907. * array(
  908. * 'name' => 'ceiling',
  909. * 'label' => 'Ceiling', //optional
  910. * 'type' => 'date',
  911. * 'default' => date() //optional
  912. * ),
  913. * array(
  914. * 'name' => 'active_only',
  915. * 'label' => 'ActiveOnly',
  916. * 'type' => 'checkbox',
  917. * 'default' => true
  918. * ),
  919. * array(
  920. * 'name' => 'submit_button',
  921. * 'type' => 'style_submit_button',
  922. * 'value' => get_lang('Search'),
  923. * 'attributes' => array('class' => 'search')
  924. * )
  925. * )
  926. * );
  927. *
  928. * @param array $form_data
  929. * @deprecated use normal FormValidator construct
  930. *
  931. * @return FormValidator
  932. */
  933. public static function create($form_data)
  934. {
  935. if (empty($form_data)) {
  936. return null;
  937. }
  938. $form_name = isset($form_data['name']) ? $form_data['name'] : 'form';
  939. $form_method = isset($form_data['method']) ? $form_data['method'] : 'POST';
  940. $form_action = isset($form_data['action']) ? $form_data['action'] : '';
  941. $form_target = isset($form_data['target']) ? $form_data['target'] : '';
  942. $form_attributes = isset($form_data['attributes']) ? $form_data['attributes'] : null;
  943. $form_track_submit = isset($form_data['track_submit']) ? $form_data['track_submit'] : true;
  944. $reset = null;
  945. $result = new FormValidator($form_name, $form_method, $form_action, $form_target, $form_attributes, $form_track_submit);
  946. $defaults = array();
  947. foreach ($form_data['items'] as $item) {
  948. $name = $item['name'];
  949. $type = isset($item['type']) ? $item['type'] : 'text';
  950. $label = isset($item['label']) ? $item['label'] : '';
  951. if ($type == 'wysiwyg') {
  952. $element = $result->addHtmlEditor($name, $label);
  953. } else {
  954. $element = $result->addElement($type, $name, $label);
  955. }
  956. if (isset($item['attributes'])) {
  957. $attributes = $item['attributes'];
  958. $element->setAttributes($attributes);
  959. }
  960. if (isset($item['value'])) {
  961. $value = $item['value'];
  962. $element->setValue($value);
  963. }
  964. if (isset($item['default'])) {
  965. $defaults[$name] = $item['default'];
  966. }
  967. if (isset($item['rules'])) {
  968. $rules = $item['rules'];
  969. foreach ($rules as $rule) {
  970. $message = $rule['message'];
  971. $type = $rule['type'];
  972. $format = isset($rule['format']) ? $rule['format'] : null;
  973. $validation = isset($rule['validation']) ? $rule['validation'] : 'server';
  974. $force = isset($rule['force']) ? $rule['force'] : false;
  975. $result->addRule($name, $message, $type, $format, $validation, $reset, $force);
  976. }
  977. }
  978. }
  979. $result->setDefaults($defaults);
  980. return $result;
  981. }
  982. /**
  983. * @return HTML_QuickForm_Renderer_Default
  984. */
  985. public static function getDefaultRenderer()
  986. {
  987. return
  988. isset($GLOBALS['_HTML_QuickForm_default_renderer']) ?
  989. $GLOBALS['_HTML_QuickForm_default_renderer'] : null;
  990. }
  991. /**
  992. * Adds a input of type url to the form.
  993. * @param type $name The label for the form-element
  994. * @param type $label The element name
  995. * @param type $required Optional. Is the form-element required (default=true)
  996. * @param type $attributes Optional. List of attributes for the form-element
  997. */
  998. public function addUrl($name, $label, $required = true, $attributes = array())
  999. {
  1000. $this->addElement('url', $name, $label, $attributes);
  1001. $this->applyFilter($name, 'trim');
  1002. $this->addRule($name, get_lang('InsertAValidUrl'), 'url');
  1003. if ($required) {
  1004. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1005. }
  1006. }
  1007. /**
  1008. * Adds a text field for letters to the form.
  1009. * A trim-filter is attached to the field.
  1010. * @param string $name The element name
  1011. * @param string $label The label for the form-element
  1012. * @param bool $required Optional. Is the form-element required (default=true)
  1013. * @param array $attributes Optional. List of attributes for the form-element
  1014. */
  1015. public function addTextLettersOnly(
  1016. $name,
  1017. $label,
  1018. $required = false,
  1019. $attributes = []
  1020. ) {
  1021. $attributes = array_merge(
  1022. $attributes,
  1023. [
  1024. 'pattern' => '[a-zA-ZñÑ]+',
  1025. 'title' => get_lang('OnlyLetters')
  1026. ]
  1027. );
  1028. $this->addElement(
  1029. 'text',
  1030. $name,
  1031. [
  1032. $label,
  1033. get_lang('OnlyLetters')
  1034. ],
  1035. $attributes
  1036. );
  1037. $this->applyFilter($name, 'trim');
  1038. if ($required) {
  1039. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1040. }
  1041. $this->addRule(
  1042. $name,
  1043. get_lang('OnlyLetters'),
  1044. 'regex',
  1045. '/^[a-zA-ZñÑ]+$/'
  1046. );
  1047. }
  1048. /**
  1049. * Adds a text field for alphanumeric characters to the form.
  1050. * A trim-filter is attached to the field.
  1051. * @param string $name The element name
  1052. * @param string $label The label for the form-element
  1053. * @param bool $required Optional. Is the form-element required (default=true)
  1054. * @param array $attributes Optional. List of attributes for the form-element
  1055. */
  1056. public function addTextAlphanumeric(
  1057. $name,
  1058. $label,
  1059. $required = false,
  1060. $attributes = []
  1061. ) {
  1062. $attributes = array_merge(
  1063. $attributes,
  1064. [
  1065. 'pattern' => '[a-zA-Z0-9ñÑ]+',
  1066. 'title' => get_lang('OnlyLettersAndNumbers')
  1067. ]
  1068. );
  1069. $this->addElement(
  1070. 'text',
  1071. $name,
  1072. [
  1073. $label,
  1074. get_lang('OnlyLettersAndNumbers')
  1075. ],
  1076. $attributes
  1077. );
  1078. $this->applyFilter($name, 'trim');
  1079. if ($required) {
  1080. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1081. }
  1082. $this->addRule(
  1083. $name,
  1084. get_lang('OnlyLettersAndNumbers'),
  1085. 'regex',
  1086. '/^[a-zA-Z0-9ÑÑ]+$/'
  1087. );
  1088. }
  1089. /**
  1090. * Adds a text field for letters and spaces to the form.
  1091. * A trim-filter is attached to the field.
  1092. * @param string $name The element name
  1093. * @param string $label The label for the form-element
  1094. * @param bool $required Optional. Is the form-element required (default=true)
  1095. * @param array $attributes Optional. List of attributes for the form-element
  1096. */
  1097. public function addTextLettersAndSpaces(
  1098. $name,
  1099. $label,
  1100. $required = false,
  1101. $attributes = []
  1102. ) {
  1103. $attributes = array_merge(
  1104. $attributes,
  1105. [
  1106. 'pattern' => '[a-zA-ZñÑ\s]+',
  1107. 'title' => get_lang('OnlyLettersAndSpaces')
  1108. ]
  1109. );
  1110. $this->addElement(
  1111. 'text',
  1112. $name,
  1113. [
  1114. $label,
  1115. get_lang('OnlyLettersAndSpaces')
  1116. ],
  1117. $attributes
  1118. );
  1119. $this->applyFilter($name, 'trim');
  1120. if ($required) {
  1121. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1122. }
  1123. $this->addRule(
  1124. $name,
  1125. get_lang('OnlyLettersAndSpaces'),
  1126. 'regex',
  1127. '/^[a-zA-ZñÑ\s]+$/'
  1128. );
  1129. }
  1130. /**
  1131. * Adds a text field for alphanumeric and spaces characters to the form.
  1132. * A trim-filter is attached to the field.
  1133. * @param string $name The element name
  1134. * @param string $label The label for the form-element
  1135. * @param bool $required Optional. Is the form-element required (default=true)
  1136. * @param array $attributes Optional. List of attributes for the form-element
  1137. */
  1138. public function addTextAlphanumericAndSpaces(
  1139. $name,
  1140. $label,
  1141. $required = false,
  1142. $attributes = []
  1143. ) {
  1144. $attributes = array_merge(
  1145. $attributes,
  1146. [
  1147. 'pattern' => '[a-zA-Z0-9ñÑ\s]+',
  1148. 'title' => get_lang('OnlyLettersAndNumbersAndSpaces')
  1149. ]
  1150. );
  1151. $this->addElement(
  1152. 'text',
  1153. $name,
  1154. [
  1155. $label,
  1156. get_lang('OnlyLettersAndNumbersAndSpaces')
  1157. ],
  1158. $attributes
  1159. );
  1160. $this->applyFilter($name, 'trim');
  1161. if ($required) {
  1162. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1163. }
  1164. $this->addRule(
  1165. $name,
  1166. get_lang('OnlyLettersAndNumbersAndSpaces'),
  1167. 'regex',
  1168. '/^[a-zA-Z0-9ñÑ\s]+$/'
  1169. );
  1170. }
  1171. /**
  1172. * @param string $url
  1173. */
  1174. public function addMultipleUpload($url)
  1175. {
  1176. $inputName = 'input_file_upload';
  1177. $this->addMultipleUploadJavascript($url, $inputName);
  1178. $this->addHtml('
  1179. <div class="description-upload">'.get_lang('ClickToSelectOrDragAndDropMultipleFilesOnTheUploadField').'</div>
  1180. <span class="btn btn-success fileinput-button">
  1181. <i class="glyphicon glyphicon-plus"></i>
  1182. <span>'.get_lang('AddFiles').'</span>
  1183. <!-- The file input field used as target for the file upload widget -->
  1184. <input id="'.$inputName.'" type="file" name="files[]" multiple>
  1185. </span>
  1186. <br />
  1187. <br />
  1188. <div id="dropzone">
  1189. <div class="button-load">
  1190. '.get_lang('UploadFiles').'
  1191. </div>
  1192. </div>
  1193. <br />
  1194. <!-- The global progress bar -->
  1195. <div id="progress" class="progress">
  1196. <div class="progress-bar progress-bar-success"></div>
  1197. </div>
  1198. <div id="files" class="files"></div>
  1199. ');
  1200. }
  1201. /**
  1202. *
  1203. * @param string $url page that will handle the upload
  1204. * @param string $inputName
  1205. */
  1206. private function addMultipleUploadJavascript($url, $inputName)
  1207. {
  1208. $icon = Display::return_icon('file_txt.gif');
  1209. $this->addHtml("
  1210. <script>
  1211. $(function () {
  1212. 'use strict';
  1213. $('#".$this->getAttribute('id')."').submit(function() {
  1214. return false;
  1215. });
  1216. $('#dropzone').on('click', function() {
  1217. $('#".$inputName."').click();
  1218. });
  1219. var url = '".$url."';
  1220. var uploadButton = $('<button/>')
  1221. .addClass('btn btn-primary')
  1222. .prop('disabled', true)
  1223. .text('".addslashes(get_lang('Loading'))."')
  1224. .on('click', function () {
  1225. var \$this = $(this),
  1226. data = \$this.data();
  1227. \$this
  1228. .off('click')
  1229. .text('".addslashes(get_lang('Cancel'))."')
  1230. .on('click', function () {
  1231. \$this.remove();
  1232. data.abort();
  1233. });
  1234. data.submit().always(function () {
  1235. \$this.remove();
  1236. });
  1237. });
  1238. $('#".$inputName."').fileupload({
  1239. url: url,
  1240. dataType: 'json',
  1241. autoUpload: true,
  1242. // Enable image resizing, except for Android and Opera,
  1243. // which actually support image resizing, but fail to
  1244. // send Blob objects via XHR requests:
  1245. disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),
  1246. previewMaxWidth: 100,
  1247. previewMaxHeight: 100,
  1248. previewCrop: true,
  1249. dropzone: $('#dropzone')
  1250. }).on('fileuploadadd', function (e, data) {
  1251. data.context = $('<div class=\"row\" style=\"margin-bottom:35px\" />').appendTo('#files');
  1252. $.each(data.files, function (index, file) {
  1253. var node = $('<div class=\"col-sm-5\">').text(file.name);
  1254. node.appendTo(data.context);
  1255. }
  1256. );
  1257. }).on('fileuploadprocessalways', function (e, data) {
  1258. var index = data.index,
  1259. file = data.files[index],
  1260. node = $(data.context.children()[index]);
  1261. if (file.preview) {
  1262. data.context
  1263. .prepend($('<div class=\"col-sm-2\">').html(file.preview))
  1264. ;
  1265. } else {
  1266. data.context
  1267. .prepend($('<div class=\"col-sm-2\">').html('".$icon."'))
  1268. ;
  1269. }
  1270. if (index + 1 === data.files.length) {
  1271. data.context.find('button')
  1272. .text('Upload')
  1273. .prop('disabled', !!data.files.error);
  1274. }
  1275. }).on('fileuploadprogressall', function (e, data) {
  1276. var progress = parseInt(data.loaded / data.total * 100, 10);
  1277. $('#progress .progress-bar').css(
  1278. 'width',
  1279. progress + '%'
  1280. );
  1281. }).on('fileuploaddone', function (e, data) {
  1282. $.each(data.result.files, function (index, file) {
  1283. if (file.url) {
  1284. var link = $('<a>')
  1285. .attr('target', '_blank')
  1286. .prop('href', file.url);
  1287. $(data.context.children()[index]).parent().wrap(link);
  1288. var successMessage = $('<div class=\"col-sm-3\">').html($('<span class=\"alert alert-success\"/>').text('" . addslashes(get_lang('UplUploadSucceeded')) . "'));
  1289. $(data.context.children()[index]).parent().append(successMessage);
  1290. } else if (file.error) {
  1291. var error = $('<div class=\"col-sm-3\">').html($('<span class=\"alert alert-danger\"/>').text(file.error));
  1292. $(data.context.children()[index]).parent().append(error);
  1293. }
  1294. });
  1295. }).on('fileuploadfail', function (e, data) {
  1296. $.each(data.files, function (index) {
  1297. var failedMessage = '" . addslashes(get_lang('UplUploadFailed')) . "';
  1298. var error = $('<div class=\"col-sm-3\">').html($('<span class=\"alert alert-danger\"/>').text(failedMessage));
  1299. $(data.context.children()[index]).parent().append(error);
  1300. });
  1301. }).prop('disabled', !$.support.fileInput)
  1302. .parent().addClass($.support.fileInput ? undefined : 'disabled');
  1303. $('.fileinput-button').hide();
  1304. });
  1305. </script>");
  1306. }
  1307. }
  1308. /**
  1309. * Cleans HTML text filter
  1310. * @param string $html HTML to clean
  1311. * @param int $mode (optional)
  1312. * @return string The cleaned HTML
  1313. */
  1314. function html_filter($html, $mode = NO_HTML)
  1315. {
  1316. $allowed_tags = HTML_QuickForm_Rule_HTML::get_allowed_tags($mode);
  1317. $cleaned_html = kses($html, $allowed_tags);
  1318. return $cleaned_html;
  1319. }
  1320. function html_filter_teacher($html)
  1321. {
  1322. return html_filter($html, TEACHER_HTML);
  1323. }
  1324. function html_filter_student($html)
  1325. {
  1326. return html_filter($html, STUDENT_HTML);
  1327. }
  1328. function html_filter_teacher_fullpage($html)
  1329. {
  1330. return html_filter($html, TEACHER_HTML_FULLPAGE);
  1331. }
  1332. function html_filter_student_fullpage($html)
  1333. {
  1334. return html_filter($html, STUDENT_HTML_FULLPAGE);
  1335. }
  1336. /**
  1337. * Cleans mobile phone number text
  1338. * @param string $mobilePhoneNumber Mobile phone number to clean
  1339. * @return string The cleaned mobile phone number
  1340. */
  1341. function mobile_phone_number_filter($mobilePhoneNumber)
  1342. {
  1343. $mobilePhoneNumber = str_replace(array('+', '(', ')'), '', $mobilePhoneNumber);
  1344. return ltrim($mobilePhoneNumber, '0');
  1345. }