]> git.mxchange.org Git - shipsimu.git/blob - inc/classes/main/helper/web/forms/class_WebFormHelper.php
generateUniqueId() and more useless/deprecated methods removed, code speed-up, link...
[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                         // Switch the state
421                         $this->closePreviousGroupByContent($content);
422
423                         // All call it again if the group name is not empty
424                         if (!empty($groupId)) {
425                                 $this->addFormGroup($groupId, $groupText);
426                         } // END - if
427                 }
428         }
429
430         /**
431          * Add a form sub group or close an already opened and open a new one or
432          * throws an exception if no group has been opened before or if the sub
433          * group name is empty.
434          *
435          * @param       $subGroupId             Name of the group or last opened if empty
436          * @param       $subGroupText   Text including HTML to show above this group
437          * @return      void
438          * @throws      FormFormClosedException         If no group has been opened before
439          * @throws      EmptyVariableException          If $subGroupId is not set
440          */
441         public function addFormSubGroup ($subGroupId = "", $subGroupText = "") {
442                 // Is a group opened?
443                 if (!$this->ifGroupOpenedPreviously()) {
444                         // Throw exception here
445                         throw new FormFormClosedException(array($this, $subGroupId), self::EXCEPTION_UNEXPECTED_CLOSED_GROUP);
446                 } // END - if
447
448                 // At least the sub group name should be set
449                 if ((empty($subGroupId)) && (!$this->ifSubGroupOpenedPreviously())) {
450                         // Throw exception here
451                         throw new EmptyVariableException(array($this, 'subGroupId'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
452                 } elseif (empty($subGroupId)) {
453                         // Close the last opened
454                         $subGroupId = $this->getSubGroupId();
455                 }
456
457                 // Same sub group to open?
458                 if ((!$this->ifSubGroupOpenedPreviously()) && ($subGroupId == $this->getSubGroupId())) {
459                         // Abort here silently
460                         return false;
461                 } // END - if
462
463                 // Initialize content with closing div by default
464                 $content = "    </div>\n</div><!-- Sub group- CLOSE //-->";
465
466                 // Is this group opened?
467                 if (!$this->ifSubGroupOpenedPreviously()) {
468                         // Begin the span block
469                         $content = sprintf("<!-- Sub group %s - OPEN //-->
470 <div class=\"subgroup_box\" id=\"%s_subgroup_box\">
471         <span class=\"subgroup_text\" id=\"%s_subgroup_text\">
472                 %s
473         </span>
474         <div class=\"subgroup_field\" id=\"%s_subgroup_field\">",
475                                 $subGroupId,
476                                 $subGroupId,
477                                 $subGroupId,
478                                 $subGroupText,
479                                 $subGroupId
480                         );
481
482                         // Switch the state and remeber the name
483                         $this->openSubGroupByIdContent($subGroupId, $content);
484                 } else {
485                         // Switch the state
486                         $this->closePreviousSubGroupByContent($content);
487
488                         // All call it again if sub group name is not empty
489                         if (!empty($subGroupId)) {
490                                 $this->addFormSubGroup($subGroupId, $subGroupText);
491                         } // END - if
492                 }
493         }
494
495         /**
496          * Add text surrounded by a span block when there is a group opened before
497          * or else by a div block.
498          *
499          * @param       $fieldName                      Field name
500          * @param       $fieldText                      Text for the field
501          * @return      void
502          * @throws      FormClosedException             If the form is not yet opened
503          */
504         public function addFieldText ($fieldName, $fieldText) {
505                 // Is the form opened?
506                 if (($this->formOpened === false) && ($this->formEnabled === true)) {
507                         // Throw an exception
508                         throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
509                 } // END - if
510
511                 // Set the block type
512                 $block = "div";
513                 if ($this->ifGroupOpenedPreviously()) $block = "span";
514
515                 // Generate the content
516                 $inputContent = sprintf("       <%s id=\"%s_text\">
517                 %s
518         </%s>",
519                         $block,
520                         $fieldName,
521                         $fieldText,
522                         $block
523                 );
524
525                 // And add it
526                 $this->addContent($inputContent);
527         }
528
529         /**
530          * Add text (notes) surrounded by a div block. Still opened groups or sub
531          * groups will be automatically closed.
532          *
533          * @param       $noteId         Id for this note
534          * @param       $formNotes      The form notes we shell addd
535          * @return      void
536          * @throws      FormClosedException             If the form is not yet opened
537          */
538         public function addFormNote ($noteId, $formNotes) {
539                 // Is the form opened?
540                 if (($this->formOpened === false) && ($this->formEnabled === true)) {
541                         // Throw an exception
542                         throw new FormClosedException (array($this, "form_notes"), self::EXCEPTION_CLOSED_FORM);
543                 } // END - if
544
545                 // Is a group open?
546                 if ($this->ifGroupOpenedPreviously()) {
547                         // Then automatically close it here
548                         $this->addFormGroup();
549                 } // END - if
550
551                 // Generate the content
552                 $inputContent = sprintf("       <div id=\"form_note_%s\">
553                 %s
554         </div>",
555                         $noteId,
556                         $formNotes
557                 );
558
559                 // And add it
560                 $this->addContent($inputContent);
561         }
562
563         /**
564          * Checks wether the registration requires a valid email address
565          *
566          * @return      $required       Wether the email address is required
567          */
568         public function ifRegisterRequiresEmailVerification () {
569                 $required = ($this->getConfigInstance()->readConfig('register_requires_email') === "Y");
570                 return $required;
571         }
572
573         /**
574          * Checks wether profile data shall be asked
575          *
576          * @return      $required       Wether profile shall be asked
577          */
578         public function ifRegisterIncludesProfile () {
579                 $required = ($this->getConfigInstance()->readConfig('register_includes_profile') === "Y");
580                 return $required;
581         }
582
583         /**
584          * Adds a pre-configured CAPTCHA
585          *
586          * @return      void
587          */
588         public function addCaptcha () {
589                 // Get last executed pre filter
590                 $extraInstance = Registry::getRegistry()->getInstance('extra');
591
592                 // Get a configured instance
593                 $captchaInstance = ObjectFactory::createObjectByConfiguredName($this->getFormName().'_captcha', array($this, $extraInstance));
594
595                 // Initiate the CAPTCHA
596                 $captchaInstance->initiateCaptcha();
597
598                 // Render the CAPTCHA code
599                 $captchaInstance->renderCode();
600
601                 // Get the content and add it to the helper
602                 $this->addContent($captchaInstance->getContent());
603         }
604
605         /**
606          * Enables/disables the form tag usage
607          *
608          * @param       $formEnabled    Wether form is enabled or disabled
609          * @return      void
610          */
611         public final function enableForm ($formEnabled = true) {
612                 $this->formEnabled = (bool) $formEnabled;
613         }
614
615         /**
616          * Setter for form name
617          *
618          * @param       $formName       Name of this form
619          * @return      void
620          */
621         public final function setFormName ($formName) {
622                 $this->formName = (string) $formName;
623         }
624
625         /**
626          * Getter for form name
627          *
628          * @return      $formName       Name of this form
629          */
630         public final function getFormName () {
631                 return $this->formName;
632         }
633
634         /**
635          * Checks wether this form is secured by a CAPTCHA
636          *
637          * @return      $isSecured      Wether this form is secured by a CAPTCHA
638          */
639         public function ifFormSecuredWithCaptcha () {
640                 $isSecured = ($this->getConfigInstance()->readConfig($this->getFormName().'_captcha_secured') === "Y");
641                 return $isSecured;
642         }
643
644         /**
645          * Flushs the content out (not yet secured against open forms, etc.!) or
646          * close the form automatically
647          *
648          * @return      void
649          * @throws      FormOpenedException             If the form is still open
650          */
651         public function flushContent () {
652                 // Is the form still open?
653                 if (($this->formOpened === true) && ($this->formEnabled === true)) {
654                         // Close the form automatically
655                         $this->addFormTag();
656                 } elseif ($this->formEnabled === false) {
657                         if ($this->ifSubGroupOpenedPreviously()) {
658                                 // Close sub group
659                                 $this->addFormSubGroup();
660                         } elseif ($this->ifGroupOpenedPreviously()) {
661                                 // Close group
662                                 $this->addFormGroup();
663                         }
664                 }
665
666                 // Send content to template engine
667                 //* DEBUG: */ echo __METHOD__.": form=".$this->getFormName().", size=".strlen($this->getContent())."<br />\n";
668                 $this->getTemplateInstance()->assignVariable($this->getFormName(), $this->getContent());
669         }
670 }
671
672 // [EOF]
673 ?>