<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4.0                                                      |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group                                |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license,       |
// | that is bundled with this package in the file LICENSE, and is        |
// | available at through the world-wide-web at                           |
// | http://www.php.net/license/2_02.txt.                                 |
// | If you did not receive a copy of the PHP license and are unable to   |
// | obtain it through the world-wide-web, please send a note to          |
// | license@php.net so we can mail you a copy immediately.               |
// +----------------------------------------------------------------------+
// | Authors: Alexey Borzov <borz_off@cs.msu.su>                          |
// |          Bertrand Mansion <bmansion@mamasam.com>                     |
// |          Thomas Schulz <ths@4bconsult.de>                            |
// +----------------------------------------------------------------------+
//
// $Id: SmartyStatic.php,v 1.3 2004/08/26 14:50:11 ths Exp $

require_once 'HTML/Quickform/Renderer/SmartyDynamic.php';

/**
 * A static renderer for HTML_QuickForm, makes an array of form content
 * useful for an Smarty template
 *
 * Based on old toArray() code and ITStatic renderer.
 *
 * The form array structure is the following:
 * Array (
 *  [frozen]       => whether the complete form is frozen'
 *  [javascript]   => javascript for client-side validation
 *  [attributes]   => attributes for <form> tag
 *  [hidden]       => html of all hidden elements
 *  [requirednote] => note about the required elements
 *  [errors] => Array
 *      (
 *          [1st_element_name] => Error for the 1st element
 *          ...
 *          [nth_element_name] => Error for the nth element
 *      )
 *
 *  [header] => Array
 *      (
 *          [1st_header_name] => Header text for the 1st header
 *          ...
 *          [nth_header_name] => Header text for the nth header
 *      )
 *
 *  [1st_element_name] => Array for the 1st element
 *  ...
 *  [nth_element_name] => Array for the nth element
 *
 * // where an element array has the form:
 *      (
 *          [name]      => element name
 *          [value]     => element value,
 *          [type]      => type of the element
 *          [frozen]    => whether element is frozen
 *          [label]     => label for the element
 *          [required]  => whether element is required
 * // if element is not a group:
 *          [html]      => HTML for the element
 * // if element is a group:
 *          [separator] => separator for group elements
 *          [1st_gitem_name] => Array for the 1st element in group
 *          ...
 *          [nth_gitem_name] => Array for the nth element in group
 *      )
 * )
 *
 * @access public
 */
class HTML_QuickForm_Renderer_SmartyStatic extends HTML_QuickForm_Renderer_SmartyDynamic
{
   /**
    * The Form instance
    * @var object
    */
    var $_form = null;

   /**
    * The Smarty template engine instance
    * @var object
    */
    var $_tpl = null;

   /**
    * a directory relatated to the current template dir for the
    * @var object
    */
    var $_tplSubdir = null;

   /**
    * Current element index
    * @var integer
    */
    var $_elementIdx = 0;

    /**
    * The current element index inside a group
    * @var integer
    */
    var $_groupElementIdx = 0;

   /**
    * How to handle the required tag for required fields
    * @var string
    * @see      setRequiredTemplate()
    */
    var $_requiredTpl = array();

   /**
    * How to handle error messages in form validation
    * @var string
    * @see      setErrorTemplate()
    */
    var $_errorTpl = array();

   /**
    * Constructor
    *
    * @access public
    */
    function HTML_QuickForm_Renderer_SmartyStatic(&$tpl, $tplSubdir='')
    {
        $this->HTML_QuickForm_Renderer_SmartyDynamic($tpl, $tplSubdir, true);

    } // end constructor

   /**
    * Called when visiting a header element
    *
    * @param    object     An HTML_QuickForm_header element being visited
    * @access   public
    * @return   void
    */
    function renderHeader(&$header)
    {
        if ($name = $header->getName()) {
            $this->_ary['header'][$name] = $header->toHtml();
        } else {
            $this->_ary['header'][$this->_sectionCount] = $header->toHtml();
        }
        $this->_currentSection = $this->_sectionCount++;
    } // end func renderHeader

   /**
    * Called when visiting a group, before processing any group elements
    *
    * @param    object     An HTML_QuickForm_group object being visited
    * @param    bool       Whether a group is required
    * @param    string     An error message associated with a group
    * @access   public
    * @return   void
    */
    function startGroup(&$group, $required, $error)
    {
        // make unnamed groups accessible
        if (0 === strpos($group->_name, 'qf_group_')) {
            foreach (array_keys($group->_elements) as $key) {
                $element =& $group->_elements[$key];
                if ($this->_form->_freezeAll) {
                    $element->freeze();
                }
                $elementName = $element->getName();
                $required    = ($this->_form->isElementRequired($elementName) && $this->_form->_freezeAll == false);
                $error       = $this->_form->getElementError($elementName);
                $this->renderElement($element, $required, $error);
            }

        } else {
            parent::startGroup($group, $required, $error);
            $this->_groupElementIdx = 1;
        }

    } // end func startGroup

   /**
    * Creates an array representing an element containing
    * the key for storing this
    *
    * @access private
    * @param  object    An HTML_QuickForm_element object
    * @param  bool      Whether an element is required
    * @param  string    Error associated with the element
    * @return array
    */
    function _elementToArray(&$element, $required, $error)
    {
        // TODO: braucht erst beim aufruf durch qfe gerendert werden

        // prevent double calls on generic elements
        if (empty($element->_renderedArray)) {

            $ret = parent::_elementToArray($element, $required, $error);

            if ('group' == $ret['type']) {
                $ret['html'] = $element->toHtml();
                // we don't need the elements, see the array structure
                unset($ret['elements']);
            }
            if ('list' == $ret['type'] or 'grid' == $ret['type']) {
                $ret['options'] = $element->_options;
            }
            
            // render label and element-html
            $this->_renderElementLabel($ret);
            $this->_renderElementHtml($ret);
            
            // create keys for elements grouped by native group or name
            if (strstr($ret['name'], '[') or $this->_currentGroup) {
                preg_match('/([^]]*)\\[([^]]*)\\]/', $ret['name'], $matches);
                if (isset($matches[1])) {
                    $sKeysSub = substr_replace($ret['name'], '', 0, strlen($matches[1]));
                    $sKeysSub = str_replace(
                        array('['  ,   ']', '[\'\']'),
                        array('[\'', '\']', '[]'    ),
                        $sKeysSub
                    );
                    $sKeys = '[\'' . $matches[1]  . '\']' . $sKeysSub;
                } else {
                    $sKeys = '[\'' . $ret['name'] . '\']';
                }
                // special handling for elements in native groups
                if ($this->_currentGroup) {
                    // skip unnamed group items unless radios: no name -> no static access
                    // identification: have the same key string as the parent group
                    if ($this->_currentGroup['keys'] == $sKeys and 'radio' != $ret['type']) {
                        return false;
                    }
                    // reduce string of keys by remove leading group keys
                    if (0 === strpos($sKeys, $this->_currentGroup['keys'])) {
                        $sKeys = substr_replace($sKeys, '', 0, strlen($this->_currentGroup['keys']));
                    }
                }
            // element without a name
            } elseif ($ret['name'] == '') {
                $sKeys = '[\'element_' . $this->_elementIdx . '\']';
            // other elements
            } else {
                $sKeys = '[\'' . $ret['name'] . '\']';
            }
            // for radios: add extra key from value
            if ('radio' == $ret['type'] and substr($sKeys, -2) != '[]') {
                $sKeys .= '[\'' . $ret['value'] . '\']';
            }
            $this->_elementIdx++;
            $ret['keys'] = $sKeys;
            $element->_renderedArray = $ret;

        }
        return $element->_renderedArray;

    } // end func _elementToArray

   /**
    * Stores an array representation of an element in the form array
    *
    * @access private
    * @param array  Array representation of an element
    * @return void
    */
    function _storeArray($elAry)
    {
        if ($elAry) {
            $sKeys = $elAry['keys'];
            unset($elAry['keys']);
            // where should we put this element...
            if (is_array($this->_currentGroup) && ('group' != $elAry['type'])) {
                $toEval = '$this->_currentGroup' . $sKeys . ' = $elAry;';
            } else {
                $toEval = '$this->_ary' . $sKeys . ' = $elAry;';
            }
            eval($toEval);
        }
        return;
    }

   /**
    * Render the Element Label
    *
    * This method is used to add additional Formating to Element labels 
    * like required notes, additional help, error messages...
    *
    * @param    array       The element array
    * @see      setLabelTemplate()
    * @access   private
    * @return   void
    */
    function _renderElementLabel(&$element)
    {
        $this->_tpl->assign('qfe', $element);
        $element['label'] = $this->_tpl->fetch($this->_labelTpl);
        $this->_tpl->clear_assign('qfe');
    }
    

   /**
    * Render the Element HTML
    *
    * This method is used to add additional Formating to Element HTML 
    * like required notes, additional help, error messages or former 
    * renderd label...
    *
    * @param    array       The element array
    * @see      setHtmlTemplate()
    * @access   private
    * @return   void
    */
    function _renderElementHtml(&$element)
    {
        $this->_tpl->assign('qfe', $element);
        $element['html'] = $this->_tpl->fetch($this->_htmlTpl);
        $this->_tpl->clear_assign('qfe');
    }

   /**
    * Sets the way an label is rendered
    *
    * template example:
    * -----------------
    * {if $qfe.error}
    *     <span class="error">{$qfe.error|translate}</span><br />
    * {/if}
    * {$qfe.html}
    * {if $qfe.label_note}
    *     <div class="notice">{$qfe.label_note|translate}</div>
    * {/if}
    *
    * @param    string      The required element template
    * @access   public
    * @return   void
    */
    function setLabelTemplate($template)
    {
        $this->_labelTpl = $this->_tplSubdir . $template;
    }

   /**
    * Sets the elements hatmle is rendered
    *
    * template example:
    * {$qfe.label}
    * {if $qfe.required}
    *     <span class="error">*</span>
    * {/if}
    *
    * @param    string      The element error template
    * @access   public
    * @return   void
    */
    function setHtmlTemplate($template)
    {
        $this->_htmlTpl = $this->_tplSubdir . $template;
    } // end func setErrorTemplate
}
?>