Conflicting getField() in BaseHelper vs. BaseFrameworkSystem fixed
[shipsimu.git] / inc / classes / main / helper / web / forms / class_WebFormHelper.php
1 <?php
2 /**
3  * A helper for constructing web forms
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, this is free software
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.ship-simu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program. If not, see <http://www.gnu.org/licenses/>.
23  */
24 class WebFormHelper extends BaseWebHelper implements HelpableTemplate {
25         /**
26          * Wether the form tag is opened (keep at false or else your forms will
27          * never work!)
28          */
29         private $formOpened = false;
30
31         /**
32          * Name of the form
33          */
34         private $formName = "";
35
36         /**
37          * Wether the group is opened or not
38          */
39         private $groupOpened = false;
40
41         /**
42          * Wether the sub group is opened or not
43          */
44         private $subGroupOpened = false;
45
46         /**
47          * Name of the group
48          */
49         private $groupName = "";
50
51         /**
52          * Name of the sub group
53          */
54         private $subGroupName = "";
55
56         /**
57          * Wether form tag is enabled (default: true)
58          */
59         private $formEnabled = true;
60
61         // Class Constants
62         const EXCEPTION_FORM_NAME_INVALID       = 0x120;
63         const EXCEPTION_CLOSED_FORM             = 0x121;
64         const EXCEPTION_OPENED_FORM             = 0x122;
65         const EXCEPTION_UNEXPECTED_CLOSED_GROUP = 0x123;
66
67         /**
68          * Protected constructor
69          *
70          * @return      void
71          */
72         protected function __construct () {
73                 // Call parent constructor
74                 parent::__construct(__CLASS__);
75
76                 // Set part description
77                 $this->setObjectDescription("Helper class for HTML forms");
78
79                 // Create unique ID number
80                 $this->generateUniqueId();
81         }
82
83         /**
84          * Creates the helper class with the given template engine instance and form name
85          *
86          * @param       $templateInstance       An instance of a valid template engine
87          * @param       $formName                       Name of the form
88          * @param       $formId                         Value for "id" attribute (default: $formName)
89          * @param       $withForm                       Wether include the form tag
90          * @return      $helperInstance         A preparedf instance of this helper
91          */
92         public final static function createWebFormHelper (CompileableTemplate $templateInstance, $formName, $formId = false, $withForm = true) {
93                 // Get new instance
94                 $helperInstance = new WebFormHelper();
95
96                 // Set template instance
97                 $helperInstance->setTemplateInstance($templateInstance);
98
99                 // Is the form id not set?
100                 if ($formId === false) {
101                         // Use form id from form name
102                         $formId = $formName;
103                 } // END - if
104
105                 // Set form name
106                 $helperInstance->setFormName($formName);
107                 // A form-less field may say "false" here...
108                 if ($withForm === true) {
109                         // Create the form
110                         $helperInstance->addFormTag($formName, $formId);
111                 } else {
112                         // Disable form
113                         $helperInstance->enableForm(false);
114                 }
115
116                 // Return the prepared instance
117                 return $helperInstance;
118         }
119
120         /**
121          * Add the form tag or close it an already opened form tag
122          *
123          * @param       $formName       Name of the form (default: false)
124          * @param       $formId         Id of the form (attribute "id"; default: false)
125          * @return      void
126          * @throws      InvalidFormNameException        If the form name is invalid (=false)
127          * @todo        Add some unique PIN here to bypass problems with some browser and/or extensions
128          */
129         public function addFormTag ($formName = false, $formId = false) {
130                 // When the form is not yet opened at least form name must be valid
131                 if (($this->formOpened === false) && ($formName === false)) {
132                         // Thrown an exception
133                         throw new InvalidFormNameException ($this, self::EXCEPTION_FORM_NAME_INVALID);
134                 } // END - if
135
136                 // Close the form is default
137                 $formContent = "</form>";
138
139                 // Check wether we shall open or close the form
140                 if (($this->formOpened === false) && ($this->formEnabled === true)) {
141                         // Add HTML code
142                         $formContent = sprintf("<form name=\"%s\" class=\"forms\" action=\"%s/%s\" method=\"%s\" target=\"%s\"",
143                                 $formName,
144                                 $this->getConfigInstance()->readConfig('base_url'),
145                                 $this->getConfigInstance()->readConfig('form_action'),
146                                 $this->getConfigInstance()->readConfig('form_method'),
147                                 $this->getConfigInstance()->readConfig('form_target')
148                         );
149
150                         // Add form id as well
151                         $formContent .= sprintf(" id=\"%s_form\"",
152                                 $formId
153                         );
154
155                         // Add close bracket
156                         $formContent .= ">";
157
158                         // Open the form and remeber the form name
159                         $this->formOpened = true;
160                 } else {
161                         // Add the hidden field required to identify safely this form
162                         $this->addInputHiddenField('form', $this->getFormName());
163
164                         // Is a group open?
165                         if ($this->groupOpened === true) {
166                                 // Then automatically close it here
167                                 $this->addFormGroup();
168                         } // END - if
169
170                         // Simply close it
171                         $this->formOpened = false;
172                 }
173
174                 // Add it to the content
175                 $this->addContent($formContent);
176         }
177
178         /**
179          * Add a text input tag to the form or throw an exception if it is not yet
180          * opened. The field's name will be set as id.
181          *
182          * @param       $fieldName              Input field name
183          * @param       $fieldValue             Input default value (default: empty)
184          * @return      void
185          * @throws      FormClosedException             If the form is not yet opened
186          */
187         public function addInputTextField ($fieldName, $fieldValue = "") {
188                 // Is the form opened?
189                 if (($this->formOpened === false) && ($this->formEnabled === true)) {
190                         // Throw an exception
191                         throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
192                 } // END - if
193
194                 // Generate the content
195                 $inputContent = sprintf("<input type=\"text\" class=\"textfield %s_field\" name=\"%s\" value=\"%s\" />",
196                         $fieldName,
197                         $fieldName,
198                         $fieldValue
199                 );
200
201                 // And add it maybe with a "li" tag
202                 $this->addContent($inputContent);
203         }
204
205         /**
206          * Add a text input tag to the form with pre-loaded default value
207          *
208          * @param       $fieldName      Input field name
209          * @return      void
210          */
211         public function addInputTextFieldWithDefault ($fieldName) {
212                 // Get the value from instance
213                 $fieldValue = $this->getValueField($fieldName);
214                 //* DEBUG: */ echo __METHOD__.":".$fieldName."=".$fieldValue."<br />\n";
215
216                 // Add the text field
217                 $this->addInputTextField($fieldName, $fieldValue);
218         }
219
220         /**
221          * Add a password input tag to the form or throw an exception if it is not
222          * yet opened. The field's name will be set as id.
223          *
224          * @param       $fieldName                      Input field name
225          * @param       $fieldValue                     Input default value (default: empty)
226          * @return      void
227          * @throws      FormClosedException             If the form is not yet opened
228          */
229         public function addInputPasswordField ($fieldName, $fieldValue = "") {
230                 // Is the form opened?
231                 if (($this->formOpened === false) && ($this->formEnabled === true)) {
232                         // Throw an exception
233                         throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
234                 } // END - if
235
236                 // Generate the content
237                 $inputContent = sprintf("<input type=\"password\" class=\"password %s_field\" name=\"%s\" value=\"%s\" />",
238                         $fieldName,
239                         $fieldName,
240                         $fieldValue
241                 );
242
243                 // And add it
244                 $this->addContent($inputContent);
245         }
246
247         /**
248          * Add a hidden input tag to the form or throw an exception if it is not
249          * yet opened. The field's name will be set as id.
250          *
251          * @param       $fieldName                      Input field name
252          * @param       $fieldValue                     Input default value (default: empty)
253          * @return      void
254          * @throws      FormClosedException             If the form is not yet opened
255          */
256         public function addInputHiddenField ($fieldName, $fieldValue = "") {
257                 // Is the form opened?
258                 if (($this->formOpened === false) && ($this->formEnabled === true)) {
259                         // Throw an exception
260                         throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
261                 } // END - if
262
263                 // Generate the content
264                 $inputContent = sprintf("<input type=\"hidden\" name=\"%s\" value=\"%s\" />",
265                         $fieldName,
266                         $fieldValue
267                 );
268
269                 // And add it
270                 $this->addContent($inputContent);
271         }
272
273         /**
274          * Add a hidden input tag to the form with pre-loaded default value
275          *
276          * @param       $fieldName      Input field name
277          * @return      void
278          */
279         public function addInputHiddenFieldWithDefault ($fieldName) {
280                 // Get the value from instance
281                 $fieldValue = $this->getValueField($fieldName);
282                 //* DEBUG: */ echo __METHOD__.":".$fieldName."=".$fieldValue."<br />\n";
283
284                 // Add the text field
285                 $this->addInputHiddenField($fieldName, $fieldValue);
286         }
287
288         /**
289          * Add a hidden input tag to the form with configuration value
290          *
291          * @param       $fieldName      Input field name
292          * @param       $prefix         Prefix for configuration without trailing _
293          * @return      void
294          */
295         public function addInputHiddenConfiguredField ($fieldName, $prefix) {
296                 // Get the value from instance
297                 $fieldValue = $this->getConfigInstance()->readConfig("{$prefix}_{$fieldName}");
298                 //* DEBUG: */ echo __METHOD__.":".$fieldName."=".$fieldValue."<br />\n";
299
300                 // Add the text field
301                 $this->addInputHiddenField($fieldName, $fieldValue);
302         }
303
304         /**
305          * Add a checkbox input tag to the form or throw an exception if it is not
306          * yet opened. The field's name will be set as id.
307          *
308          * @param       $fieldName                      Input field name
309          * @param       $fieldChecked           Wether the field is checked (defaut: checked)
310          * @return      void
311          * @throws      FormClosedException             If the form is not yet opened
312          */
313         public function addInputCheckboxField ($fieldName, $fieldChecked = true) {
314                 // Is the form opened?
315                 if (($this->formOpened === false) && ($this->formEnabled === true)) {
316                         // Throw an exception
317                         throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
318                 } // END - if
319
320                 // Set wether the check box is checked...
321                 $checked = " checked=\"checked\"";
322                 if ($fieldChecked === false) $checked = " ";
323
324                 // Generate the content
325                 $inputContent = sprintf("<input type=\"checkbox\" name=\"%s\" class=\"checkbox %s_field\" value=\"1\"%s/>",
326                         $fieldName,
327                         $fieldName,
328                         $checked
329                 );
330
331                 // And add it
332                 $this->addContent($inputContent);
333         }
334
335         /**
336          * Add a reset input tag to the form or throw an exception if it is not
337          * yet opened. The field's name will be set as id.
338          *
339          * @param       $buttonText             Text displayed on the button
340          * @return      void
341          * @throws      FormClosedException             If the form is not yet opened
342          */
343         public function addInputResetButton ($buttonText) {
344                 // Is the form opened?
345                 if (($this->formOpened === false) && ($this->formEnabled === true)) {
346                         // Throw an exception
347                         throw new FormClosedException (array($this, "reset"), self::EXCEPTION_CLOSED_FORM);
348                 } // END - if
349
350                 // Generate the content
351                 $inputContent = sprintf("<input type=\"reset\" class=\"reset_button\" id=\"%s_reset\" value=\"%s\" />",
352                         $this->getFormName(),
353                         $buttonText
354                 );
355
356                 // And add it
357                 $this->addContent($inputContent);
358         }
359
360         /**
361          * Add a reset input tag to the form or throw an exception if it is not
362          * yet opened. The field's name will be set as id.
363          *
364          * @param       $buttonText                     Text displayed on the button
365          * @return      void
366          * @throws      FormClosedException             If the form is not yet opened
367          */
368         public function addInputSubmitButton ($buttonText) {
369                 // Is the form opened?
370                 if (($this->formOpened === false) && ($this->formEnabled === true)) {
371                         // Throw an exception
372                         throw new FormClosedException (array($this, "submit"), self::EXCEPTION_CLOSED_FORM);
373                 } // END - if
374
375                 // Generate the content
376                 $inputContent = sprintf("<input type=\"submit\" class=\"submit_button\" id=\"%s_submit\" name=\"%s_button\" value=\"%s\" />",
377                         $this->getFormName(),
378                         $this->getFormName(),
379                         $buttonText
380                 );
381
382                 // And add it
383                 $this->addContent($inputContent);
384         }
385
386         /**
387          * Add a form group or close an already opened and open a new one
388          *
389          * @param       $groupName      Name of the group or last opened if empty
390          * @param       $groupText      Text including HTML to show above this group
391          * @return      void
392          * @throws      FormClosedException             If no form has been opened before
393          * @throws      EmptyVariableException  If $groupName is not set
394          */
395         public function addFormGroup ($groupName = "", $groupText = "") {
396                 // Is a form opened?
397                 if (($this->formOpened === false) && ($this->formEnabled === true)) {
398                         // Throw exception here
399                         throw new FormClosedException(array($this, $groupName), self::EXCEPTION_CLOSED_FORM);
400                 } // END - if
401
402                 // At least the group name should be set
403                 if ((empty($groupName)) && ($this->groupOpened === false)) {
404                         // Throw exception here
405                         throw new EmptyVariableException(array($this, 'groupName'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
406                 } elseif (empty($groupName)) {
407                         // Close the last opened
408                         $groupName = $this->groupName;
409                 }
410
411                 // Same group to open?
412                 if (($this->groupOpened === false) && ($groupName == $this->groupName)) {
413                         // Abort here silently
414                         return false;
415                 } // END - if
416
417                 // Initialize content with closing div by default
418                 $content = "    </div>\n</div><!-- Group - CLOSE //-->";
419
420                 // Is this group opened?
421                 if ($this->groupOpened === false) {
422                         // Begin the div/span blocks
423                         $content = sprintf("<!-- Group %s - OPEN //-->
424 <div class=\"group_box\" id=\"%s_group_box\">
425         <span class=\"group_text\" id=\"%s_group_text\">
426                 %s
427         </span>
428         <div class=\"group_field\" id=\"%s_group_field\">",
429                                 $groupName,
430                                 $groupName,
431                                 $groupName,
432                                 $groupText,
433                                 $groupName
434                         );
435
436                         // Add the content
437                         $this->addContent($content);
438
439                         // Switch the state
440                         $this->groupName = $groupName;
441                         $this->groupOpened = true;
442                 } else {
443                         // Is a sub group opened?
444                         if ($this->subGroupOpened === true) {
445                                 // Close it here
446                                 $this->addFormSubGroup();
447                         } // END - if
448
449                         // Add the content
450                         $this->addContent($content);
451
452                         // Switch the state
453                         $this->groupOpened = false;
454
455                         // All call it again if the group name is not empty
456                         if (!empty($groupName)) {
457                                 $this->addFormGroup($groupName, $groupText);
458                         } // END - if
459                 }
460         }
461
462         /**
463          * Add a form sub group or close an already opened and open a new one or
464          * throws an exception if no group has been opened before or if the sub
465          * group name is empty.
466          *
467          * @param       $subGroupName   Name of the group or last opened if empty
468          * @param       $subGroupText   Text including HTML to show above this group
469          * @return      void
470          * @throws      FormGroupClosedException        If no group has been opened before
471          * @throws      EmptyVariableException          If $subGroupName is not set
472          */
473         public function addFormSubGroup ($subGroupName = "", $subGroupText = "") {
474                 // Is a group opened?
475                 if ($this->groupOpened === false) {
476                         // Throw exception here
477                         throw new FormGroupClosedException(array($this, $subGroupName), self::EXCEPTION_UNEXPECTED_CLOSED_GROUP);
478                 } // END - if
479
480                 // At least the sub group name should be set
481                 if ((empty($subGroupName)) && ($this->subGroupOpened === false)) {
482                         // Throw exception here
483                         throw new EmptyVariableException(array($this, 'groupName'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
484                 } elseif (empty($subGroupName)) {
485                         // Close the last opened
486                         $subGroupName = $this->subGroupName;
487                 }
488
489                 // Same sub group to open?
490                 if (($this->subGroupOpened === false) && ($subGroupName == $this->subGroupName)) {
491                         // Abort here silently
492                         return false;
493                 } // END - if
494
495                 // Initialize content with closing div by default
496                 $content = "    </div>\n</div><!-- Sub group- CLOSE //-->";
497
498                 // Is this group opened?
499                 if ($this->subGroupOpened === false) {
500                         // Begin the span block
501                         $content = sprintf("<!-- Sub group %s - OPEN //-->
502 <div class=\"subgroup_box\" id=\"%s_subgroup_box\">
503         <span class=\"subgroup_text\" id=\"%s_subgroup_text\">
504                 %s
505         </span>
506         <div class=\"subgroup_field\" id=\"%s_subgroup_field\">",
507                                 $subGroupName,
508                                 $subGroupName,
509                                 $subGroupName,
510                                 $subGroupText,
511                                 $subGroupName
512                         );
513
514                         // Add the content
515                         $this->addContent($content);
516
517                         // Switch the state and remeber the name
518                         $this->subGroupOpened = true;
519                         $this->subGroupName = $subGroupName;
520                 } else {
521                         // Add the content
522                         $this->addContent($content);
523
524                         // Switch the state
525                         $this->subGroupOpened = false;
526
527                         // All call it again if sub group name is not empty
528                         if (!empty($subGroupName)) {
529                                 $this->addFormSubGroup($subGroupName, $subGroupText);
530                         } // END - if
531                 }
532         }
533
534         /**
535          * Add text surrounded by a span block when there is a group opened before
536          * or else by a div block.
537          *
538          * @param       $fieldName                      Field name
539          * @param       $fieldText                      Text for the field
540          * @return      void
541          * @throws      FormClosedException             If the form is not yet opened
542          */
543         public function addFieldText ($fieldName, $fieldText) {
544                 // Is the form opened?
545                 if (($this->formOpened === false) && ($this->formEnabled === true)) {
546                         // Throw an exception
547                         throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
548                 } // END - if
549
550                 // Set the block type
551                 $block = "div";
552                 if ($this->groupOpened === true) $block = "span";
553
554                 // Generate the content
555                 $inputContent = sprintf("       <%s id=\"%s_text\">
556                 %s
557         </%s>",
558                         $block,
559                         $fieldName,
560                         $fieldText,
561                         $block
562                 );
563
564                 // And add it
565                 $this->addContent($inputContent);
566         }
567
568         /**
569          * Add text (notes) surrounded by a div block. Still opened groups or sub
570          * groups will be automatically closed.
571          *
572          * @param       $noteId         Id for this note
573          * @param       $formNotes      The form notes we shell addd
574          * @return      void
575          * @throws      FormClosedException             If the form is not yet opened
576          */
577         public function addFormNote ($noteId, $formNotes) {
578                 // Is the form opened?
579                 if (($this->formOpened === false) && ($this->formEnabled === true)) {
580                         // Throw an exception
581                         throw new FormClosedException (array($this, "form_notes"), self::EXCEPTION_CLOSED_FORM);
582                 } // END - if
583
584                 // Is a group open?
585                 if ($this->groupOpened === true) {
586                         // Then automatically close it here
587                         $this->addFormGroup();
588                 } // END - if
589
590                 // Generate the content
591                 $inputContent = sprintf("       <div id=\"form_note_%s\">
592                 %s
593         </div>",
594                         $noteId,
595                         $formNotes
596                 );
597
598                 // And add it
599                 $this->addContent($inputContent);
600         }
601
602         /**
603          * Checks wether the registration requires a valid email address
604          *
605          * @return      $required       Wether the email address is required
606          */
607         public function ifRegisterRequiresEmailVerification () {
608                 $required = ($this->getConfigInstance()->readConfig('register_requires_email') === "Y");
609                 return $required;
610         }
611
612         /**
613          * Checks wether profile data shall be asked
614          *
615          * @return      $required       Wether profile shall be asked
616          */
617         public function ifRegisterIncludesProfile () {
618                 $required = ($this->getConfigInstance()->readConfig('register_includes_profile') === "Y");
619                 return $required;
620         }
621
622         /**
623          * Adds a pre-configured CAPTCHA
624          *
625          * @return      void
626          */
627         public function addCaptcha () {
628                 // Get last executed pre filter
629                 $extraInstance = Registry::getRegistry()->getInstance('extra');
630
631                 // Get a configured instance
632                 $captchaInstance = ObjectFactory::createObjectByConfiguredName($this->getFormName()."_captcha", array($this, $extraInstance));
633
634                 // Initiate the CAPTCHA
635                 $captchaInstance->initiateCaptcha();
636
637                 // Render the CAPTCHA code
638                 $captchaInstance->renderCode();
639
640                 // Get the content and add it to the helper
641                 $this->addContent($captchaInstance->getContent());
642         }
643
644         /**
645          * Enables/disables the form tag usage
646          *
647          * @param       $formEnabled    Wether form is enabled or disabled
648          * @return      void
649          */
650         public final function enableForm ($formEnabled = true) {
651                 $this->formEnabled = (bool) $formEnabled;
652         }
653
654         /**
655          * Setter for form name
656          *
657          * @param       $formName       Name of this form
658          * @return      void
659          */
660         public final function setFormName ($formName) {
661                 $this->formName = (string) $formName;
662         }
663
664         /**
665          * Getter for form name
666          *
667          * @return      $formName       Name of this form
668          */
669         public final function getFormName () {
670                 return $this->formName;
671         }
672
673         /**
674          * Checks wether this form is secured by a CAPTCHA
675          *
676          * @return      $isSecured      Wether this form is secured by a CAPTCHA
677          */
678         public function ifFormSecuredWithCaptcha () {
679                 $isSecured = ($this->getConfigInstance()->readConfig($this->getFormName().'_captcha_secured') === "Y");
680                 return $isSecured;
681         }
682
683         /**
684          * Flushs the content out (not yet secured against open forms, etc.!) or
685          * close the form automatically
686          *
687          * @return      void
688          * @throws      FormOpenedException             If the form is still open
689          */
690         public function flushContent () {
691                 // Is the form still open?
692                 if (($this->formOpened === true) && ($this->formEnabled === true)) {
693                         // Close the form automatically
694                         $this->addFormTag();
695                 } elseif ($this->formEnabled === false) {
696                         if ($this->subGroupOpened === true) {
697                                 // Close sub group
698                                 $this->addFormSubGroup();
699                         } elseif ($this->groupOpened === true) {
700                                 // Close group
701                                 $this->addFormGroup();
702                         }
703                 }
704
705                 // Send content to template engine
706                 //* DEBUG: */ echo __METHOD__.": form=".$this->getFormName().", size=".strlen($this->getContent())."<br />\n";
707                 $this->getTemplateInstance()->assignVariable($this->getFormName(), $this->getContent());
708         }
709 }
710
711 // [EOF]
712 ?>