=====Advanced Form Open===== //Installed as a [[WikkaBetaFeatures beta feature]] on this server as of 2005-06-12.// >>See also: ~-WikkaCore ~-GenerateUniqueId ~-Mod015fFilesAction ~-EmailpasswordActionInfo ~-AdvancedReferrersHandler ~-GrabCodeHandler >>The [[Docs:WikkaCore 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 1.1.6.0. release version ~-''modified to make use of the new ##[[GenerateUniqueId makeId()]]## method'' ~-''modified to use lowercase form method values (required by XHTML)'' %%(php;694) /** * Build an opening form tag with specified or generated attributes. * * This method builds an opening form tag, taking care that the result is valid XHTML * no matter where the parameters come from: invalid parameters are ignored and defaults used. * This enables this method to be used with user-provided parameter values. * * The form will always have the required action attribute and an id attribute to provide * a 'hook' for styling and scripting. This method tries its best to ensure the id attribute * is unique, among other things by adding a 'form_' prefix to make it different from ids for * other elements. * For a file upload form ($file=TRUE) the appropriate method and enctype attributes are generated. * * When rewriting is not active, a hidden field is attached as well to pass on the page name. * NOTE: is this really needed?? * * @author {@link http://wikka.jsnx.com/JavaWoman JavaWoman} * @copyright Copyright © 2005, Marjolein Katsma * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License * * @access public * @uses makeId() * @uses ID_LENGTH * @uses existsHandler() * @uses existsPage() * @uses Href() * @uses MiniHref() * * @param string $method optional: "method" which consists of handler and possibly a query string * to be used as part of action attribute * @param string $tag optional: page name to be used for action attribute; * if not specified, the current page will be used * @param string $formMethod optional: method attribute; must be POST (default) or GET; * anything but POST is ignored and considered as GET; * always converted to lowercase * @param string $id optional: id attribute * @param string $class optional: class attribute * @param boolean $file optional: specifies whether there will be a file upload field; * default: FALSE; if TRUE sets method attribute to POST and generates * appropriate enctype attribute * @return string opening form tag and hidden input field when not rewriting. */ function FormOpen($method='',$tag='',$formMethod='post',$id='',$class='',$file=FALSE) { $attrMethod = ''; # no method for HTML default 'get' $attrClass = ''; $attrEnctype = ''; # default no enctype -> HTML default application/x-www-form-urlencoded $hiddenval = ''; // validations $validMethod = $this->existsHandler($method); $validPage = $this->existsPage($tag); // derivations (MiniHref supplies current page name if none specified) $page = ($validPage) ? $tag : ''; $method = ($validMethod) ? $method : ''; // form action (action is a required attribute!) $attrAction = ' action="'.$this->Href($method, $page).'"'; // form method (ignore anything but post) and enctype if (TRUE === $file) { $attrMethod = ' method="post"'; # required for file upload $attrEnctype = ' enctype="multipart/form-data"'; # required for file upload } elseif (preg_match('/^post$/i',$formMethod)) # ignore case... { $attrMethod = ' method="post"'; # ...but generate lowercase } // form id if ('' == $id) # if no id given, generate one based on other parameters { $id = substr(md5($method.$tag.$formMethod.$class),0,ID_LENGTH); } $attrId = ' id="'.$this->makeId('form',$id).'"'; # make sure we have a unique id // form class if ('' != $class) { $attrClass = ' class="'.$class.'"'; } // build HTML fragment $result = ''."\n"; if (!$this->config['rewrite_mode']) # @@@ is this bit really necessary? { $hiddenval = $this->MiniHref($method, $page); $result .= ''."\n"; } return $result; } %% ====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 [[GenerateUniqueId 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 [[GenerateUniqueId 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: %%(php) /** * 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 http://wikka.jsnx.com/JavaWoman JavaWoman} * @copyright Copyright © 2005, Marjolein Katsma * @license http://www.gnu.org/copyleft/lesser.html 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')) { $this->_initSystem(); } // 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; break; } } 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: %%(php) /** * 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 http://wikka.jsnx.com/JavaWoman JavaWoman} * @copyright Copyright © 2004, Marjolein Katsma * @license http://www.gnu.org/copyleft/lesser.html 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 } } closedir($dh); // return result return $aDirList; # only return final result } %% ==Naming== 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: %%(php) /** * Initialize constants (pseudo class constants). * * Constants for system-dependent values like separators are derived here. * * @author {@link http://wikka.jsnx.com/JavaWoman JavaWoman} * @copyright Copyright © 2005, Marjolein Katsma * @license http://www.gnu.org/copyleft/lesser.html 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. ==Naming== As with ##""_recurseDirs()""##, the _ prefix signals a private method. ====Advantages==== This new ##""FormOpen()""## method will solve a number of existing problems in current released and beta code. ==Released (1.1.6.0)== ~-The [[Mod015fFilesAction {{files}}]] action no longer needs to construct its file upload form itself: ##""FormOpen()""## now generates the necessary ##enctype## if told it's to be used for file upload. ~-The [[Docs:EmailpasswordActionInfo email password]] action can now use ##""FormOpen()""## (and ##""FormClose()""##) to generate a valid form (it isn't valid now!). ==Beta features== ~-The ##referrers.php## and ##review_blacklist.php## files files will no longer need to surround the filter form with a ##div## just to be able to define an id for a styling 'hook': the (same) id can now be defined on the form itself. See AdvancedReferrersHandler. ~-The [[GrabCodeHandler Grab code]] handler can now specify a class for the "grab" button form so they can be properly styled (and avoid the current inline styling that can't do it all without being able to style the form itself). ==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. ==Exception== There is one exception: the [[Docs:GoogleFormActionInfo 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. --JavaWoman ~& How about supporting JS form validation using the onSubmit event? I know you still have to do it server side, but sometimes it's just a bit more convenient for the user if he knows right away that something is wrong. On my site, I require the edit note field to be filled in, and I wrote a quick hack for it because I didn't want to hardcode the form into edit.php. It's based on the //old// ""FormOpen"" method (and I didn't give too much thought to the directories), but the basic idea is like this: ~&%%(php) function ValidFormOpen($method = "", $tag = "", $formMethod = "post") { $result = "
Href($method, $tag)."\" method=\"".$formMethod."\" onSubmit=\"return isFormValid(this);\">\n"; $result .= ''."\n"; if (!$this->config["rewrite_mode"]) $result .= "MiniHref($method, $tag)."\" />\n"; return $result; } %% ~&--CyneBeald ---- CategoryDevelopmentCore