FormValidator.class.php 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800
  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. * @todo this function should be added in the element class
  108. * @return string
  109. */
  110. public function getDefaultElementTemplate()
  111. {
  112. return '
  113. <div class="form-group {error_class}">
  114. <label {label-for} class="col-sm-2 control-label {extra_label_class}" >
  115. <!-- BEGIN required --><span class="form_required">*</span><!-- END required -->
  116. {label}
  117. </label>
  118. <div class="col-sm-8">
  119. {icon}
  120. {element}
  121. <!-- BEGIN label_2 -->
  122. <p class="help-block">{label_2}</p>
  123. <!-- END label_2 -->
  124. <!-- BEGIN error -->
  125. <span class="help-inline">{error}</span>
  126. <!-- END error -->
  127. </div>
  128. <div class="col-sm-2">
  129. <!-- BEGIN label_3 -->
  130. {label_3}
  131. <!-- END label_3 -->
  132. </div>
  133. </div>';
  134. }
  135. /**
  136. * @return string
  137. */
  138. public function getLayout()
  139. {
  140. return $this->layout;
  141. }
  142. /**
  143. * @param string $layout
  144. */
  145. public function setLayout($layout)
  146. {
  147. $this->layout = $layout;
  148. }
  149. /**
  150. * Adds a text field to the form.
  151. * A trim-filter is attached to the field.
  152. * @param string $label The label for the form-element
  153. * @param string $name The element name
  154. * @param bool $required (optional) Is the form-element required (default=true)
  155. * @param array $attributes (optional) List of attributes for the form-element
  156. * @return HTML_QuickForm_text
  157. */
  158. public function addText($name, $label, $required = true, $attributes = array())
  159. {
  160. $element = $this->addElement('text', $name, $label, $attributes);
  161. $this->applyFilter($name, 'trim');
  162. if ($required) {
  163. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  164. }
  165. return $element;
  166. }
  167. /**
  168. * The "date_range_picker" element creates 2 hidden fields
  169. * "elementName" + "_start" and "elementName" + "_end"
  170. * For example if the name is "range", you will have 2 new fields
  171. * when executing $form->getSubmitValues()
  172. * "range_start" and "range_end"
  173. *
  174. * @param string $name
  175. * @param string $label
  176. * @param bool $required
  177. * @param array $attributes
  178. */
  179. public function addDateRangePicker($name, $label, $required = true, $attributes = array())
  180. {
  181. $this->addElement('date_range_picker', $name, $label, $attributes);
  182. $this->addElement('hidden', $name.'_start');
  183. $this->addElement('hidden', $name.'_end');
  184. if ($required) {
  185. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  186. }
  187. }
  188. /**
  189. * @param string $name
  190. * @param string $label
  191. * @param array $attributes
  192. *
  193. * @return mixed
  194. */
  195. public function addDatePicker($name, $label, $attributes = [])
  196. {
  197. return $this->addElement('DatePicker', $name, $label, $attributes);
  198. }
  199. /**
  200. * @param string $name
  201. * @param string $label
  202. * @param array $attributes
  203. *
  204. * @return mixed
  205. */
  206. public function addSelectLanguage($name, $label, $options = [], $attributes = [])
  207. {
  208. return $this->addElement('SelectLanguage', $name, $label, $options, $attributes);
  209. }
  210. /**
  211. * @param string $name
  212. * @param string $label
  213. * @param array $options
  214. * @param array $attributes
  215. * @throws
  216. */
  217. public function addSelectAjax($name, $label, $options = [], $attributes = [])
  218. {
  219. if (!isset($attributes['url'])) {
  220. throw new \Exception('select_ajax needs an URL');
  221. }
  222. $this->addElement(
  223. 'select_ajax',
  224. $name,
  225. $label,
  226. $options,
  227. $attributes
  228. );
  229. }
  230. /**
  231. * @param string $name
  232. * @param string $label
  233. * @param array $attributes
  234. *
  235. * @return mixed
  236. */
  237. public function addDateTimePicker($name, $label, $attributes = [])
  238. {
  239. return $this->addElement('DateTimePicker', $name, $label, $attributes);
  240. }
  241. /**
  242. * @param string $name
  243. * @param string $value
  244. */
  245. public function addHidden($name, $value)
  246. {
  247. $this->addElement('hidden', $name, $value);
  248. }
  249. /**
  250. * @param string $name
  251. * @param string $label
  252. * @param array $attributes
  253. *
  254. * @return HTML_QuickForm_textarea
  255. */
  256. public function addTextarea($name, $label, $attributes = array())
  257. {
  258. return $this->addElement('textarea', $name, $label, $attributes);
  259. }
  260. /**
  261. * @param string $name
  262. * @param string $label
  263. * @param string $icon font-awesome
  264. * @param string $style default|primary|success|info|warning|danger|link
  265. * @param string $size large|default|small|extra-small
  266. * @param string $class Example plus is transformed to icon fa fa-plus
  267. * @param array $attributes
  268. *
  269. * @return HTML_QuickForm_button
  270. */
  271. public function addButton(
  272. $name,
  273. $label,
  274. $icon = 'check',
  275. $style = 'default',
  276. $size = 'default',
  277. $class = null,
  278. $attributes = array(),
  279. $createElement = false
  280. ) {
  281. if ($createElement) {
  282. return $this->createElement(
  283. 'button',
  284. $name,
  285. $label,
  286. $icon,
  287. $style,
  288. $size,
  289. $class,
  290. $attributes
  291. );
  292. }
  293. return $this->addElement(
  294. 'button',
  295. $name,
  296. $label,
  297. $icon,
  298. $style,
  299. $size,
  300. $class,
  301. $attributes
  302. );
  303. }
  304. /**
  305. * Returns a button with the primary color and a check mark
  306. * @param string $label Text appearing on the button
  307. * @param string $name Element name (for form treatment purposes)
  308. * @param bool $createElement Whether to use the create or add method
  309. *
  310. * @return HTML_QuickForm_button
  311. */
  312. public function addButtonSave($label, $name = 'submit', $createElement = false)
  313. {
  314. return $this->addButton(
  315. $name,
  316. $label,
  317. 'check',
  318. 'primary',
  319. null,
  320. null,
  321. array(),
  322. $createElement
  323. );
  324. }
  325. /**
  326. * Returns a cancel button
  327. * @param string $label Text appearing on the button
  328. * @param string $name Element name (for form treatment purposes)
  329. * @param bool $createElement Whether to use the create or add method
  330. *
  331. * @return HTML_QuickForm_button
  332. */
  333. public function addButtonCancel($label, $name = 'submit', $createElement = false)
  334. {
  335. return $this->addButton(
  336. $name,
  337. $label,
  338. 'times',
  339. 'danger',
  340. null,
  341. null,
  342. array(),
  343. $createElement
  344. );
  345. }
  346. /**
  347. * Returns a button with the primary color and a "plus" icon
  348. * @param string $label Text appearing on the button
  349. * @param string $name Element name (for form treatment purposes)
  350. * @param bool $createElement Whether to use the create or add method
  351. * @param array $attributes Additional attributes
  352. *
  353. * @return HTML_QuickForm_button
  354. */
  355. public function addButtonCreate($label, $name = 'submit', $createElement = false, $attributes = array())
  356. {
  357. return $this->addButton(
  358. $name,
  359. $label,
  360. 'plus',
  361. 'primary',
  362. null,
  363. null,
  364. $attributes,
  365. $createElement
  366. );
  367. }
  368. /**
  369. * Returns a button with the primary color and a pencil icon
  370. * @param string $label Text appearing on the button
  371. * @param string $name Element name (for form treatment purposes)
  372. * @param bool $createElement Whether to use the create or add method
  373. * @return HTML_QuickForm_button
  374. */
  375. public function addButtonUpdate($label, $name = 'submit', $createElement = false)
  376. {
  377. return $this->addButton(
  378. $name,
  379. $label,
  380. 'pencil',
  381. 'primary',
  382. null,
  383. null,
  384. array(),
  385. $createElement
  386. );
  387. }
  388. /**
  389. * Returns a button with the danger color and a trash icon
  390. * @param string $label Text appearing on the button
  391. * @param string $name Element name (for form treatment purposes)
  392. * @param bool $createElement Whether to use the create or add method
  393. *
  394. * @return HTML_QuickForm_button
  395. */
  396. public function addButtonDelete($label, $name = 'submit', $createElement = false)
  397. {
  398. return $this->addButton(
  399. $name,
  400. $label,
  401. 'trash',
  402. 'danger',
  403. null,
  404. null,
  405. array(),
  406. $createElement
  407. );
  408. }
  409. /**
  410. * Returns a move style button
  411. * @param string $label Text appearing on the button
  412. * @param string $name Element name (for form treatment purposes)
  413. * @param bool $createElement Whether to use the create or add method
  414. *
  415. * @return HTML_QuickForm_button
  416. */
  417. public function addButtonMove($label, $name = 'submit', $createElement = false)
  418. {
  419. return $this->addButton(
  420. $name,
  421. $label,
  422. 'arrow-circle-right',
  423. 'primary',
  424. null,
  425. null,
  426. array(),
  427. $createElement
  428. );
  429. }
  430. /**
  431. * Returns a button with the primary color and a paper-plane icon
  432. * @param string $label Text appearing on the button
  433. * @param string $name Element name (for form treatment purposes)
  434. * @param bool $createElement Whether to use the create or add method
  435. *
  436. * @return HTML_QuickForm_button
  437. */
  438. public function addButtonSend($label, $name = 'submit', $createElement = false, $attributes = array())
  439. {
  440. return $this->addButton(
  441. $name,
  442. $label,
  443. 'paper-plane',
  444. 'primary',
  445. null,
  446. null,
  447. $attributes,
  448. $createElement
  449. );
  450. }
  451. /**
  452. * Returns a button with the default (grey?) color and a magnifier icon
  453. * @param string $label Text appearing on the button
  454. * @param string $name Element name (for form treatment purposes)
  455. *
  456. * @return HTML_QuickForm_button
  457. */
  458. public function addButtonSearch($label = null, $name = 'submit', $attributes = array())
  459. {
  460. if (empty($label)) {
  461. $label = get_lang('Search');
  462. }
  463. return $this->addButton($name, $label, 'search', 'default', null, null, $attributes);
  464. }
  465. /**
  466. * Returns a button with the primary color and a right-pointing arrow icon
  467. * @param string $label Text appearing on the button
  468. * @param string $name Element name (for form treatment purposes)
  469. * @param array $attributes Additional attributes
  470. * @return HTML_QuickForm_button
  471. */
  472. public function addButtonNext($label, $name = 'submit', $attributes = array())
  473. {
  474. return $this->addButton(
  475. $name,
  476. $label,
  477. 'arrow-right',
  478. 'primary',
  479. null,
  480. null,
  481. $attributes
  482. );
  483. }
  484. /**
  485. * Returns a button with the primary color and a check mark icon
  486. * @param string $label Text appearing on the button
  487. * @param string $name Element name (for form treatment purposes)
  488. * @param bool $createElement Whether to use the create or add method
  489. * @return HTML_QuickForm_button
  490. */
  491. public function addButtonImport($label, $name = 'submit', $createElement = false)
  492. {
  493. return $this->addButton(
  494. $name,
  495. $label,
  496. 'check',
  497. 'primary',
  498. null,
  499. null,
  500. array(),
  501. $createElement
  502. );
  503. }
  504. /**
  505. * Returns a button with the primary color and a check-mark icon
  506. * @param string $label Text appearing on the button
  507. * @param string $name Element name (for form treatment purposes)
  508. * @param bool $createElement Whether to use the create or add method
  509. * @return HTML_QuickForm_button
  510. */
  511. public function addButtonExport($label, $name = 'submit', $createElement = false)
  512. {
  513. return $this->addButton(
  514. $name,
  515. $label,
  516. 'check',
  517. 'primary',
  518. null,
  519. null,
  520. array(),
  521. $createElement
  522. );
  523. }
  524. /**
  525. * Shortcut to filter button
  526. * @param string $label Text appearing on the button
  527. * @param string $name Element name (for form treatment purposes)
  528. * @param bool $createElement Whether to use the create or add method
  529. * @return HTML_QuickForm_button
  530. */
  531. public function addButtonFilter($label, $name = 'submit', $createElement = false)
  532. {
  533. return $this->addButton(
  534. $name,
  535. $label,
  536. 'filter',
  537. 'primary',
  538. null,
  539. null,
  540. array(),
  541. $createElement
  542. );
  543. }
  544. /**
  545. * Shortcut to reset button
  546. * @param string $label Text appearing on the button
  547. * @param string $name Element name (for form treatment purposes)
  548. * @param bool $createElement Whether to use the create or add method
  549. * @return HTML_QuickForm_button
  550. */
  551. public function addButtonReset($label, $name = 'reset', $createElement = false)
  552. {
  553. $icon = 'eraser';
  554. $style = 'default';
  555. $size = 'default';
  556. $class = null;
  557. $attributes = array();
  558. if ($createElement) {
  559. return $this->createElement(
  560. 'reset',
  561. $name,
  562. $label,
  563. $icon,
  564. $style,
  565. $size,
  566. $class,
  567. $attributes
  568. );
  569. }
  570. return $this->addElement(
  571. 'reset',
  572. $name,
  573. $label,
  574. $icon,
  575. $style,
  576. $size,
  577. $class,
  578. $attributes
  579. );
  580. }
  581. /**
  582. * Returns a button with the primary color and an upload icon
  583. * @param string $label Text appearing on the button
  584. * @param string $name Element name (for form treatment purposes)
  585. * @param bool $createElement Whether to use the create or add method
  586. *
  587. * @return HTML_QuickForm_button
  588. */
  589. public function addButtonUpload($label, $name = 'submit', $createElement = false)
  590. {
  591. return $this->addButton(
  592. $name,
  593. $label,
  594. 'upload',
  595. 'primary',
  596. null,
  597. null,
  598. array(),
  599. $createElement
  600. );
  601. }
  602. /**
  603. * Returns a button with the primary color and a download icon
  604. * @param string $label Text appearing on the button
  605. * @param string $name Element name (for form treatment purposes)
  606. * @param bool $createElement Whether to use the create or add method
  607. *
  608. * @return HTML_QuickForm_button
  609. */
  610. public function addButtonDownload($label, $name = 'submit', $createElement = false)
  611. {
  612. return $this->addButton(
  613. $name,
  614. $label,
  615. 'download',
  616. 'primary',
  617. null,
  618. null,
  619. array(),
  620. $createElement
  621. );
  622. }
  623. /**
  624. * Returns a button with the primary color and a magnifier icon
  625. * @param string $label Text appearing on the button
  626. * @param string $name Element name (for form treatment purposes)
  627. * @param bool $createElement Whether to use the create or add method
  628. *
  629. * @return HTML_QuickForm_button
  630. */
  631. public function addButtonPreview($label, $name = 'submit', $createElement = false)
  632. {
  633. return $this->addButton(
  634. $name,
  635. $label,
  636. 'search',
  637. 'primary',
  638. null,
  639. null,
  640. array(),
  641. $createElement
  642. );
  643. }
  644. /**
  645. * Returns a button with the primary color and a copy (double sheet) icon
  646. * @param string $label Text appearing on the button
  647. * @param string $name Element name (for form treatment purposes)
  648. * @param bool $createElement Whether to use the create or add method
  649. *
  650. * @return HTML_QuickForm_button
  651. */
  652. public function addButtonCopy($label, $name = 'submit', $createElement = false)
  653. {
  654. return $this->addButton(
  655. $name,
  656. $label,
  657. 'copy',
  658. 'primary',
  659. null,
  660. null,
  661. array(),
  662. $createElement
  663. );
  664. }
  665. /**
  666. * @param string $name
  667. * @param string $label
  668. * @param string $text
  669. * @param array $attributes
  670. *
  671. * @return HTML_QuickForm_checkbox
  672. */
  673. public function addCheckBox($name, $label, $text = '', $attributes = array())
  674. {
  675. return $this->addElement('checkbox', $name, $label, $text, $attributes);
  676. }
  677. /**
  678. * @param string $name
  679. * @param string $label
  680. * @param array $options
  681. * @param array $attributes
  682. *
  683. * @return HTML_QuickForm_group
  684. */
  685. public function addCheckBoxGroup($name, $label, $options = array(), $attributes = array())
  686. {
  687. $group = array();
  688. foreach ($options as $value => $text) {
  689. $attributes['value'] = $value;
  690. $group[] = $this->createElement(
  691. 'checkbox',
  692. $value,
  693. null,
  694. $text,
  695. $attributes
  696. );
  697. }
  698. return $this->addGroup($group, $name, $label);
  699. }
  700. /**
  701. * @param string $name
  702. * @param string $label
  703. * @param array $options
  704. * @param array $attributes
  705. *
  706. * @return HTML_QuickForm_radio
  707. */
  708. public function addRadio($name, $label, $options = array(), $attributes = array())
  709. {
  710. $group = array();
  711. foreach ($options as $key => $value) {
  712. $group[] = $this->createElement('radio', null, null, $value, $key, $attributes);
  713. }
  714. return $this->addGroup($group, $name, $label);
  715. }
  716. /**
  717. * @param string $name
  718. * @param string $label
  719. * @param array $options
  720. * @param array $attributes
  721. *
  722. * @return HTML_QuickForm_select
  723. */
  724. public function addSelect($name, $label, $options = array(), $attributes = array())
  725. {
  726. return $this->addElement('select', $name, $label, $options, $attributes);
  727. }
  728. /**
  729. * @param $name
  730. * @param $label
  731. * @param $collection
  732. * @param array $attributes
  733. * @param bool $addNoneOption
  734. * @param string $textCallable set a function getStringValue() by default __toString()
  735. *
  736. * @return HTML_QuickForm_element
  737. */
  738. public function addSelectFromCollection(
  739. $name,
  740. $label,
  741. $collection,
  742. $attributes = array(),
  743. $addNoneOption = false,
  744. $textCallable = ''
  745. ) {
  746. $options = [];
  747. if ($addNoneOption) {
  748. $options[0] = get_lang('None');
  749. }
  750. if (!empty($collection)) {
  751. foreach ($collection as $item) {
  752. $text = $item;
  753. if (!empty($textCallable)) {
  754. $text = $item->$textCallable();
  755. }
  756. $options[$item->getId()] = $text;
  757. }
  758. }
  759. return $this->addElement('select', $name, $label, $options, $attributes);
  760. }
  761. /**
  762. * @param string $label
  763. * @param string $text
  764. *
  765. * @return HTML_QuickForm_label
  766. */
  767. public function addLabel($label, $text)
  768. {
  769. return $this->addElement('label', $label, $text);
  770. }
  771. /**
  772. * @param string $text
  773. */
  774. public function addHeader($text)
  775. {
  776. $this->addElement('header', $text);
  777. }
  778. /**
  779. * @param string $name
  780. * @param string $label
  781. * @param array $attributes
  782. * @throws Exception if the file doesn't have an id
  783. */
  784. public function addFile($name, $label, $attributes = array())
  785. {
  786. $element = $this->addElement('file', $name, $label, $attributes);
  787. if (isset($attributes['crop_image'])) {
  788. $id = $element->getAttribute('id');
  789. if (empty($id)) {
  790. throw new Exception('If you use the crop functionality the element must have an id');
  791. }
  792. $this->addHtml('
  793. <div class="form-group">
  794. <label for="cropImage" id="'.$id.'_label_crop_image" class="col-sm-2 control-label"></label>
  795. <div class="col-sm-8">
  796. <div id="'.$id.'_crop_image" class="cropCanvas">
  797. <img id="'.$id.'_preview_image">
  798. </div>
  799. <div>
  800. <button class="btn btn-primary hidden" name="cropButton" id="'.$id.'_crop_button" >
  801. <em class="fa fa-crop"></em> '.
  802. get_lang('CropYourPicture').'
  803. </button>
  804. </div>
  805. </div>
  806. </div>'
  807. );
  808. $this->addHidden($id.'_crop_result', '');
  809. $this->addHidden($id.'_crop_image_base_64', '');
  810. }
  811. }
  812. /**
  813. * @param string $snippet
  814. */
  815. public function addHtml($snippet)
  816. {
  817. $this->addElement('html', $snippet);
  818. }
  819. /**
  820. * Adds a HTML-editor to the form
  821. * @param string $name
  822. * @param string $label The label for the form-element
  823. * @param bool $required (optional) Is the form-element required (default=true)
  824. * @param bool $fullPage (optional) When it is true, the editor loads completed html code for a full page.
  825. * @param array $config (optional) Configuration settings for the online editor.
  826. * @param bool $style
  827. */
  828. public function addHtmlEditor(
  829. $name,
  830. $label,
  831. $required = true,
  832. $fullPage = false,
  833. $config = [],
  834. $style = false
  835. ) {
  836. $attributes = [];
  837. $attributes['rows'] = isset($config['rows']) ? $config['rows'] : 15;
  838. $attributes['cols'] = isset($config['cols']) ? $config['cols'] : 80;
  839. $attributes['cols-size'] = isset($config['cols-size']) ? $config['cols-size'] : [];
  840. $attributes['class'] = isset($config['class']) ? $config['class'] : [];
  841. $this->addElement('html_editor', $name, $label, $attributes, $config);
  842. $this->applyFilter($name, 'trim');
  843. if ($required) {
  844. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  845. }
  846. /** @var HtmlEditor $element */
  847. $element = $this->getElement($name);
  848. if ($style) {
  849. $config['style'] = true;
  850. }
  851. if ($fullPage) {
  852. $config['fullPage'] = true;
  853. }
  854. if ($element->editor) {
  855. $element->editor->processConfig($config);
  856. }
  857. }
  858. /**
  859. * Adds a Google Maps Geolocalization field to the form
  860. *
  861. * @param $name
  862. * @param $label
  863. */
  864. public function addGeoLocationMapField($name, $label)
  865. {
  866. $gMapsPlugin = GoogleMapsPlugin::create();
  867. $geolocalization = $gMapsPlugin->get('enable_api') === 'true';
  868. if ($geolocalization) {
  869. $gmapsApiKey = $gMapsPlugin->get('api_key');
  870. $this->addHtml('<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key='.$gmapsApiKey.'" ></script>');
  871. }
  872. $this->addElement(
  873. 'text',
  874. $name,
  875. $label,
  876. ['id' => $name]
  877. );
  878. $this->applyFilter($name, 'stripslashes');
  879. $this->applyFilter($name, 'trim');
  880. $this->addHtml('
  881. <div class="form-group">
  882. <label for="geolocalization_'.$name.'" class="col-sm-2 control-label"></label>
  883. <div class="col-sm-8">
  884. <button class="null btn btn-default " id="geolocalization_'.$name.'" name="geolocalization_'.$name.'" type="submit"><em class="fa fa-map-marker"></em> '.get_lang('Geolocalization').'</button>
  885. <button class="null btn btn-default " id="myLocation_'.$name.'" name="myLocation_'.$name.'" type="submit"><em class="fa fa-crosshairs"></em> '.get_lang('MyLocation').'</button>
  886. </div>
  887. </div>
  888. ');
  889. $this->addHtml('
  890. <div class="form-group">
  891. <label for="map_'.$name.'" class="col-sm-2 control-label">
  892. '.$label.' - '.get_lang('Map').'
  893. </label>
  894. <div class="col-sm-8">
  895. <div name="map_'.$name.'" id="map_'.$name.'" style="width:100%; height:300px;">
  896. </div>
  897. </div>
  898. </div>
  899. ');
  900. $this->addHtml(
  901. '<script>
  902. $(document).ready(function() {
  903. if (typeof google === "object") {
  904. var address = $("#' . $name.'").val();
  905. initializeGeo'.$name.'(address, false);
  906. $("#geolocalization_'.$name.'").on("click", function() {
  907. var address = $("#'.$name.'").val();
  908. initializeGeo'.$name.'(address, false);
  909. return false;
  910. });
  911. $("#myLocation_'.$name.'").on("click", function() {
  912. myLocation'.$name.'();
  913. return false;
  914. });
  915. $("#'.$name.'").keypress(function (event) {
  916. if (event.which == 13) {
  917. $("#geolocalization_'.$name.'").click();
  918. return false;
  919. }
  920. });
  921. } else {
  922. $("#map_'.$name.'").html("<div class=\"alert alert-info\">'.get_lang('YouNeedToActivateTheGoogleMapsPluginInAdminPlatformToSeeTheMap').'</div>");
  923. }
  924. });
  925. function myLocation'.$name.'() {
  926. if (navigator.geolocation) {
  927. var geoPosition = function(position) {
  928. var lat = position.coords.latitude;
  929. var lng = position.coords.longitude;
  930. var latLng = new google.maps.LatLng(lat, lng);
  931. initializeGeo'.$name.'(false, latLng)
  932. };
  933. var geoError = function(error) {
  934. alert("Geocode ' . get_lang('Error').': " + error);
  935. };
  936. var geoOptions = {
  937. enableHighAccuracy: true
  938. };
  939. navigator.geolocation.getCurrentPosition(geoPosition, geoError, geoOptions);
  940. }
  941. }
  942. function initializeGeo'.$name.'(address, latLng) {
  943. var geocoder = new google.maps.Geocoder();
  944. var latlng = new google.maps.LatLng(-34.397, 150.644);
  945. var myOptions = {
  946. zoom: 15,
  947. center: latlng,
  948. mapTypeControl: true,
  949. mapTypeControlOptions: {
  950. style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
  951. },
  952. navigationControl: true,
  953. mapTypeId: google.maps.MapTypeId.ROADMAP
  954. };
  955. map_'.$name.' = new google.maps.Map(document.getElementById("map_'.$name.'"), myOptions);
  956. var parameter = address ? { "address": address } : latLng ? { "latLng": latLng } : false;
  957. if (geocoder && parameter) {
  958. geocoder.geocode(parameter, function(results, status) {
  959. if (status == google.maps.GeocoderStatus.OK) {
  960. if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
  961. map_'.$name.'.setCenter(results[0].geometry.location);
  962. if (!address) {
  963. $("#'.$name.'").val(results[0].formatted_address);
  964. }
  965. var infowindow = new google.maps.InfoWindow({
  966. content: "<b>" + $("#'.$name.'").val() + "</b>",
  967. size: new google.maps.Size(150, 50)
  968. });
  969. var marker = new google.maps.Marker({
  970. position: results[0].geometry.location,
  971. map: map_'.$name.',
  972. title: $("#'.$name.'").val()
  973. });
  974. google.maps.event.addListener(marker, "click", function() {
  975. infowindow.open(map_'.$name.', marker);
  976. });
  977. } else {
  978. alert("' . get_lang("NotFound").'");
  979. }
  980. } else {
  981. alert("Geocode ' . get_lang('Error').': '.get_lang("AddressField").' '.get_lang("NotFound").'");
  982. }
  983. });
  984. }
  985. }
  986. </script>
  987. ');
  988. }
  989. /**
  990. * @param string $name
  991. * @param string $label
  992. *
  993. * @return mixed
  994. */
  995. public function addButtonAdvancedSettings($name, $label = '')
  996. {
  997. $label = !empty($label) ? $label : get_lang('AdvancedParameters');
  998. return $this->addElement('advanced_settings', $name, $label);
  999. }
  1000. /**
  1001. * Adds a progress loading image to the form.
  1002. *
  1003. */
  1004. public function addProgress($delay = 2, $label = '')
  1005. {
  1006. if (empty($label)) {
  1007. $label = get_lang('PleaseStandBy');
  1008. }
  1009. $this->with_progress_bar = true;
  1010. $id = $this->getAttribute('id');
  1011. $this->updateAttributes("onsubmit=\"javascript: addProgress('".$id."')\"");
  1012. $this->addHtml('<script language="javascript" src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/upload.js" type="text/javascript"></script>');
  1013. }
  1014. /**
  1015. * This function has been created for avoiding changes directly within QuickForm class.
  1016. * When we use it, the element is threated as 'required' to be dealt during validation.
  1017. * @param array $elements The array of elements
  1018. * @param string $message The message displayed
  1019. */
  1020. public function add_multiple_required_rule($elements, $message)
  1021. {
  1022. $this->_required[] = $elements[0];
  1023. $this->addRule($elements, $message, 'multiple_required');
  1024. }
  1025. /**
  1026. * Displays the form.
  1027. * If an element in the form didn't validate, an error message is showed
  1028. * asking the user to complete the form.
  1029. */
  1030. public function display()
  1031. {
  1032. echo $this->returnForm();
  1033. }
  1034. /**
  1035. * Returns the HTML code of the form.
  1036. * @return string $return_value HTML code of the form
  1037. */
  1038. public function returnForm()
  1039. {
  1040. $returnValue = '';
  1041. /** @var HTML_QuickForm_element $element */
  1042. foreach ($this->_elements as $element) {
  1043. $elementError = parent::getElementError($element->getName());
  1044. if (!is_null($elementError)) {
  1045. $returnValue .= Display::return_message($elementError, 'warning').'<br />';
  1046. break;
  1047. }
  1048. }
  1049. $returnValue .= parent::toHtml();
  1050. // Add div-element which is to hold the progress bar
  1051. $id = $this->getAttribute('id');
  1052. if (isset($this->with_progress_bar) && $this->with_progress_bar) {
  1053. $icon = Display::return_icon('progress_bar.gif');
  1054. // @todo improve UI
  1055. $returnValue .= '<br />
  1056. <div id="loading_div_'.$id.'" class="loading_div" style="display:none;margin-left:40%; margin-top:10px; height:50px;">
  1057. '.$icon.'
  1058. </div>
  1059. ';
  1060. }
  1061. return $returnValue;
  1062. }
  1063. /**
  1064. * Returns the HTML code of the form.
  1065. * If an element in the form didn't validate, an error message is showed
  1066. * asking the user to complete the form.
  1067. *
  1068. * @return string $return_value HTML code of the form
  1069. *
  1070. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, august 2006
  1071. * @author Julio Montoya
  1072. * @deprecated use returnForm()
  1073. */
  1074. public function return_form()
  1075. {
  1076. return $this->returnForm();
  1077. }
  1078. /**
  1079. * Create a form validator based on an array of form data:
  1080. *
  1081. * array(
  1082. * 'name' => 'zombie_report_parameters', //optional
  1083. * 'method' => 'GET', //optional
  1084. * 'items' => array(
  1085. * array(
  1086. * 'name' => 'ceiling',
  1087. * 'label' => 'Ceiling', //optional
  1088. * 'type' => 'date',
  1089. * 'default' => date() //optional
  1090. * ),
  1091. * array(
  1092. * 'name' => 'active_only',
  1093. * 'label' => 'ActiveOnly',
  1094. * 'type' => 'checkbox',
  1095. * 'default' => true
  1096. * ),
  1097. * array(
  1098. * 'name' => 'submit_button',
  1099. * 'type' => 'style_submit_button',
  1100. * 'value' => get_lang('Search'),
  1101. * 'attributes' => array('class' => 'search')
  1102. * )
  1103. * )
  1104. * );
  1105. *
  1106. * @param array $form_data
  1107. * @deprecated use normal FormValidator construct
  1108. *
  1109. * @return FormValidator
  1110. */
  1111. public static function create($form_data)
  1112. {
  1113. if (empty($form_data)) {
  1114. return null;
  1115. }
  1116. $form_name = isset($form_data['name']) ? $form_data['name'] : 'form';
  1117. $form_method = isset($form_data['method']) ? $form_data['method'] : 'POST';
  1118. $form_action = isset($form_data['action']) ? $form_data['action'] : '';
  1119. $form_target = isset($form_data['target']) ? $form_data['target'] : '';
  1120. $form_attributes = isset($form_data['attributes']) ? $form_data['attributes'] : null;
  1121. $form_track_submit = isset($form_data['track_submit']) ? $form_data['track_submit'] : true;
  1122. $reset = null;
  1123. $result = new FormValidator($form_name, $form_method, $form_action, $form_target, $form_attributes, $form_track_submit);
  1124. $defaults = array();
  1125. foreach ($form_data['items'] as $item) {
  1126. $name = $item['name'];
  1127. $type = isset($item['type']) ? $item['type'] : 'text';
  1128. $label = isset($item['label']) ? $item['label'] : '';
  1129. if ($type == 'wysiwyg') {
  1130. $element = $result->addHtmlEditor($name, $label);
  1131. } else {
  1132. $element = $result->addElement($type, $name, $label);
  1133. }
  1134. if (isset($item['attributes'])) {
  1135. $attributes = $item['attributes'];
  1136. $element->setAttributes($attributes);
  1137. }
  1138. if (isset($item['value'])) {
  1139. $value = $item['value'];
  1140. $element->setValue($value);
  1141. }
  1142. if (isset($item['default'])) {
  1143. $defaults[$name] = $item['default'];
  1144. }
  1145. if (isset($item['rules'])) {
  1146. $rules = $item['rules'];
  1147. foreach ($rules as $rule) {
  1148. $message = $rule['message'];
  1149. $type = $rule['type'];
  1150. $format = isset($rule['format']) ? $rule['format'] : null;
  1151. $validation = isset($rule['validation']) ? $rule['validation'] : 'server';
  1152. $force = isset($rule['force']) ? $rule['force'] : false;
  1153. $result->addRule($name, $message, $type, $format, $validation, $reset, $force);
  1154. }
  1155. }
  1156. }
  1157. $result->setDefaults($defaults);
  1158. return $result;
  1159. }
  1160. /**
  1161. * @return HTML_QuickForm_Renderer_Default
  1162. */
  1163. public static function getDefaultRenderer()
  1164. {
  1165. return
  1166. isset($GLOBALS['_HTML_QuickForm_default_renderer']) ?
  1167. $GLOBALS['_HTML_QuickForm_default_renderer'] : null;
  1168. }
  1169. /**
  1170. * Adds a input of type url to the form.
  1171. * @param string $name The label for the form-element
  1172. * @param string $label The element name
  1173. * @param bool $required Optional. Is the form-element required (default=true)
  1174. * @param array $attributes Optional. List of attributes for the form-element
  1175. */
  1176. public function addUrl($name, $label, $required = true, $attributes = array())
  1177. {
  1178. $this->addElement('url', $name, $label, $attributes);
  1179. $this->applyFilter($name, 'trim');
  1180. $this->addRule($name, get_lang('InsertAValidUrl'), 'url');
  1181. if ($required) {
  1182. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1183. }
  1184. }
  1185. /**
  1186. * Adds a text field for letters to the form.
  1187. * A trim-filter is attached to the field.
  1188. * @param string $name The element name
  1189. * @param string $label The label for the form-element
  1190. * @param bool $required Optional. Is the form-element required (default=true)
  1191. * @param array $attributes Optional. List of attributes for the form-element
  1192. */
  1193. public function addTextLettersOnly(
  1194. $name,
  1195. $label,
  1196. $required = false,
  1197. $attributes = []
  1198. ) {
  1199. $attributes = array_merge(
  1200. $attributes,
  1201. [
  1202. 'pattern' => '[a-zA-ZñÑ]+',
  1203. 'title' => get_lang('OnlyLetters')
  1204. ]
  1205. );
  1206. $this->addElement(
  1207. 'text',
  1208. $name,
  1209. [
  1210. $label,
  1211. get_lang('OnlyLetters')
  1212. ],
  1213. $attributes
  1214. );
  1215. $this->applyFilter($name, 'trim');
  1216. if ($required) {
  1217. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1218. }
  1219. $this->addRule(
  1220. $name,
  1221. get_lang('OnlyLetters'),
  1222. 'regex',
  1223. '/^[a-zA-ZñÑ]+$/'
  1224. );
  1225. }
  1226. /**
  1227. * Adds a text field for alphanumeric characters to the form.
  1228. * A trim-filter is attached to the field.
  1229. * @param string $name The element name
  1230. * @param string $label The label for the form-element
  1231. * @param bool $required Optional. Is the form-element required (default=true)
  1232. * @param array $attributes Optional. List of attributes for the form-element
  1233. */
  1234. public function addTextAlphanumeric(
  1235. $name,
  1236. $label,
  1237. $required = false,
  1238. $attributes = []
  1239. ) {
  1240. $attributes = array_merge(
  1241. $attributes,
  1242. [
  1243. 'pattern' => '[a-zA-Z0-9ñÑ]+',
  1244. 'title' => get_lang('OnlyLettersAndNumbers')
  1245. ]
  1246. );
  1247. $this->addElement(
  1248. 'text',
  1249. $name,
  1250. [
  1251. $label,
  1252. get_lang('OnlyLettersAndNumbers')
  1253. ],
  1254. $attributes
  1255. );
  1256. $this->applyFilter($name, 'trim');
  1257. if ($required) {
  1258. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1259. }
  1260. $this->addRule(
  1261. $name,
  1262. get_lang('OnlyLettersAndNumbers'),
  1263. 'regex',
  1264. '/^[a-zA-Z0-9ÑÑ]+$/'
  1265. );
  1266. }
  1267. /**
  1268. * @param string $name
  1269. * @param $label
  1270. * @param bool $required
  1271. * @param array $attributes
  1272. * @param bool $allowNegative
  1273. * @param integer $minValue
  1274. * @param null $maxValue
  1275. */
  1276. public function addFloat(
  1277. $name,
  1278. $label,
  1279. $required = false,
  1280. $attributes = [],
  1281. $allowNegative = false,
  1282. $minValue = null,
  1283. $maxValue = null
  1284. ) {
  1285. $this->addElement(
  1286. 'FloatNumber',
  1287. $name,
  1288. $label,
  1289. $attributes
  1290. );
  1291. $this->applyFilter($name, 'trim');
  1292. if ($required) {
  1293. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1294. }
  1295. // Rule allows "," and "."
  1296. /*$this->addRule(
  1297. $name,
  1298. get_lang('OnlyNumbers'),
  1299. 'regex',
  1300. '/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)|(^-?\d\d*\,\d*$)|(^-?\,\d\d*$)/'
  1301. );*/
  1302. if ($allowNegative == false) {
  1303. $this->addRule(
  1304. $name,
  1305. get_lang('NegativeValue'),
  1306. 'compare',
  1307. '>=',
  1308. 'server',
  1309. false,
  1310. false,
  1311. 0
  1312. );
  1313. }
  1314. if (!is_null($minValue)) {
  1315. $this->addRule(
  1316. $name,
  1317. get_lang('UnderMin'),
  1318. 'compare',
  1319. '>=',
  1320. 'server',
  1321. false,
  1322. false,
  1323. $minValue
  1324. );
  1325. }
  1326. if (!is_null($maxValue)) {
  1327. $this->addRule(
  1328. $name,
  1329. get_lang('OverMax'),
  1330. 'compare',
  1331. '<=',
  1332. 'server',
  1333. false,
  1334. false,
  1335. $maxValue
  1336. );
  1337. }
  1338. }
  1339. /**
  1340. * Adds a text field for letters and spaces to the form.
  1341. * A trim-filter is attached to the field.
  1342. * @param string $name The element name
  1343. * @param string $label The label for the form-element
  1344. * @param bool $required Optional. Is the form-element required (default=true)
  1345. * @param array $attributes Optional. List of attributes for the form-element
  1346. */
  1347. public function addTextLettersAndSpaces(
  1348. $name,
  1349. $label,
  1350. $required = false,
  1351. $attributes = []
  1352. ) {
  1353. $attributes = array_merge(
  1354. $attributes,
  1355. [
  1356. 'pattern' => '[a-zA-ZñÑ\s]+',
  1357. 'title' => get_lang('OnlyLettersAndSpaces')
  1358. ]
  1359. );
  1360. $this->addElement(
  1361. 'text',
  1362. $name,
  1363. [
  1364. $label,
  1365. get_lang('OnlyLettersAndSpaces')
  1366. ],
  1367. $attributes
  1368. );
  1369. $this->applyFilter($name, 'trim');
  1370. if ($required) {
  1371. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1372. }
  1373. $this->addRule(
  1374. $name,
  1375. get_lang('OnlyLettersAndSpaces'),
  1376. 'regex',
  1377. '/^[a-zA-ZñÑ\s]+$/'
  1378. );
  1379. }
  1380. /**
  1381. * Adds a text field for alphanumeric and spaces characters to the form.
  1382. * A trim-filter is attached to the field.
  1383. * @param string $name The element name
  1384. * @param string $label The label for the form-element
  1385. * @param bool $required Optional. Is the form-element required (default=true)
  1386. * @param array $attributes Optional. List of attributes for the form-element
  1387. */
  1388. public function addTextAlphanumericAndSpaces(
  1389. $name,
  1390. $label,
  1391. $required = false,
  1392. $attributes = []
  1393. ) {
  1394. $attributes = array_merge(
  1395. $attributes,
  1396. [
  1397. 'pattern' => '[a-zA-Z0-9ñÑ\s]+',
  1398. 'title' => get_lang('OnlyLettersAndNumbersAndSpaces')
  1399. ]
  1400. );
  1401. $this->addElement(
  1402. 'text',
  1403. $name,
  1404. [
  1405. $label,
  1406. get_lang('OnlyLettersAndNumbersAndSpaces')
  1407. ],
  1408. $attributes
  1409. );
  1410. $this->applyFilter($name, 'trim');
  1411. if ($required) {
  1412. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  1413. }
  1414. $this->addRule(
  1415. $name,
  1416. get_lang('OnlyLettersAndNumbersAndSpaces'),
  1417. 'regex',
  1418. '/^[a-zA-Z0-9ñÑ\s]+$/'
  1419. );
  1420. }
  1421. /**
  1422. * @param string $url
  1423. */
  1424. public function addMultipleUpload($url)
  1425. {
  1426. $inputName = 'input_file_upload';
  1427. $this->addMultipleUploadJavascript($url, $inputName);
  1428. $this->addHtml('
  1429. <div class="description-upload">
  1430. '.get_lang('ClickToSelectOrDragAndDropMultipleFilesOnTheUploadField').'
  1431. </div>
  1432. <span class="btn btn-success fileinput-button">
  1433. <i class="glyphicon glyphicon-plus"></i>
  1434. <span>'.get_lang('AddFiles').'</span>
  1435. <!-- The file input field used as target for the file upload widget -->
  1436. <input id="'.$inputName.'" type="file" name="files[]" multiple>
  1437. </span>
  1438. <div id="dropzone">
  1439. <div class="button-load">
  1440. '.get_lang('UploadFiles').'
  1441. </div>
  1442. </div>
  1443. <br />
  1444. <!-- The global progress bar -->
  1445. <div id="progress" class="progress">
  1446. <div class="progress-bar progress-bar-success"></div>
  1447. </div>
  1448. <div id="files" class="files"></div>
  1449. ');
  1450. }
  1451. /**
  1452. *
  1453. * @param string $url page that will handle the upload
  1454. * @param string $inputName
  1455. */
  1456. private function addMultipleUploadJavascript($url, $inputName)
  1457. {
  1458. $icon = Display::return_icon('file_txt.gif');
  1459. $this->addHtml("
  1460. <script>
  1461. $(function () {
  1462. 'use strict';
  1463. $('#".$this->getAttribute('id')."').submit(function() {
  1464. return false;
  1465. });
  1466. $('#dropzone').on('click', function() {
  1467. $('#".$inputName."').click();
  1468. });
  1469. var url = '".$url."';
  1470. var uploadButton = $('<button/>')
  1471. .addClass('btn btn-primary')
  1472. .prop('disabled', true)
  1473. .text('".addslashes(get_lang('Loading'))."')
  1474. .on('click', function () {
  1475. var \$this = $(this),
  1476. data = \$this.data();
  1477. \$this
  1478. .off('click')
  1479. .text('".addslashes(get_lang('Cancel'))."')
  1480. .on('click', function () {
  1481. \$this.remove();
  1482. data.abort();
  1483. });
  1484. data.submit().always(function () {
  1485. \$this.remove();
  1486. });
  1487. });
  1488. $('#".$inputName."').fileupload({
  1489. url: url,
  1490. dataType: 'json',
  1491. // Enable image resizing, except for Android and Opera,
  1492. // which actually support image resizing, but fail to
  1493. // send Blob objects via XHR requests:
  1494. disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),
  1495. previewMaxWidth: 100,
  1496. previewMaxHeight: 100,
  1497. previewCrop: true,
  1498. dropzone: $('#dropzone'),
  1499. }).on('fileuploadadd', function (e, data) {
  1500. data.context = $('<div class=\"row\" style=\"margin-bottom:35px\" />').appendTo('#files');
  1501. $.each(data.files, function (index, file) {
  1502. var node = $('<div class=\"col-sm-5\">').text(file.name);
  1503. node.appendTo(data.context);
  1504. });
  1505. }).on('fileuploadprocessalways', function (e, data) {
  1506. var index = data.index,
  1507. file = data.files[index],
  1508. node = $(data.context.children()[index]);
  1509. if (file.preview) {
  1510. data.context
  1511. .prepend($('<div class=\"col-sm-2\">').html(file.preview))
  1512. ;
  1513. } else {
  1514. data.context
  1515. .prepend($('<div class=\"col-sm-2\">').html('".$icon."'))
  1516. ;
  1517. }
  1518. if (index + 1 === data.files.length) {
  1519. data.context.find('button')
  1520. .text('Upload')
  1521. .prop('disabled', !!data.files.error);
  1522. }
  1523. }).on('fileuploadprogressall', function (e, data) {
  1524. var progress = parseInt(data.loaded / data.total * 100, 10);
  1525. $('#progress .progress-bar').css(
  1526. 'width',
  1527. progress + '%'
  1528. );
  1529. }).on('fileuploaddone', function (e, data) {
  1530. $.each(data.result.files, function (index, file) {
  1531. if (file.url) {
  1532. var link = $('<a>')
  1533. .attr('target', '_blank')
  1534. .prop('href', file.url);
  1535. $(data.context.children()[index]).parent().wrap(link);
  1536. var successMessage = $('<div class=\"col-sm-3\">').html($('<span class=\"alert alert-success\"/>').text('" . addslashes(get_lang('UplUploadSucceeded'))."'));
  1537. $(data.context.children()[index]).parent().append(successMessage);
  1538. } else if (file.error) {
  1539. var error = $('<div class=\"col-sm-3\">').html($('<span class=\"alert alert-danger\"/>').text(file.error));
  1540. $(data.context.children()[index]).parent().append(error);
  1541. }
  1542. });
  1543. $('#dropzone').removeClass('hover');
  1544. }).on('fileuploadfail', function (e, data) {
  1545. $.each(data.files, function (index) {
  1546. var failedMessage = '" . addslashes(get_lang('UplUploadFailed'))."';
  1547. var error = $('<div class=\"col-sm-3\">').html($('<span class=\"alert alert-danger\"/>').text(failedMessage));
  1548. $(data.context.children()[index]).parent().append(error);
  1549. });
  1550. $('#dropzone').removeClass('hover');
  1551. }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');
  1552. $('#dropzone').on('dragover', function (e) {
  1553. // dragleave callback implementation
  1554. $('#dropzone').addClass('hover');
  1555. });
  1556. $('#dropzone').on('dragleave', function (e) {
  1557. $('#dropzone').removeClass('hover');
  1558. });
  1559. $('.fileinput-button').hide();
  1560. });
  1561. </script>");
  1562. }
  1563. /**
  1564. * @param string $elementName
  1565. * @param string $groupName if element is inside a group
  1566. * @throws Exception
  1567. */
  1568. public function addPasswordRule($elementName, $groupName = '')
  1569. {
  1570. // Constant defined in old config/profile.conf.php
  1571. if (CHECK_PASS_EASY_TO_FIND === true) {
  1572. $message = get_lang('PassTooEasy').': '.api_generate_password();
  1573. if (!empty($groupName)) {
  1574. $groupObj = $this->getElement($groupName);
  1575. if ($groupObj instanceof HTML_QuickForm_group) {
  1576. $elementName = $groupObj->getElementName($elementName);
  1577. if ($elementName === false) {
  1578. throw new Exception("The $groupName doesn't have the element $elementName");
  1579. }
  1580. $this->_rules[$elementName][] = array(
  1581. 'type' => 'callback',
  1582. 'format' => 'api_check_password',
  1583. 'message' => $message,
  1584. 'validation' => '',
  1585. 'reset' => false,
  1586. 'group' => $groupName
  1587. );
  1588. }
  1589. } else {
  1590. $this->addRule(
  1591. $elementName,
  1592. $message,
  1593. 'callback',
  1594. 'api_check_password'
  1595. );
  1596. }
  1597. }
  1598. }
  1599. }
  1600. /**
  1601. * Cleans HTML text filter
  1602. * @param string $html HTML to clean
  1603. * @param int $mode (optional)
  1604. * @return string The cleaned HTML
  1605. */
  1606. function html_filter($html, $mode = NO_HTML)
  1607. {
  1608. $allowed_tags = HTML_QuickForm_Rule_HTML::get_allowed_tags($mode);
  1609. $cleaned_html = kses($html, $allowed_tags);
  1610. return $cleaned_html;
  1611. }
  1612. function html_filter_teacher($html)
  1613. {
  1614. return html_filter($html, TEACHER_HTML);
  1615. }
  1616. function html_filter_student($html)
  1617. {
  1618. return html_filter($html, STUDENT_HTML);
  1619. }
  1620. function html_filter_teacher_fullpage($html)
  1621. {
  1622. return html_filter($html, TEACHER_HTML_FULLPAGE);
  1623. }
  1624. function html_filter_student_fullpage($html)
  1625. {
  1626. return html_filter($html, STUDENT_HTML_FULLPAGE);
  1627. }
  1628. /**
  1629. * Cleans mobile phone number text
  1630. * @param string $mobilePhoneNumber Mobile phone number to clean
  1631. * @return string The cleaned mobile phone number
  1632. */
  1633. function mobile_phone_number_filter($mobilePhoneNumber)
  1634. {
  1635. $mobilePhoneNumber = str_replace(array('+', '(', ')'), '', $mobilePhoneNumber);
  1636. return ltrim($mobilePhoneNumber, '0');
  1637. }