FormValidator.class.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. <?php
  2. /*
  3. ==============================================================================
  4. Dokeos - elearning and course management software
  5. Copyright (c) 2004-2005 Dokeos S.A.
  6. Copyright (c) Bart Mollet, Hogeschool Gent
  7. For a full list of contributors, see "credits.txt".
  8. The full license can be read in "license.txt".
  9. This program is free software; you can redistribute it and/or
  10. modify it under the terms of the GNU General Public License
  11. as published by the Free Software Foundation; either version 2
  12. of the License, or (at your option) any later version.
  13. See the GNU General Public License for more details.
  14. Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
  15. Mail: info@dokeos.com
  16. ==============================================================================
  17. */
  18. require_once ('HTML/QuickForm.php');
  19. require_once ('HTML/QuickForm/advmultiselect.php');
  20. /**
  21. * Filter
  22. */
  23. define('NO_HTML', 1);
  24. define('STUDENT_HTML', 2);
  25. define('TEACHER_HTML', 3);
  26. define('STUDENT_HTML_FULLPAGE',4);
  27. define('TEACHER_HTML_FULLPAGE',5);
  28. /**
  29. * Objects of this class can be used to create/manipulate/validate user input.
  30. */
  31. class FormValidator extends HTML_QuickForm
  32. {
  33. var $with_progress_bar=false;
  34. /**
  35. * Constructor
  36. * @param string $form_name Name of the form
  37. * @param string $method Method ('post' (default) or 'get')
  38. * @param string $action Action (default is $PHP_SELF)
  39. * @param string $target Form's target defaults to '_self'
  40. * @param mixed $attributes (optional)Extra attributes for <form> tag
  41. * @param bool $trackSubmit (optional)Whether to track if the form was
  42. * submitted by adding a special hidden field (default = true)
  43. */
  44. function FormValidator($form_name, $method = 'post', $action = '', $target = '', $attributes = null, $trackSubmit = true)
  45. {
  46. $this->HTML_QuickForm($form_name, $method,$action, $target, $attributes, $trackSubmit);
  47. // Load some custom elements and rules
  48. $dir = dirname(__FILE__).'/';
  49. $this->registerElementType('html_editor', $dir.'Element/html_editor.php', 'HTML_QuickForm_html_editor');
  50. $this->registerElementType('datepicker', $dir.'Element/datepicker.php', 'HTML_QuickForm_datepicker');
  51. $this->registerElementType('datepickerdate', $dir.'Element/datepickerdate.php', 'HTML_QuickForm_datepickerdate');
  52. $this->registerElementType('receivers', $dir.'Element/receivers.php', 'HTML_QuickForm_receivers');
  53. $this->registerElementType('select_language', $dir.'Element/select_language.php', 'HTML_QuickForm_Select_Language');
  54. $this->registerElementType('select_theme', $dir.'Element/select_theme.php', 'HTML_QuickForm_Select_Theme');
  55. $this->registerElementType('style_button', $dir.'Element/style_button.php', 'HTML_QuickForm_stylebutton');
  56. $this->registerElementType('style_submit_button', $dir.'Element/style_submit_button.php', 'HTML_QuickForm_stylesubmitbutton');
  57. $this->registerElementType('style_reset_button', $dir.'Element/style_reset_button.php', 'HTML_QuickForm_styleresetbutton');
  58. $this->registerRule('date', null, 'HTML_QuickForm_Rule_Date', $dir.'Rule/Date.php');
  59. $this->registerRule('date_compare', null, 'HTML_QuickForm_Rule_DateCompare', $dir.'Rule/DateCompare.php');
  60. $this->registerRule('html',null,'HTML_QuickForm_Rule_HTML',$dir.'Rule/HTML.php');
  61. $this->registerRule('username_available',null,'HTML_QuickForm_Rule_UsernameAvailable',$dir.'Rule/UsernameAvailable.php');
  62. $this->registerRule('username',null,'HTML_QuickForm_Rule_Username',$dir.'Rule/Username.php');
  63. $this->registerRule('filetype',null,'HTML_QuickForm_Rule_Filetype',$dir.'Rule/Filetype.php');
  64. $this->registerRule('multiple_required','required','HTML_QuickForm_Rule_MultipleRequired',$dir.'Rule/MultipleRequired.php');
  65. // Modify the default templates
  66. $renderer = & $this->defaultRenderer();
  67. $form_template = <<<EOT
  68. <form {attributes}>
  69. {content}
  70. <div class="clear">
  71. &nbsp;
  72. </div>
  73. </form>
  74. EOT;
  75. $renderer->setFormTemplate($form_template);
  76. $element_template = <<<EOT
  77. <div class="row">
  78. <div class="label">
  79. <!-- BEGIN required --><span class="form_required">*</span> <!-- END required -->{label}
  80. </div>
  81. <div class="formw">
  82. <!-- BEGIN error --><span class="form_error">{error}</span><br /><!-- END error --> {element}
  83. </div>
  84. </div>
  85. EOT;
  86. $renderer->setElementTemplate($element_template);
  87. $header_template = <<<EOT
  88. <div class="row">
  89. <div class="form_header">{header}</div>
  90. </div>
  91. EOT;
  92. $renderer->setHeaderTemplate($header_template);
  93. HTML_QuickForm :: setRequiredNote('<span class="form_required">*</span> <small>'.get_lang('ThisFieldIsRequired').'</small>');
  94. $required_note_template = <<<EOT
  95. <div class="row">
  96. <div class="label"></div>
  97. <div class="formw">{requiredNote}</div>
  98. </div>
  99. EOT;
  100. $renderer->setRequiredNoteTemplate($required_note_template);
  101. }
  102. /**
  103. * Add a textfield to the form.
  104. * A trim-filter is attached to the field.
  105. * @param string $label The label for the form-element
  106. * @param string $name The element name
  107. * @param boolean $required Is the form-element required (default=true)
  108. * @param array $attributes Optional list of attributes for the form-element
  109. */
  110. function add_textfield( $name, $label,$required = true, $attributes = array())
  111. {
  112. $this->addElement('text',$name,$label,$attributes);
  113. $this->applyFilter($name,'trim');
  114. if($required)
  115. {
  116. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  117. }
  118. }
  119. /**
  120. * Add a HTML-editor to the form to fill in a title.
  121. * A trim-filter is attached to the field.
  122. * A HTML-filter is attached to the field (cleans HTML)
  123. * A rule is attached to check for unwanted HTML
  124. * @param string $label The label for the form-element
  125. * @param string $name The element name
  126. * @param boolean $required Is the form-element required (default=true)
  127. * @param boolean $full_page When it is true, the editor loads completed html code for a full page.
  128. * @param array $editor_config Optional configuration settings for the online editor.
  129. */
  130. function add_html_editor($name, $label, $required = true, $full_page = false, $config = null)
  131. {
  132. $this->addElement('html_editor', $name, $label, 'rows="15" cols="80"', $config);
  133. $this->applyFilter($name,'trim');
  134. $html_type = STUDENT_HTML;
  135. if(!empty($_SESSION['status']))
  136. {
  137. $html_type = $_SESSION['status'] == COURSEMANAGER ? TEACHER_HTML : STUDENT_HTML;
  138. }
  139. if (is_array($config))
  140. {
  141. if (isset($config['FullPage']))
  142. {
  143. $full_page = is_bool($config['FullPage']) ? $config['FullPage'] : ($config['FullPage'] === 'true');
  144. }
  145. else
  146. {
  147. $config['FullPage'] = $full_page;
  148. }
  149. }
  150. else
  151. {
  152. $config = array('FullPage' => (bool) $full_page);
  153. }
  154. if($full_page)
  155. {
  156. $html_type = $_SESSION['status'] == COURSEMANAGER ? TEACHER_HTML_FULLPAGE : STUDENT_HTML_FULLPAGE;
  157. //First *filter* the HTML (markup, indenting, ...)
  158. //$this->applyFilter($name,'html_filter_teacher_fullpage');
  159. }
  160. else
  161. {
  162. //First *filter* the HTML (markup, indenting, ...)
  163. //$this->applyFilter($name,'html_filter_teacher');
  164. }
  165. if($required)
  166. {
  167. $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required');
  168. }
  169. if($full_page)
  170. {
  171. $el = $this->getElement($name);
  172. $el->fullPage = true;
  173. }
  174. //Add rule to check not-allowed HTML
  175. //$this->addRule($name,get_lang('SomeHTMLNotAllowed'),'html',$html_type);
  176. }
  177. /**
  178. * Add a datepicker element to the form
  179. * A rule is added to check if the date is a valid one
  180. * @param string $label The label for the form-element
  181. * @param string $name The element name
  182. */
  183. function add_datepicker($name,$label)
  184. {
  185. $this->addElement('datepicker', $name, $label, array ('form_name' => $this->getAttribute('name')));
  186. $this->_elements[$this->_elementIndex[$name]]->setLocalOption('minYear', 1900);
  187. $this->addRule($name, get_lang('InvalidDate'), 'date');
  188. }
  189. /**
  190. * Add a datepickerdate element to the form
  191. * A rule is added to check if the date is a valid one
  192. * @param string $label The label for the form-element
  193. * @param string $name The element name
  194. */
  195. function add_datepickerdate($name,$label)
  196. {
  197. $this->addElement('datepickerdate', $name, $label, array ('form_name' => $this->getAttribute('name')));
  198. $this->_elements[$this->_elementIndex[$name]]->setLocalOption('minYear', 1900);
  199. $this->addRule($name, get_lang('InvalidDate'), 'date');
  200. }
  201. /**
  202. * Add a timewindow element to the form.
  203. * 2 datepicker elements are added and a rule to check if the first date is
  204. * before the second one.
  205. * @param string $label The label for the form-element
  206. * @param string $name The element name
  207. */
  208. function add_timewindow($name_1, $name_2, $label_1,$label_2)
  209. {
  210. $this->add_datepicker($name_1, $label_1);
  211. $this->add_datepicker( $name_2, $label_2);
  212. $this->addRule(array ($name_1, $name_2), get_lang('StartDateShouldBeBeforeEndDate'), 'date_compare', 'lte');
  213. }
  214. /**
  215. * Add a button to the form to add resources.
  216. */
  217. function add_resource_button()
  218. {
  219. $group[] = $this->createElement('static','add_resource_img',null,'<img src="'.api_get_path(WEB_CODE_PATH).'img/attachment.gif" alt="'.get_lang('Attachment').'"/>');
  220. $group[] = $this->createElement('submit','add_resource',get_lang('Attachment'),'class="link_alike"');
  221. $this->addGroup($group);
  222. }
  223. /**
  224. * Adds a progress bar to the form.
  225. *
  226. * Once the user submits the form, a progress bar (animated gif) is
  227. * displayed. The progress bar will disappear once the page has been
  228. * reloaded.
  229. *
  230. * @param int $delay The number of seconds between the moment the user
  231. * submits the form and the start of the progress bar.
  232. */
  233. function add_progress_bar($delay = 2, $label='')
  234. {
  235. if(empty($label))
  236. {
  237. $label = get_lang('PleaseStandBy');
  238. }
  239. $this->with_progress_bar = true;
  240. $this->updateAttributes("onsubmit=\"myUpload.start('dynamic_div','".api_get_path(WEB_CODE_PATH)."img/progress_bar.gif','".$label."','".$this->getAttribute('id')."')\"");
  241. $this->addElement('html','<script language="javascript" src="'.api_get_path(WEB_CODE_PATH).'inc/lib/javascript/upload.js" type="text/javascript"></script>');
  242. $this->addElement('html','<script type="text/javascript">var myUpload = new upload('.(abs(intval($delay))*1000).');</script>');
  243. }
  244. /**
  245. * Use the new functions (php 5.2) allowing to display a real upload progress.
  246. * @param upload_id the value of the field UPLOAD_IDENTIFIER
  247. * @param elementAfter the first element of the form (to place at first UPLOAD_IDENTIFIER
  248. * @param delay the frequency of the xajax call
  249. * @param waitAfterUpload
  250. */
  251. function add_real_progress_bar($upload_id, $elementAfter, $delay=2,$waitAfterUpload=false)
  252. {
  253. if(!function_exists('uploadprogress_get_info'))
  254. {
  255. $this -> add_progress_bar($delay);
  256. return;
  257. }
  258. if(!class_exists('xajax')) {
  259. require_once api_get_path(LIBRARY_PATH).'xajax/xajax.inc.php';
  260. }
  261. $xajax_upload = new xajax(api_get_path(WEB_CODE_PATH).'inc/lib/upload.xajax.php');
  262. $xajax_upload -> registerFunction ('updateProgress');
  263. // IMPORTANT : must be the first element of the form
  264. $el = $this->insertElementBefore(FormValidator::createElement('html','<input type="hidden" name="UPLOAD_IDENTIFIER" value="'.$upload_id.'" />'), $elementAfter);
  265. $this->addElement('html','<br />');
  266. // add the div where the progress bar will be displayed
  267. $this->addElement('html','
  268. <div id="dynamic_div_container" style="display:none">
  269. <div id="dynamic_div_label">'.get_lang('UploadFile').'</div>
  270. <div id="dynamic_div_frame" style="width:214px; height:12px; border:1px solid grey; background-image:url('.api_get_path(REL_PATH).'main/img/real_upload_frame.gif);">
  271. <div id="dynamic_div_filled" style="width:0%;height:100%;background-image:url('.api_get_path(REL_PATH).'main/img/real_upload_step.gif);background-repeat:repeat-x;background-position:center;"></div>
  272. </div>
  273. </div>');
  274. if($waitAfterUpload){
  275. $this->addElement('html','
  276. <div id="dynamic_div_waiter_container" style="display:none">
  277. <div id="dynamic_div_waiter_label">
  278. '.get_lang('SlideshowConversion').'
  279. </div>
  280. <div id="dynamic_div_waiter_frame">
  281. <img src="'.api_get_path(WEB_CODE_PATH).'img/real_upload_frame.gif" />
  282. </div>
  283. </div>
  284. ');
  285. }
  286. // get the xajax code
  287. $this->addElement('html',$xajax_upload -> getJavascript(api_get_path(WEB_CODE_PATH).'inc/lib/xajax'));
  288. // get the upload code
  289. $this->addElement('html','<script language="javascript" src="'.api_get_path(WEB_CODE_PATH).'inc/lib/javascript/upload.js" type="text/javascript"></script>');
  290. $this->addElement('html','<script type="text/javascript">var myUpload = new upload('.(abs(intval($delay))*1000).');</script>');
  291. if(!$waitAfterUpload)
  292. {
  293. $waitAfterUpload = 0;
  294. }
  295. // add the upload event
  296. $this->updateAttributes("onsubmit=\"myUpload.startRealUpload('dynamic_div','".$upload_id."','".$this->getAttribute('id')."',".$waitAfterUpload.")\"");
  297. }
  298. /**
  299. * This function avoid to change directly QuickForm class.
  300. * When we use it, the element is threated as 'required' to be dealt during validation
  301. * @param array $element the array of elements
  302. * @param string $message the message displayed
  303. */
  304. function add_multiple_required_rule($elements, $message)
  305. {
  306. $this->_required[] = $elements[0];
  307. $this -> addRule ($elements , $message , 'multiple_required');
  308. }
  309. /**
  310. * Display the form.
  311. * If an element in the form didn't validate, an error message is showed
  312. * asking the user to complete the form.
  313. */
  314. function display()
  315. {
  316. echo $this->return_form();
  317. }
  318. /**
  319. * Returns the HTML code of the form.
  320. * If an element in the form didn't validate, an error message is showed
  321. * asking the user to complete the form.
  322. *
  323. * @return string $return_value HTML code of the form
  324. *
  325. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  326. * @version Dokeos 1.8, august 2006
  327. */
  328. function return_form()
  329. {
  330. $error = false;
  331. foreach($this->_elements as $index => $element)
  332. {
  333. if( !is_null(parent::getElementError($element->getName())) )
  334. {
  335. $error = true;
  336. break;
  337. }
  338. }
  339. if($error)
  340. {
  341. Display::display_error_message(get_lang('FormHasErrorsPleaseComplete'));
  342. }
  343. $return_value = parent::toHtml();
  344. // Add the div which will hold the progress bar
  345. if(isset($this->with_progress_bar) && $this->with_progress_bar)
  346. {
  347. $return_value .= '<div id="dynamic_div" style="display:block;margin-left:40%;margin-top:10px;height:50px;"></div>';
  348. }
  349. return $return_value;
  350. }
  351. }
  352. /**
  353. * Clean HTML
  354. * @param string HTML to clean
  355. * @param int $mode
  356. * @return string The cleaned HTML
  357. */
  358. function html_filter($html, $mode = NO_HTML)
  359. {
  360. require_once(dirname(__FILE__).'/Rule/HTML.php');
  361. $allowed_tags = HTML_QuickForm_Rule_HTML::get_allowed_tags($mode);
  362. $cleaned_html = kses($html,$allowed_tags);
  363. return $cleaned_html;
  364. }
  365. function html_filter_teacher($html)
  366. {
  367. return html_filter($html,TEACHER_HTML);
  368. }
  369. function html_filter_student($html)
  370. {
  371. return html_filter($html,STUDENT_HTML);
  372. }
  373. function html_filter_teacher_fullpage($html)
  374. {
  375. return html_filter($html,TEACHER_HTML_FULLPAGE);
  376. }
  377. function html_filter_student_fullpage($html)
  378. {
  379. return html_filter($html,STUDENT_HTML_FULLPAGE);
  380. }
  381. ?>