<?php
/*******************************************************************************
 * Copyright (C) 2007 Easter-eggs
 * https://ldapsaisie.org
 *
 * Author: See AUTHORS file in top-level directory.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

******************************************************************************/

LSsession :: loadLSclass('LSlog_staticLoggerClass');

/**
 * Element d'un formulaire pour LdapSaisie
 *
 * Cette classe gère les éléments des formulaires.
 *
 * @author Benjamin Renard <brenard@easter-eggs.com>
 */

class LSformElement extends LSlog_staticLoggerClass {

  /**
   * The attribute name
   * @var string
   */
  var $name;

  /**
   * The attribute label
   * @see LSformElement::__construct()
   * @see LSformElement::getLabel()
   * @var string
   */
  var $label;

  /**
   * Attribute configuration (LSobjects.<type>.attrs.<attr_name>)
   * @see LSformElement::getParam()
   * @var array<string,mixed>
   */
  var $params;

  /**
   * Values of the element
   * @var array<mixed>
   */
  var $values = array();

  /**
   * Reference of the related LSform object
   * @var LSform
   */
  var $form = null;

  /**
   * Require telltale
   * @see LSformElement::setRequired()
   * @see LSformElement::isRequired()
   * @var bool
   */
  var $_required = false;

  /**
   * Freeze telltale (=read-only element)
   * @see LSformElement::freeze()
   * @see LSformElement::isFreeze()
   * @var bool
   */
  var $_freeze = false;

  /**
   * Reference to the related LSattr_html object
   * @var LSattr_html
   */
  var $attr_html;

  /**
   * The one-value template filename (=for one vaue of the form element)
   * Note: commonly overwrite in implementated classes
   * @var string
   */
  var $fieldTemplate = 'LSformElement_field.tpl';

  /**
   * The template filename (of the form complement element)
   * Note: may be overwrite in implementated classes
   * @var string
   */
  var $template = 'LSformElement.tpl';

  /**
   * Template variables passed to Smarty computing the form element template
   * Note: this variables are commonly added in implementated classes
   * @var array<string,mixed>
   */
  var $fetchVariables = array();

  /**
   * Constructor
   *
   * @author Benjamin Renard <brenard@easter-eggs.com>
   *
   * @param LSform &$form  The LSform parent object
   * @param string $name The name of the element
   * @param string $label The label of the element
   * @param array $params The parameters of the element
   * @param LSattr_html &$attr_html  The LSattr_html object of the corresponding attribute
   *
   * @return void
   */
  public function __construct(&$form, $name, $label, $params, &$attr_html){
    $this -> name = $name;
    $this -> label = $label;
    $this -> params = $params;
    $this -> form =& $form;
    $this -> attr_html =& $attr_html;
  }

  /**
   * Allow conversion of LSformElement to string
   *
   * @return string The string representation of the LSformElement
   */
  public function __toString() {
    return strval($this -> form)." -> <".get_class($this)." ".$this -> name.">";
  }

  /**
   * Définis la valeur de l'élément
   *
   * Cette méthode définis la valeur de l'élément
   *
   * @author Benjamin Renard <brenard@easter-eggs.com>
   *
   * @param string|array $data La futur valeur de l'élément
   *
   * @return boolean Retourne True
   */
  public function setValue($data) {
    $this -> values = ensureIsArray($data);
    return true;
  }

  /**
   * Définis la valeur de l'élément à partir des données
   * envoyées en POST du formulaire
   *
   * Cette méthode définis la valeur de l'élément à partir des données
   * envoyées en POST du formulaire.
   *
   * @author Benjamin Renard <brenard@easter-eggs.com>
   *
   * @param string|array $data La futur valeur de l'élément
   *
   * @return boolean Retourne True
   */
  public function setValueFromPostData($data) {
    $this -> values = ensureIsArray($data);
    self :: log_trace($this." -> setValueFromPostData(): input data=".varDump($data)." / values=".varDump($this -> values));
    return true;
  }

  /**
   * Exporte les valeurs de l'élément
   *
   * @return array Les valeurs de l'élement
   */
  public function exportValues(){
    return $this -> values;
  }

  /**
   * Ajoute une valeur à l'élément
   *
   * Cette méthode ajoute une valeur à l'élément
   *
   * @author Benjamin Renard <brenard@easter-eggs.com>
   *
   * @param string|array $data La futur valeur de l'élément
   *
   * @return void
   */
  public function addValue($data) {
    $this -> values = array_merge($this -> values, ensureIsArray($data));
  }

  /**
   * Test si l'élément est éditable
   *
   * Cette méthode test si l'élément est éditable
   *
   * @return boolean
   */
  public function isFreeze(){
    return $this -> _freeze;
  }

  /**
   * Freeze l'élément
   *
   * Rend l'élément non-editable
   *
   * @return void
   */
  public function freeze() {
    $this -> _freeze = true;
  }

  /**
   * Défini la propriété required de l'élément.
   *
   * param boolean $isRequired true si l'élément est requis, false sinon
   *
   * @return void
   */
  public function setRequired($isRequired=true) {
    $this -> _required = $isRequired;
  }

  /**
   * Test si l'élément est requis
   *
   * Cette méthode test si l'élément est requis
   *
   * @return boolean
   */
  public function isRequired(){
    return $this -> _required;
  }

  /**
   * Return label info of the element:
   *   array(
   *     'label' => 'The label',
   *     'required' => true|false,
   *     'help_info' => 'The help info of the element',
   *     'help_info_in_view' => true|false,
   *   )
   *
   * @return array The label info
   */
  public function getLabelInfos() {
    if ($this -> isRequired()) {
        $return['required']=true;
    }
    $return['label'] = $this -> getLabel();
    $help_infos = array();
    if ( $this -> getParam('displayAttrName', $this -> attr_html -> attribute -> ldapObject -> getConfig('displayAttrName', false, 'bool'), 'bool') ) {
      $help_infos[] = _("Attribute")." : ".$this -> name."\n";
    }
    if ($this -> getParam('help_info')) {
      $help_infos[] = __($this -> getParam('help_info'));
    }
    if (!empty($help_infos))
      $return['help_info'] = implode(' - ', $help_infos);
    $return['help_info_in_view'] = $this -> getParam('help_info_in_view', false, 'bool');

    return $return;
  }

  /**
   * Recupère la valeur de l'élement passée en POST
   *
   * Cette méthode vérifie la présence en POST de la valeur de l'élément et la récupère
   * pour la mettre dans le tableau passer en paramètre avec en clef le nom de l'élément
   *
   * @param array &$return Reference of the array for retrieved values
   * @param boolean $onlyIfPresent If true and data of this element is not present in POST data,
   *                                   just ignore it.
   *
   * @return boolean true si la valeur est présente en POST, false sinon
   */
  public function getPostData(&$return, $onlyIfPresent=false) {
    if($this -> isFreeze()) {
      return true;
    }
    $return[$this -> name] = self :: getData($_POST, $this -> name);
    if (!is_array($return[$this -> name])) {
      if ($onlyIfPresent) {
        self :: log_debug($this -> name.": not in POST data => ignore it");
        unset($return[$this -> name]);
      }
      else {
        $return[$this -> name] = array();
      }
    }
    return true;
  }

  /**
   * Retrieve the value of the element specified by its name ($name)
   * from POST data (provided as $post).
   *
   * @param array &$post Reference of the array for input POST data
   * @param string $name POST data element name
   *
   * @return mixed Array of POST data value if present, false otherwise
   */
  protected static function getData(&$post, $name) {
    if (isset($post[$name])) {
      $return = array();
      $post[$name] = ensureIsArray($post[$name]);
      foreach($post[$name] as $key => $val) {
        if (!is_empty($val)) {
          $return[$key] = $val;
        }
      }
      return $return;
    }
    return false;
  }

  /**
   * Retourne le label de l'élement
   *
   * Retourne $this -> label, ou $this -> params['label'], ou $this -> name
   *
   * @return string Le label de l'élément
   */
  public function getLabel() {
    if ($this -> label != "") {
      return __($this -> label);
    }
    return __($this -> getParam('label', $this -> name));
  }

  /**
   * Le champ est-il a valeur multiple
   *
   * @return boolean True si le champ est à valeur multiple, False sinon
   */
  public function isMultiple() {
    return $this -> getParam('multiple', false, 'bool');
  }

 /**
  * Return HTML code of the LSformElement based on its (smarty) template file
  *
  * @param string $template The template filename (optional, default: $this -> template)
  * @param array $variables Array of template variables to assign before template compilation (optional)
  *
  * @return string HTML code of the LSformElement
  */
  public function fetchTemplate($template=NULL,$variables=array()) {
    if (!$template) {
      $template = $this -> template;
    }
    return LSsession :: fetchTemplate(
      $template,
      array_merge_recursive(
        $variables,
        $this -> fetchVariables,
        array(
          'freeze' => $this -> isFreeze(),
          'multiple'=> $this -> isMultiple(),
          'value' => '',
          'values' => $this -> values,
          'attr_name' => $this -> name,
          'noValueTxt' => __($this -> getParam('no_value_label', 'No set value', 'string')),
          'fieldTemplate' => $this -> fieldTemplate,
          'fieldType' => get_class($this)
        )
      )
    );
  }

 /**
  * Return HTML code of an empty form field
  *
  * @param integer|null $value_idx The value index (optional, default: null == 0)
  *
  * @return string The HTML code of an empty field
  */
  public function getEmptyField($value_idx=null) {
    return $this -> fetchTemplate(
      $this -> fieldTemplate,
      array(
        'value_idx' => intval($value_idx),
      )
    );
  }

 /**
  * Return a parameter (or default value)
  *
  * @param string $param      The configuration parameter
  * @param mixed $default    The default value (default : null)
  * @param string $cast       Cast resulting value in specific type (default : disabled)
  *
  * @return mixed The parameter value or default value if not set
  **/
  public function getParam($param, $default=null, $cast=null) {
    return LSconfig :: get($param, $default, $cast, $this -> params);
  }

  /**
   * CLI autocompleter for form element attribute values
   *
   * @param array &$opts                      Array of avalaible autocomplete options
   * @param string $comp_word                 The (unquoted) command word to autocomplete
   * @param string $attr_value                The current attribute value in command word to
   *                                          autocomplete (optional, default: empty string)
   * @param string $multiple_value_delimiter  The multiple value delimiter
   *                                          (optional, default: "|")
   * @param string $quote_char                The quote character detected
   *                                          (optional, default: empty string)
   *
   * @return void
   */
  public function autocomplete_attr_values(&$opts, $comp_word, $attr_value="", $multiple_value_delimiter="|", $quote_char='') {
    return;
  }

  /**
   * CLI autocompleter helper to split form element attribute values
   *
   * @param string $attr_value               The current attribute value in command word
   *                                         to autocomplete
   *                                         (optional, default: empty string)
   * @param string $multiple_value_delimiter The multiple value delimiter
   *                                         (optional, default: "|")
   * @param array &$attr_values              Array that will contain splited attribute
   *                                         values without last-one
   * @param string &$last_attr_value         Array that will contain the last splited
   *                                         attribute value
   *
   * @return boolean True on success, False otherwise
   */
  protected function split_autocomplete_attr_values($attr_value, $multiple_value_delimiter, &$attr_values, &$last_attr_value) {
    $attr_values = explode($multiple_value_delimiter, $attr_value);
    if (count($attr_values) > 1 && !$this -> getParam('multiple', false, 'bool')) {
      self :: log_error("The attribute ".$this -> name." is not multivalued.");
      return false;
    }
    self :: log_debug("split_autocomplete_attr_values('$attr_value', '$multiple_value_delimiter'): values = '".implode("', '", $attr_values)."'");
    $last_attr_value = array_pop($attr_values);
    self :: log_debug("split_autocomplete_attr_values('$attr_value', '$multiple_value_delimiter'): last value = '$last_attr_value'");
    return true;
  }

  /**
   * CLI autocompleter helper to format and add form element attribute value option
   *
   * @param array &$opts Array of avalaible autocomplete options
   * @param array &$attr_values Array of splited attribute values without last-one
   * @param string $value The attribute value to add as option
   * @param string $multiple_value_delimiter The multiple value delimiter (optional, default: "|")
   * @param string $quote_char The quote character (optional, default: empty string)
   *
   * @return void
   */
  protected function add_autocomplete_attr_value_opts(&$opts, &$attr_values, $value, $multiple_value_delimiter='|', $quote_char='') {
    if (in_array($value, $attr_values)) {
      self :: log_debug("LSformElement :: autocomplete_opts(): '$value' already one of selected value, ignore it");
      return;
    }
    $opt = $this -> name . "=" .implode($multiple_value_delimiter, array_merge($attr_values, array($value)));
    self :: log_debug("LSformElement :: add_autocomplete_attr_value_opts(): option=$opt");
    if ($quote_char)
      $opt = LScli :: quote_word($opt, $quote_char);
    if (!in_array($opt, $opts))
      $opts[] = $opt;
  }

  /**
   * Retrieve value as return in API response
   *
   * @param boolean $details If true, returned values will contain details if this field
   *                         type support it (optional, default: false)
   *
   * @return mixed API value(s) or null/empty array if no value
   */
  public function getApiValue($details=false) {
    if (method_exists($this, 'parseValue')) {
      $values = array();
      foreach(ensureIsArray($this -> values) as $value) {
        $parsed_value = $this -> parseValue($value, $details);
        if ($parsed_value != false)
          $values[] = $parsed_value;
      }
    }
    else {
      $values = ensureIsArray($this -> values);
    }
    if ($this -> isMultiple())
      return $values;
    if (!$values)
      return null;
    return $values[0];
  }

  /**
   * Get display info of the form element
   *
   * @return array
   */
  public function getDisplay(){
    $return = $this -> getLabelInfos();
    $return['html'] = $this -> fetchTemplate();
    return $return;
  }
}
