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