<?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');

/**
 * Manage IOformat of LSldapObject import/export
 *
 * @property-read bool $update_only
 * @author Benjamin Renard <brenard@easter-eggs.com>
 */
class LSioFormat extends LSlog_staticLoggerClass {

  /**
   * LSobject type name
   * @var string
   */
  var $LSobject;

  /**
   * ioFormat name
   * @var string
   */
  var $name;

  /**
   * Configuration of the IOformat
   * (LSobjects.<type>.ioFormat.<name>)
   * @see LSioFormat::__construct()
   * @see LSioFormat::getConfig()
   * @see LSioFormat::ready()
   * @var array|false
   */
  var $config = false;

  /**
   * The related LSioFormatDriver object
   * @see LSioFormat::__construct()
   * @see LSioFormat::ready()
   * @var LSioFormatDriver|false
   */
  var $driver = false;

  /**
   * Constructor
   *
   * @param string $LSobject The LSobject type name
   * @param string $ioFormat The ioFormat name
   *
   * @return void
   **/
  public function __construct($LSobject, $ioFormat) {
    $this -> LSobject = $LSobject;
    $this -> name = $ioFormat;
    $conf = LSconfig::get('LSobjects.'.$LSobject.".ioFormat.".$ioFormat);
    if(is_array($conf)) {
      $this -> config = $conf;
      $driver = $this -> getConfig('driver');
      if ($driver && LSsession :: loadLSclass('LSioFormat'.$driver)) {
        $driverClass = "LSioFormat".$driver;
        $driverOptions = $this -> getConfig('driver_options', array(), 'array');
        $this -> driver = new $driverClass($driverOptions);
      }
      else {
        LSerror :: addErrorCode('LSioFormat_01', $driver);
      }
    }
  }

  /**
   * Access to infos of the ioFormat
   *
   * @param string $key The name of the value
   *
   * @return mixed The value
   **/
  public function __get($key) {
    switch($key) {
      case 'update_only':
        return $this -> getConfig('update_only', false, 'bool');
    }
    // Unknown key, log warning
    self :: log_warning("__get($key): invalid property requested\n".LSlog :: get_debug_backtrace_context());
  }

  /**
   * Check if ioFormat driver is ready
   *
   * @return boolean True if ioFormat driver is ready, false otherwise
   **/
  public function ready() {
    return (is_array($this -> config) && $this -> driver !== False);
  }

  /**
   * Return a configuration 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 configuration parameter value or default value if not set
   **/
  public function getConfig($param, $default=null, $cast=null) {
    return LSconfig :: get($param, $default, $cast, (is_array($this -> config)?$this -> config:array()));
  }

  /**
   * Load and valid file
   *
   * @param string $file The file path to load
   *
   * @return boolean True if file is loaded and valid, false otherwise
   **/
  public function loadFile($file) {
    if ($this -> driver -> loadFile($file)) {
      return $this -> driver -> isValid();
    }
    return False;
  }

  /**
   * Retrieve all objects contained by the loaded file
   *
   * @return array The objects contained by the loaded file
   **/
  public function getAll() {
    return $this -> driver -> getAllFormated(
      $this -> getConfig('fields', array(), 'array'),
      $this -> getConfig('generated_fields', array(), 'array')
    );
  }

  /**
   * Export objects
   *
   * @param array<LSldapObject> $objects The objects to export
   * @param resource|null $stream The output stream (optional, default: STDOUT)
   *
   * @return boolean True on success, False otherwise
   */
  public function exportObjects(&$objects, $stream=null) {
    self :: log_trace('exportObjects(): start');
    $fields = $this -> getConfig('fields');
    if (!$fields) {
      self :: log_error('exportObjects(): No field configured !');
      return false;
    }
    if (!LSsession :: loadLSclass('LSform', null, true))
      return false;

    $objects_data = array();
    foreach($objects as $object) {
      $dn = $object -> getDn();
      $objects_data[$dn] = array();

      // Build a LSform object
      $export = new LSform($object, 'export');

      // Add attributes to export and put their values to data to export
      foreach($fields as $key => $attr_name) {
        $objects_data[$dn][$key] = null;
        if ($attr_name == 'dn') {
          $objects_data[$dn][$key] = $dn;
        }
        else if (!isset($object -> attrs[$attr_name])) {
          self :: log_warning("exportObjects($object): attribute '$attr_name' does not exist !");
          continue;
        }
        else {
          $object -> attrs[$attr_name] -> addToExport($export);
          if (!isset($export -> elements[$attr_name])) {
            // @phpstan-ignore-next-line
            self :: log_debug("exportObjects($object): attribute '$attr_name' not added to export : may be user can't read it");
            continue;
          }
          $objects_data[$dn][$key] = $export -> elements[$attr_name] -> getApiValue(false);
        }
      }
    }
    self :: log_trace('exportObjects(): objects data = '.varDump($objects_data));
    return $this -> driver -> exportObjectsData($objects_data, $stream);
  }

  /**
   * Trigger action to run to specified event
   *
   * @param string $event The event name
   * @param string $evenData The event context data (optional, default: null)
   *
   * @return boolean True on success, False otherwise
   */
  public function fireEvent($event, $evenData=null) {
    self :: log_debug(strval($this)." -> fireEvent($event)");
    $return = true;
    if(isset($this -> config[$event])) {
      foreach(ensureIsArray($this -> config[$event]) as $func) {
        if(is_callable($func)) {
          self :: log_debug(strval($this)." -> fireEvent($event): run ".format_callable($func));
          if(!call_user_func_array($func, array(&$this, &$evenData))) {
            $return = false;
          }
        }
        else {
          self :: log_warning(strval($this)." -> fireEvent($event): function '".format_callable($func)."' doesn't exists.");
          $return = false;
        }
      }
    }
    else
      self :: log_trace(strval($this)." -> fireEvent($event): no configured trigger for this event.");
    return $return;
  }

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

}

LSerror :: defineError('LSioFormat_01',
___("LSioFormat : IOformat driver %{driver} invalid or unavailable.")
);
