Advanced Form Open

Installed as a beta feature on this server as of 2005-06-12.

The Wikka core has a FormOpen() method that creates the opening tag for a form. However, it has a number of limitations, such as no way to specify an id and/or class attribute, and not supporting enctype needed for a file upload form. This leads to ugly workarounds and inconsistent (and sometimes invalid) code.

The following replacement for FormOpen() addresses these issues and makes sure the generated code is valid XHTML. It uses a number of new supporting methods that will be more generally useful as well.

New FormOpen() method

The folowing code should replace the FormOpen() method in wikka.php (at line 694 in the release version
  1.     /**
  2.      * Build an opening form tag with specified or generated attributes.
  3.      *
  4.      * This method builds an opening form tag, taking care that the result is valid XHTML
  5.      * no matter where the parameters come from: invalid parameters are ignored and defaults used.
  6.      * This enables this method to be used with user-provided parameter values.
  7.      *
  8.      * The form will always have the required action attribute and an id attribute to provide
  9.      * a 'hook' for styling and scripting. This method tries its best to ensure the id attribute
  10.      * is unique, among other things by adding a 'form_' prefix to make it different from ids for
  11.      * other elements.
  12.      * For a file upload form ($file=TRUE) the appropriate method and enctype attributes are generated.
  13.      *
  14.      * When rewriting is not active, a hidden field is attached as well to pass on the page name.
  15.      * NOTE: is this really needed??
  16.      *
  17.      * @author      {@link JavaWoman}
  18.      * @copyright   Copyright © 2005, Marjolein Katsma
  19.      * @license GNU Lesser General Public License
  20.      *
  21.      * @access  public
  22.      * @uses    makeId()
  23.      * @uses    ID_LENGTH
  24.      * @uses    existsHandler()
  25.      * @uses    existsPage()
  26.      * @uses    Href()
  27.      * @uses    MiniHref()
  28.      *
  29.      * @param   string  $method     optional: "method" which consists of handler and possibly a query string
  30.      *                              to be used as part of action attribute
  31.      * @param   string  $tag        optional: page name to be used for action attribute;
  32.      *                              if not specified, the current page will be used
  33.      * @param   string  $formMethod optional: method attribute; must be POST (default) or GET;
  34.      *                              anything but POST is ignored and considered as GET;
  35.      *                              always converted to lowercase
  36.      * @param   string  $id         optional: id attribute
  37.      * @param   string  $class      optional: class attribute
  38.      * @param   boolean $file       optional: specifies whether there will be a file upload field;
  39.      *                              default: FALSE; if TRUE sets method attribute to POST and generates
  40.      *                              appropriate enctype attribute
  41.      * @return  string opening form tag and hidden input field when not rewriting.
  42.      */
  43.     function FormOpen($method='',$tag='',$formMethod='post',$id='',$class='',$file=FALSE)
  44.     {
  45.         $attrMethod = '';                                               # no method for HTML default 'get'
  46.         $attrClass = '';
  47.         $attrEnctype = '';                                              # default no enctype -> HTML default application/x-www-form-urlencoded
  48.         $hiddenval = '';
  49.         // validations
  50.         $validMethod = $this->existsHandler($method);
  51.         $validPage = $this->existsPage($tag);
  52.         // derivations (MiniHref supplies current page name if none specified)
  53.         $page = ($validPage) ? $tag : '';
  54.         $method = ($validMethod) ? $method : '';
  56.         // form action (action is a required attribute!)
  57.         $attrAction = ' action="'.$this->Href($method, $page).'"';
  58.         // form method (ignore anything but post) and enctype
  59.         if (TRUE === $file)
  60.         {
  61.             $attrMethod  = ' method="post"';                            # required for file upload
  62.             $attrEnctype = ' enctype="multipart/form-data"';            # required for file upload
  63.         }
  64.         elseif (preg_match('/^post$/i',$formMethod))                    # ignore case...
  65.         {
  66.             $attrMethod = ' method="post"';                             # ...but generate lowercase
  67.         }
  68.         // form id
  69.         if ('' == $id)                                                  # if no id given, generate one based on other parameters
  70.         {
  71.             $id = substr(md5($method.$tag.$formMethod.$class),0,ID_LENGTH);
  72.         }
  73.         $attrId = ' id="'.$this->makeId('form',$id).'"';                # make sure we have a unique id
  74.         // form class
  75.         if ('' != $class)
  76.         {
  77.             $attrClass = ' class="'.$class.'"';
  78.         }
  80.         // build HTML fragment
  81.         $result = '<form'.$attrAction.$attrMethod.$attrEnctype.$attrId.$attrClass.'>'."\n";
  82.         if (!$this->config['rewrite_mode'])                             # @@@ is this bit really necessary?
  83.         {
  84.             $hiddenval = $this->MiniHref($method, $page);
  85.             $result .= '<fieldset class="hidden"><input type="hidden" name="wakka" value="'.$hiddenval.'" /></fieldset>'."\n";
  86.         }
  88.         return $result;
  89.     }

Supporting methods and other code

As can be seen (and is documented in the docblock) the new FormOpen() method uses two methods and a constant that don't exist yet in wikka.php.

New makeId() method

This method takes care of generating a valid and unique id. Since this has much wider application than just for FormOpen(), this has its own development page. See GenerateUniqueId for code and installation instructions.

ID_LENGTH constant

Since this constant is also required for the makeId() method, code and instructions for that can also be found on the makeId() development page - see the Supporting code section.

New existsHandler() method

This method parallels the existsPage() method: it checks whether a handler actually exists. It takes as input what in Wikka is called $method which can be a handler name followed by an (optional) query string; the method chops off the query string and goes looking in the configured handlers path whether a handler file by the specified name exists.

Insert in the //MISC section of wikka.php, right after the new makeId() method:
     * Check if a handler (specified after page name) really exists.
     * May be passed as handler plus query string; we'll need to look at handler only
     * so we strip off any querystring first.
     * @author      {@link JavaWoman}
     * @copyright   Copyright © 2005, Marjolein Katsma
     * @license GNU Lesser General Public License
     * @access  public
     * @uses    _recurseDirs()
     * @uses    DIRSEP
     * @param   string $method "method" which starts with name of handler to check existence of
     * @return  boolean TRUE if handler is found, FALSE otherwise

    function existsHandler($method)
        // initializations
        $exists = FALSE;
        // initialize class constants
        if (!defined('DIRSEP'))

        // first strip off any query string
        $parts = preg_split('/&/',$method,1);               # return only one part
        $handler = $parts[0];
        // then check if rest corresponds to a file in the /handlers tree
        $handlersdirtree = $this->_recurseDirs(realpath($this->config['handler_path']));
        foreach ($handlersdirtree as $dirpath)
            if (file_exists($dirpath.DIRSEP.$handler.'.php'))
                $exists = TRUE;
        return $exists;

More supporting code
This public method in turn uses two new private methods, _recurseDirs() and _initSystem().

New _recurseDirs() method

This recursive utility method will build a list of directory paths starting with a given (relative) directory name. This is handy for finding a file with a particular name when it is not known which subdirectory it might live in. We use it now to check for the existence of a handler by a particular name without assuming it is a "page" handler and must be in the page subdirectory (!) but it could also be used for a "smart include" where we store bits of include code categorized in a directory tree without needing to specify a full path for the include or endlessly extending the PHP include path.

Insert right after the existsHandler() method:
     * Build a list of all subdirectories off a specified base directory (including that "base").
     * The algorithm uses a recursive "depth first" algorithm to find all subdirectories.
     * @author      {@link JavaWoman}
     * @copyright   Copyright © 2004, Marjolein Katsma
     * @license GNU Lesser General Public License
     * @access  private
     * @uses    _recurseDirs() (recursion!)
     * @uses    DIRSEP
     * @todo    maybe allow a "breadth first" algorithm as well
     * @param   string  $dir  required: absolute path of the directory to search
     * @return  array   list of directories found (including the base directory as first element)

    function _recurseDirs($dir)
        // array to gather names while recursing
        static $aDirList = array();                                                 # static: gather results through recursion

        $aDirList[] = $dir;                                                         # add current dir to list
        $dh = opendir($dir);
        while (FALSE !== ($thing = readdir($dh)))
            $next = $dir.DIRSEP.$thing;
            if (is_dir($next) && '.' != $thing && '..' != $thing)
                $this->_recurseDirs($next);                                         # ignore return value here

        // return result
        return $aDirList;                                                           # only return final result

Note that because this is a private method, I've chosen to use a _ prefix for the method name - a common convention for naming private methods.

New _initSystem() method

Some things PHP may need to work with are actually platform-dependent. We'd like to treat them as "constants" but they need to be derived once. The _initSystem() method handles this: by checking whether one of the constants is defined already we can call this method only when needed.

Insert right after the _recurseDirs() method:
     * Initialize constants (pseudo class constants).
     * Constants for system-dependent values like separators are derived here.
     * @author      {@link JavaWoman}
     * @copyright   Copyright © 2005, Marjolein Katsma
     * @license GNU Lesser General Public License
     * @access  private

    function _initSystem()
        define('PATHSEP', PATH_SEPARATOR)# system-dependent include path separator
        define('DIRSEP', DIRECTORY_SEPARATOR)# system-dependent directory separator

As it is, this now only uses PHP built-in constants (providing a more convenient short form); it may later be extended with other platform-dependent values and maybe functions.

As with _recurseDirs(), the _ prefix signals a private method.


This new FormOpen() method will solve a number of existing problems in current released and beta code.

Released (

Beta features

User contributions
And, of course, user-contributed extensions can use the new method to easily generate valid and consistent forms that can be easily styled.

There is one exception: the google form action needs a form with an external action URI; that isn't handled by FormOpen() which generates forms only for the installed Wikka system. I think we can live with that. :)

Tests? Comments?

Tests (even harsh tests) and comments are very welcome.


There is one comment on this page. [Display comment]
Valid XHTML :: Valid CSS: :: Powered by WikkaWiki