3 * A helper for constructing web forms
5 * @author Roland Haeder <webmaster@ship-simu.org>
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
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.
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.
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/>.
24 class WebFormHelper extends BaseHelper implements HelpableTemplate {
26 * Instance to the class which provides field values
28 private $valueInstance = null;
31 * Wether the form tag is opened (keep at false or else your forms will
34 private $formOpened = false;
39 private $formName = "";
42 * Wether the group is opened or not
44 private $groupOpened = false;
47 * Wether the sub group is opened or not
49 private $subGroupOpened = false;
52 * Name of the sub group
54 private $subGroupName = "";
57 * Wether form tag is enabled (default: true)
59 private $formEnabled = true;
62 const EXCEPTION_FORM_NAME_INVALID = 0x030;
63 const EXCEPTION_CLOSED_FORM = 0x031;
64 const EXCEPTION_OPENED_FORM = 0x032;
65 const EXCEPTION_UNEXPECTED_CLOSED_GROUP = 0x033;
68 * Protected constructor
72 protected function __construct () {
73 // Call parent constructor
74 parent::__construct(__CLASS__);
76 // Set part description
77 $this->setObjectDescription("Helper class for HTML forms");
79 // Create unique ID number
80 $this->generateUniqueId();
84 * Creates the helper class with the given template engine instance and form name
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 class
92 public final static function createWebFormHelper (CompileableTemplate $templateInstance, $formName, $formId = false, $withForm = true) {
94 $helperInstance = new WebFormHelper();
96 // Set template instance
97 $helperInstance->setTemplateInstance($templateInstance);
99 // Is the form id not set?
100 if ($formId === false) {
101 // Use form id from form name
106 $helperInstance->setFormName($formName);
107 // A form-less field may say "false" here...
108 if ($withForm === true) {
110 $helperInstance->addFormTag($formName, $formId);
113 $helperInstance->enableForm(false);
116 // Return the prepared instance
117 return $helperInstance;
121 * Pre-fetches field default values from the given registry key instance into this class
123 * @param $registryKey
125 * @throws NullPointerException If an instance from registry is null
127 public function prefetchFieldValues ($registryKey) {
128 // Get the required instance
129 $this->valueInstance = Registry::getRegistry()->getInstance($registryKey);
131 // Is the instance valid?
132 if (is_null($this->valueInstance)) {
133 // Throw an exception
134 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
139 * Add the form tag or close it an already opened form tag
141 * @param $formName Name of the form (default: false)
142 * @param $formId Id of the form (attribute "id"; default: false)
144 * @throws InvalidFormNameException If the form name is invalid (=false)
145 * @todo Add some unique PIN here to bypass problems with some browser and/or extensions
147 public function addFormTag ($formName = false, $formId = false) {
148 // When the form is not yet opened at least form name must be valid
149 if (($this->formOpened === false) && ($formName === false)) {
150 // Thrown an exception
151 throw new InvalidFormNameException ($this, self::EXCEPTION_FORM_NAME_INVALID);
154 // Close the form is default
155 $formContent = "</form>";
157 // Check wether we shall open or close the form
158 if (($this->formOpened === false) && ($this->formEnabled === true)) {
160 $formContent = sprintf("<form name=\"%s\" class=\"forms\" action=\"%s/%s\" method=\"%s\" target=\"%s\"",
162 $this->getConfigInstance()->readConfig('base_url'),
163 $this->getConfigInstance()->readConfig('form_action'),
164 $this->getConfigInstance()->readConfig('form_method'),
165 $this->getConfigInstance()->readConfig('form_target')
168 // Add form id as well
169 $formContent .= sprintf(" id=\"%s_form\"",
176 // Open the form and remeber the form name
177 $this->formOpened = true;
179 // Add the hidden field required to identify safely this form
180 $this->addInputHiddenField('form', $this->getFormName());
183 if ($this->groupOpened === true) {
184 // Then automatically close it here
185 $this->addFormGroup("", "");
189 $this->formOpened = false;
192 // Add it to the content
193 $this->addContent($formContent);
197 * Add a text input tag to the form or throw an exception if it is not yet
198 * opened. The field's name will be set as id.
200 * @param $fieldName Input field name
201 * @param $fieldValue Input default value (default: empty)
203 * @throws FormClosedException If the form is not yet opened
205 public function addInputTextField ($fieldName, $fieldValue = "") {
206 // Is the form opened?
207 if (($this->formOpened === false) && ($this->formEnabled === true)) {
208 // Throw an exception
209 throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
212 // Generate the content
213 $inputContent = sprintf("<input type=\"text\" class=\"textfield\" id=\"%s_field\" name=\"%s\" value=\"%s\" />",
219 // And add it maybe with a "li" tag
220 $this->addContent($inputContent);
224 * Add a text input tag to the form with pre-loaded default value
226 * @param $fieldName Input field name
229 public function addInputTextFieldWithDefault ($fieldName) {
230 // Get the value from instance
231 $fieldValue = $this->getField($fieldName);
232 //* DEBUG: */ echo __METHOD__.":".$fieldName."=".$fieldValue."<br />\n";
234 // Add the text field
235 $this->addInputTextField($fieldName, $fieldValue);
239 * Add a password input tag to the form or throw an exception if it is not
240 * yet opened. The field's name will be set as id.
242 * @param $fieldName Input field name
243 * @param $fieldValue Input default value (default: empty)
245 * @throws FormClosedException If the form is not yet opened
247 public function addInputPasswordField ($fieldName, $fieldValue = "") {
248 // Is the form opened?
249 if (($this->formOpened === false) && ($this->formEnabled === true)) {
250 // Throw an exception
251 throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
254 // Generate the content
255 $inputContent = sprintf("<input type=\"password\" class=\"password\" id=\"%s_field\" name=\"%s\" value=\"%s\" />",
262 $this->addContent($inputContent);
266 * Add a hidden input tag to the form or throw an exception if it is not
267 * yet opened. The field's name will be set as id.
269 * @param $fieldName Input field name
270 * @param $fieldValue Input default value (default: empty)
272 * @throws FormClosedException If the form is not yet opened
274 public function addInputHiddenField ($fieldName, $fieldValue = "") {
275 // Is the form opened?
276 if (($this->formOpened === false) && ($this->formEnabled === true)) {
277 // Throw an exception
278 throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
281 // Generate the content
282 $inputContent = sprintf("<input type=\"hidden\" name=\"%s\" value=\"%s\" />",
288 $this->addContent($inputContent);
292 * Add a hidden input tag to the form with pre-loaded default value
294 * @param $fieldName Input field name
297 public function addInputHiddenFieldWithDefault ($fieldName) {
298 // Get the value from instance
299 $fieldValue = $this->getField($fieldName);
300 //* DEBUG: */ echo __METHOD__.":".$fieldName."=".$fieldValue."<br />\n";
302 // Add the text field
303 $this->addInputHiddenField($fieldName, $fieldValue);
307 * Add a hidden input tag to the form with configuration value
309 * @param $fieldName Input field name
310 * @param $prefix Prefix for configuration without trailing _
313 public function addInputHiddenConfiguredField ($fieldName, $prefix) {
314 // Get the value from instance
315 $fieldValue = $this->getConfigInstance()->readConfig("{$prefix}_{$fieldName}");
316 //* DEBUG: */ echo __METHOD__.":".$fieldName."=".$fieldValue."<br />\n";
318 // Add the text field
319 $this->addInputHiddenField($fieldName, $fieldValue);
323 * Add a checkbox input tag to the form or throw an exception if it is not
324 * yet opened. The field's name will be set as id.
326 * @param $fieldName Input field name
327 * @param $fieldChecked Wether the field is checked (defaut: checked)
329 * @throws FormClosedException If the form is not yet opened
331 public function addInputCheckboxField ($fieldName, $fieldChecked = true) {
332 // Is the form opened?
333 if (($this->formOpened === false) && ($this->formEnabled === true)) {
334 // Throw an exception
335 throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
338 // Set wether the check box is checked...
339 $checked = " checked=\"checked\"";
340 if ($fieldChecked === false) $checked = " ";
342 // Generate the content
343 $inputContent = sprintf("<input type=\"checkbox\" name=\"%s\" class=\"checkbox\" id=\"%s_field\" value=\"1\"%s/>",
350 $this->addContent($inputContent);
354 * Add a reset input tag to the form or throw an exception if it is not
355 * yet opened. The field's name will be set as id.
357 * @param $buttonText Text displayed on the button
359 * @throws FormClosedException If the form is not yet opened
361 public function addInputResetButton ($buttonText) {
362 // Is the form opened?
363 if (($this->formOpened === false) && ($this->formEnabled === true)) {
364 // Throw an exception
365 throw new FormClosedException (array($this, "reset"), self::EXCEPTION_CLOSED_FORM);
368 // Generate the content
369 $inputContent = sprintf("<input type=\"reset\" class=\"reset_button\" id=\"%s_reset\" value=\"%s\" />",
370 $this->getFormName(),
375 $this->addContent($inputContent);
379 * Add a reset input tag to the form or throw an exception if it is not
380 * yet opened. The field's name will be set as id.
382 * @param $buttonText Text displayed on the button
384 * @throws FormClosedException If the form is not yet opened
386 public function addInputSubmitButton ($buttonText) {
387 // Is the form opened?
388 if (($this->formOpened === false) && ($this->formEnabled === true)) {
389 // Throw an exception
390 throw new FormClosedException (array($this, "submit"), self::EXCEPTION_CLOSED_FORM);
393 // Generate the content
394 $inputContent = sprintf("<input type=\"submit\" class=\"submit_button\" id=\"%s_submit\" name=\"%s_button\" value=\"%s\" />",
395 $this->getFormName(),
396 $this->getFormName(),
401 $this->addContent($inputContent);
405 * Add a form group or close an already opened and open a new one
407 * @param $groupName Name of the group
408 * @param $groupText Text including HTML to show above this group
410 * @throws FormClosedException If no form has been opened before
411 * @throws EmptyVariableException If $groupName is not set
413 public function addFormGroup ($groupName, $groupText) {
415 if (($this->formOpened === false) && ($this->formEnabled === true)) {
416 // Throw exception here
417 throw new FormClosedException(array($this, $groupName), self::EXCEPTION_CLOSED_FORM);
420 // At least the group name should be set
421 if ((empty($groupName)) && ($this->groupOpened === false)) {
422 // Throw exception here
423 throw new EmptyVariableException(array($this, 'groupName'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
426 // Initialize content with closing div by default
427 $content = " </div>\n</div><!-- Group - CLOSE //-->";
429 // Is this group opened?
430 if ($this->groupOpened === false) {
431 // Begin the div/span blocks
432 $content = sprintf("<!-- Group %s - OPEN //-->
433 <div class=\"group_box\" id=\"%s_group_box\">
434 <span class=\"group_text\" id=\"%s_group_text\">
437 <div class=\"group_field\" id=\"%s_group_field\">",
446 $this->addContent($content);
449 $this->groupOpened = true;
451 // Is a sub group opened?
452 if ($this->subGroupOpened === true) {
454 $this->addFormSubGroup("", "");
458 $this->addContent($content);
461 $this->groupOpened = false;
463 // All call it again if the group name is not empty
464 if (!empty($groupName)) {
465 $this->addFormGroup($groupName, $groupText);
471 * Add a form sub group or close an already opened and open a new one or
472 * throws an exception if no group has been opened before or if the sub
473 * group name is empty.
475 * @param $subGroupName Name of the group
476 * @param $subGroupText Text including HTML to show above this group
478 * @throws FormGroupClosedException If no group has been opened before
479 * @throws EmptyVariableException If $subGroupName is not set
481 public function addFormSubGroup ($subGroupName, $subGroupText) {
482 // Is a group opened?
483 if ($this->groupOpened === false) {
484 // Throw exception here
485 throw new FormGroupClosedException(array($this, $subGroupName), self::EXCEPTION_UNEXPECTED_CLOSED_GROUP);
488 // At least the sub group name should be set
489 if ((empty($subGroupName)) && ($this->subGroupOpened === false)) {
490 // Throw exception here
491 throw new EmptyVariableException(array($this, 'groupName'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
494 // Initialize content with closing div by default
495 $content = " </div>\n</div><!-- Sub group- CLOSE //-->";
497 // Is this group opened?
498 if ($this->subGroupOpened === false) {
499 // Begin the span block
500 $content = sprintf("<!-- Sub group %s - OPEN //-->
501 <div class=\"subgroup_box\" id=\"%s_subgroup_box\">
502 <span class=\"subgroup_text\" id=\"%s_subgroup_text\">
505 <div class=\"subgroup_field\" id=\"%s_subgroup_field\">",
514 $this->addContent($content);
516 // Switch the state and remeber the name
517 $this->subGroupOpened = true;
518 $this->subGroupName = $subGroupName;
521 $this->addContent($content);
524 $this->subGroupOpened = false;
526 // All call it again if sub group name is not empty
527 if (!empty($subGroupName)) {
528 $this->addFormSubGroup($subGroupName, $subGroupText);
534 * Add text surrounded by a span block when there is a group opened before
535 * or else by a div block.
537 * @param $fieldName Field name
538 * @param $fieldText Text for the field
540 * @throws FormClosedException If the form is not yet opened
542 public function addFieldText ($fieldName, $fieldText) {
543 // Is the form opened?
544 if (($this->formOpened === false) && ($this->formEnabled === true)) {
545 // Throw an exception
546 throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
549 // Set the block type
551 if ($this->groupOpened === true) $block = "span";
553 // Generate the content
554 $inputContent = sprintf(" <%s id=\"%s_text\">
564 $this->addContent($inputContent);
568 * Add text (notes) surrounded by a div block. Still opened groups or sub
569 * groups will be automatically closed.
571 * @param $formNotes The form notes we shell addd
573 * @throws FormClosedException If the form is not yet opened
575 public function addFormNote ($formNotes) {
576 // Is the form opened?
577 if (($this->formOpened === false) && ($this->formEnabled === true)) {
578 // Throw an exception
579 throw new FormClosedException (array($this, "form_notes"), self::EXCEPTION_CLOSED_FORM);
583 if ($this->groupOpened === true) {
584 // Then automatically close it here
585 $this->addFormGroup("", "");
588 // Generate the content
589 $inputContent = sprintf(" <div id=\"form_note\">
596 $this->addContent($inputContent);
600 * Checks wether the registration requires a valid email address
602 * @return $required Wether the email address is required
604 public function ifRegisterRequiresEmailVerification () {
605 $required = ($this->getConfigInstance()->readConfig('register_requires_email') == "Y");
610 * Checks wether profile data shall be asked
612 * @return $required Wether profile shall be asked
614 public function ifRegisterIncludesProfile () {
615 $required = ($this->getConfigInstance()->readConfig('register_includes_profile') == "Y");
620 * Checks wether personal data shall be asked
622 * @return $required Wether personal data shall be asked
624 public function ifRegisterIncludesPersonaData () {
625 $required = ($this->getConfigInstance()->readConfig('register_personal_data') == "Y");
630 * Checks wether email addresses can only be once used
634 public function ifEmailMustBeUnique () {
635 $isUnique = ($this->getConfigInstance()->readConfig('register_email_unique') == "Y");
640 * Checks wether the specified chat protocol is enabled in this form
642 * @return $required Wether the specified chat protocol is enabled
644 public function ifChatEnabled ($chatProtocol) {
645 $required = ($this->getConfigInstance()->readConfig(sprintf("chat_enabled_%s", $chatProtocol)) == "Y");
650 * Checks wether login is enabled or disabled
652 * @return $isEnabled Wether the login is enabled or disabled
654 public function ifLoginIsEnabled () {
655 $isEnabled = ($this->getConfigInstance()->readConfig('login_enabled') == "Y");
660 * Checks wether login shall be done by username
662 * @return $isEnabled Wether the login shall be done by username
664 public function ifLoginWithUsername () {
665 $isEnabled = ($this->getConfigInstance()->readConfig('login_type') == "username");
670 * Checks wether login shall be done by email
672 * @return $isEnabled Wether the login shall be done by email
674 public function ifLoginWithEmail () {
675 $isEnabled = ($this->getConfigInstance()->readConfig('login_type') == "email");
680 * Checks wether guest login is allowed
682 * @return $isAllowed Wether guest login is allowed
684 public function ifGuestLoginAllowed () {
685 $isAllowed = ($this->getConfigInstance()->readConfig('guest_login_allowed') == "Y");
690 * Checks wether the email address change must be confirmed
692 * @return $requireConfirm Wether email change must be confirmed
694 public function ifEmailChangeRequireConfirmation () {
695 $requireConfirm = ($this->getConfigInstance()->readConfig('email_change_confirmation') == "Y");
696 return $requireConfirm;
700 * Checks wether the rules has been updated
702 * @return $rulesUpdated Wether rules has been updated
703 * @todo Implement check if rules have been changed
705 public function ifRulesHaveChanged () {
710 * Checks wether email change is allowed
712 * @return $emailChange Wether changing email address is allowed
714 public function ifEmailChangeAllowed () {
715 $emailChange = ($this->getConfigInstance()->readConfig('email_change_allowed') == "Y");
720 * Checks wether the user account is unconfirmed
722 * @return $isUnconfirmed Wether the user account is unconfirmed
724 public function ifUserAccountUnconfirmed () {
725 $isUnconfirmed = ($this->getField('user_status') === $this->getConfigInstance()->readConfig('user_status_unconfirmed'));
726 return $isUnconfirmed;
730 * Checks wether the user account is locked
732 * @return $isUnconfirmed Wether the user account is locked
734 public function ifUserAccountLocked () {
735 $isUnconfirmed = ($this->getField('user_status') === $this->getConfigInstance()->readConfig('user_status_locked'));
736 return $isUnconfirmed;
740 * Checks wether the user account is a guest
742 * @return $isUnconfirmed Wether the user account is a guest
744 public function ifUserAccountGuest () {
745 $isUnconfirmed = ($this->getField('user_status') === $this->getConfigInstance()->readConfig('user_status_guest'));
746 return $isUnconfirmed;
750 * Checks wether this form is secured by a CAPTCHA
752 * @return $isSecured Wether this form is secured by a CAPTCHA
754 public function ifFormSecuredWithCaptcha () {
755 $isSecured = ($this->getConfigInstance()->readConfig($this->getFormName()."_captcha_secured") == "Y");
760 * Flushs the content out (not yet secured against open forms, etc.!) or
761 * close the form automatically
764 * @throws FormOpenedException If the form is still open
766 public function flushContent () {
767 // Is the form still open?
768 if (($this->formOpened === true) && ($this->formEnabled === true)) {
769 // Close the form automatically
773 // Send content to template engine
774 $this->getTemplateInstance()->assignVariable($this->getFormName(), $this->getContent());
778 * Getter for direct field values
780 * @param $fieldName Name of the field we shall fetch
781 * @return $fieldValue Value from field
783 public function getField ($fieldName) {
784 // Get the field value
785 $fieldValue = call_user_func_array(array($this->valueInstance, 'getField'), array($fieldName));
792 * Adds a pre-configured CAPTCHA
796 public function addCaptcha () {
797 // Get last executed pre filter
798 $extraInstance = Registry::getRegistry()->getInstance('extra');
800 // Get a configured instance
801 $captchaInstance = ObjectFactory::createObjectByConfiguredName($this->getFormName()."_captcha", array($this->getTemplateInstance(), $extraInstance));
803 // Initiate the CAPTCHA
804 $captchaInstance->initiateCaptcha();
806 // Render the CAPTCHA code
807 $captchaInstance->renderCode();
809 // Get the content and add it to the helper
810 $this->addContent($captchaInstance->getContent());
814 * Enables/disables the form tag usage
816 * @param $formEnabled Wether form is enabled or disabled
819 public final function enableForm ($formEnabled = true) {
820 $this->formEnabled = (bool) $formEnabled;
824 * Setter for form name
826 * @param $formName Name of this form
829 public final function setFormName ($formName) {
830 $this->formName = (string) $formName;
834 * Getter for form name
836 * @return $formName Name of this form
838 public final function getFormName () {
839 return $this->formName;