<?php
/**
  @licence GPL 2005-2010  The osCSS developers - osCSS Open Source E-commerce
  @portion code Copyright (c) 2002 osCommerce
  @package osCSS-2 <www http://www.oscss.org>
  @version 2.1.0
  @date  19/11/10, 18:04
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @file driver.content.php
*/


/**
  @class content
  Control init et gestion des data product
*/
class content {

  //! @p object
  protected static $_instance;

  public static $modules;

  /**
  */
  protected function __construct($full) {
    global $languages_id;
    contentData::start();
    if($full) self::start_module();
  }

  protected static function start_module(){
    $pdm=contentModule::getInstance();
    self::$modules=$pdm->ret_modules();
  }

  public static function getInstance($full=false) {
    if(self::$_instance == null) self::$_instance = new self($full);
    return self::$_instance;
  }

  public static function resetInstance(){
    self::$_instance = null;
    return self::getInstance();
  }

  /**
    Module configuration
  */
  public function ret_modules(){ self::start_module(); return self::$modules;}


  /**
    Data function
  */
  public static function get_query($id='',$search='',$exclude='',$option=array()){ global $languages_id; return contentData::get_query($id,$search,$exclude,$option); }
  public static function get_item($id){ return contentData::get_item($id); }
  public static function get_content_cat($id){ return contentData::get_content_cat($id); }
  public static function get_content_path($id){ return contentData::get_content_path($id); }
  public static function get_content_in_cat($current_category_id=0, $exclude=''){ return contentData::get_content_in_cat($current_category_id=0, $exclude=''); }
  public static function get_cms_liste_byDate($max, $exclude){ return contentData::get_cms_liste_byDate($max, $exclude); }
}


/**
  @class productData
  Traitement sql des product
*/
class contentData
  extends DataStatmentFO
    implements Interfacedata{

  //! @p int
  public static $lg_id;
  //! @p obj res db
  public static $obj_language;
  //! @p array
  public static $cache=array();

  //! @p array
  public static $opt=array();

  //! @p array cache
  public static $array_data=array();

  //! @p string
  private static $where_query='';
  //! @p object
  protected static $_instance;

  /**
  */
  protected function __construct() {
    global $languages_id;
    self::start();
  }

  /**
  */
  public static function start($option=''){
    global $languages_id;
    self::$lg_id=(int)$languages_id;
    $DB=Database::getInstance();
    self::$obj_language = $DB->query("select code from " . TABLE_LANGUAGES . " where languages_id='" .self::$lg_id . "'");

    if(!empty($option) && is_array($option)) self::$opt=$option;

  }


  /**
    Mise en pile de toutes les element des page de cms
  */
  private static function add_cache($id){
    self::$cache[]=$id;
  }

  /**
    Appel et recup des element du cache
  */
  private static function in_cache(){
    return implode("," ,self::$cache);
  }

  /**
    Prepa donnée sortie
  */
  protected static function statment_query($content_query,$exclude='',$search=''){

    $display_lang=self::$obj_language->fetchAssoc();
    if (empty($exclude))$exclude=array();
    $tabl=$res=array();
    while ($content = $content_query->fetchAssoc()) {
      if (!in_array($content['name'],$exclude)) {
	$res=$content;
	$res['href']=tep_href_link(FILENAME_CONTENT,'content=' . $content['id'] . '&amp;language=' . $display_lang['code']);
	$res['key']=$content['name'];
	$res['original']=$content['text'];
	$res['images']=array();

	self::$array_data[$content['id']]=$tabl[$content['id']]=new objectInfo($res);
	self::$array_data[$content['id']]->text=self::parse_content($res['text'],$content['id']);
	self::add_cache($content['id']);
      }
    }

    if((count(self::$array_data)>0))
    foreach(self::$array_data as $k=>$content)
      if (!in_array($content->name,$exclude)) {
	if((!empty($search) && strstr($content->name,$search) !=false) || empty($search)) $tabl[$content->id]=$content;
      }

    return $tabl;
  }

  /**
    Ajout constrainte clause where
  */
  protected static function add_where_query($add){ self::$where_query .=' '.$add; }

  /**
  */
  protected static function reset_query() { self::$where_query=''; }

  /**
    Requeteur
  */
  protected static function cstr_query($orderby='', $limit='', $option=''){
    $query="SELECT content_title AS title, c.content_id AS id, c.content_name AS name, content_text AS text
	    FROM " . TABLE_CONTENT_DESCRIPTION . " cd, " . TABLE_CONTENT . " c,   " . TABLE_CONTENT_TO_CATEGORIES . " ctc, " . TABLE_CATEGORIES . " cat
	    WHERE cat.categories_id=ctc.categories_id and cat.categories_status='1'  AND c.content_status = '1' AND c.content_id = ctc.content_id AND cd.content_id = ctc.content_id AND cd.language_id = '" . self::$lg_id . "' " ;

    $query .=self::$where_query;
    $query .=' ORDER BY ' .(!tep_not_null($orderby)? ' c.sort_order, c.content_name ASC  ' : $orderby) ;
    $query .=' LIMIT '.(!tep_not_null($limit)? '1' : $limit) ;

    return $query;
  }

  /**
    Extract img et complete cache avec img extraites
  */
  private static function extract_img($id,$content,$pattern){
    $pattern = "#<img.+[^>]/>#i";
    preg_match_all($pattern, $content, $images);
    //! mise en cache
    self::$array_data[$id]->images=$images ;
  }

  /**
    Parse content texte
    Fucntion qui permet de prendre en charge des element contenu dans la description du cms.
  */
  private static function parse_content($content,$id){

    $pattern ="#<img (.+)[^>]/>#i";
    self::extract_img($id,$content,$pattern);

    $sortie=(isset(self::$opt['img']) && !_test_bool(self::$opt['img']))? preg_replace($pattern, '', $content) : $content;
    $sortie=(isset(self::$opt['more']) && _test_bool(self::$opt['more']))?  substr($sortie, 0, strpos($sortie,'<!-- pagebreak -->')) : $sortie;
    return $sortie;
  }




  public static function getInstance() {
    if(self::$_instance == null) self::$_instance = new self();
    return self::$_instance;
  }

  public static function resetInstance(){
    self::$_instance = null;
    return self::getInstance();
  }

  /**
    Function recuperation des page associé a une cat

    @author oscim <mail a@oscim.fr /><web http://www.oscim.fr /> -  OscssTeam
    @param
      @a int l'id de la categorie  courante ou null
      @a array tableau d'exclusion
  */
  public static function get_content_in_cat($current_category_id=0, $exclude='',$option=''){
    global $languages_id;
    self::start($option);
    self::reset_query();
    $DB=Database::getInstance();
    self::$lg_id=(int)$languages_id;
    self::add_where_query(" AND ctc.categories_id = '" . (int)$current_category_id . "' ");
    $content_query = $DB->query($sql=self::cstr_query('',25) );

    return self::statment_query($content_query,$exclude);
  }

  /**
    Appel item
    @param
      @a string content_name le nom du titre
      @a array tableau d'exclusion
  */
  public static function get_query($id='',$search='',$exclude='',$option=array()){
    global $languages_id;

    self::start($option);

    self::reset_query();
    $DB=Database::getInstance();
    self::$lg_id=(int)$languages_id;
    $search=tep_db_prepare_input($search);

    if (count(self::$cache)>0) self::add_where_query(' AND c.content_id NOT IN ('.self::in_cache().') ');
    //! soit id soit sherach name key
    self::add_where_query((tep_not_null($id) && is_numeric($id) ? " AND c.content_id = '" . $id . "' ": (!empty($search)?" AND content_name LIKE '%" . tep_db_input($search) . "%' ":'') ));

    $content_query = $DB->query($sql=self::cstr_query((string)@$option['orderby'],@$option['limit'],(array)@$option) );

    return self::statment_query($content_query,$exclude,$search);
  }

  /**
    Alias unique ID
  */
  public static function get_item($id){
    $db_list=self::get_query($id);

    if(is_numeric($id) && isset($db_list[(int)$id])){
      return $db_list[$id];
    }else{
      $db_list=self::get_query('',$id);
      foreach($db_list as $item)
	if((string)$id==(string)$item->name)return $item;
    }
    return false;
  }

  /**
    Function recuperation de la cat d'un content_id

    @author oscim <mail a@oscim.fr /><web http://www.oscim.fr /> -  OscssTeam
    @param
      @a int l'id de la cat
  */
  public static function get_content_cat($content_id){
    $DB=Database::getInstance();
    $cur = $DB->query("SELECT categories_id from " . TABLE_CONTENT_TO_CATEGORIES . " WHERE content_id='" . (int)$content_id . "'");
    if($cur->__get('numRows')) {
      $display = $cur->fetchAssoc();
      //! mise en cache
      self::$array_data[$content_id]->parent_id=$display['categories_id'];
      return $display['categories_id'];
    }
    else return false;
  }

  /**
    Construct a category path to the product
    @author oscim <mail a@oscim.fr /><web http://www.oscim.fr /> -  OscssTeam
    @param
      @a int l'id de la ressource
  */
  public static function get_content_path($content_id) {
    $cPath = '';

    $category_query = tep_db_query("select p2c.categories_id from " . TABLE_CONTENT . " p, " . TABLE_CONTENT_TO_CATEGORIES . " p2c where p.content_id = '" . (int)$content_id . "' and p.content_status = '1' and p.content_id = p2c.content_id limit 1");
    if (tep_db_num_rows($category_query)) {
      $category = tep_db_fetch_array($category_query);

      $categories = array();
      tep_get_parent_categories($categories, $category['categories_id']);

      $categories = array_reverse($categories);

      $cPath = implode('_', $categories);

      if (tep_not_null($cPath)) $cPath .= '_';
      $cPath .= $category['categories_id'];
    }

    return $cPath;
  }

  /**
    Recupere la liste des article cms triée par date

    @note Article Type News, not in Page_xxx
    @author oscim - <mail aurelien@oscim.fr> <www http://www.oscim.fr>
    @param
      @a int max le nombre d'item dans le tableau
      @a array tableau d'exclusion des id
    @return array
  */
  public static function get_cms_liste_byDate($max=10, $exclude='') {
    global $languages_id;

    self::start();
    self::reset_query();
    $DB=Database::getInstance();
    self::$lg_id=(int)$languages_id;
    self::add_where_query(" AND content_name NOT LIKE 'Page_%' ");
    $sql=self::cstr_query(" c.date_added DESC ", $max);
    $content_query = $DB->query($sql);

    return self::statment_query($content_query,$exclude);
  }

  /**
    Return balise img
  */
  public static function get_img($id, $img_num=0){
    if(is_array( self::$array_data[$id]->images[$img_num])&& isset( self::$array_data[$id]->images[$img_num][0]) )
      return (string)self::$array_data[$id]->images[$img_num][0];
  }

}



/**
  @class AbstractProduct
  @brief Force mise en forme via class absctarction des modules de produits
*/
abstract class AbstractContent {
    // Force la classe étendue à définir cette méthode
    abstract protected function display_view($pID,$class='');
    abstract protected function load_db_values($pID);
    abstract protected function get_header($action='');
    // méthode commune
//     public function printOut() { }
}



/**
  @class contentModule
  @brief Traitement des modules associé
*/
class contentModule
  extends AbstractAcaModule
    implements InterfaceAcaGene {

  protected static $_instance;

  /**
  */
  protected function __construct() {
    global $language, $page;
    $this->name=__CLASS__;
    $this->modules=array();

    foreach(parent::initialise_type('MODULE_CONTENT_INSTALLED',$this->name) as $class){
      $cl[$class]=new $class ();
      $list_mod[$class] = $cl[$class]->sort_order;
    }
    asort($list_mod);
    foreach($list_mod as $class=>$s){
      $this->modules[$class] =$cl[$class];
    }
    unset($cl);unset($list_mod);
    return $this->modules;
  }


  public static function getInstance() {
    if(self::$_instance == null) self::$_instance = new self();
    return self::$_instance;
  }

  public static function resetInstance(){
    self::$_instance = null;
    return self::getInstance();
  }

  public function display_view($ID,$class=''){return array();}

  /**
    Affiche module display_view mini

    @param
      @a int  cID le Id du customers
      @a string class le nom de la class appelé, ou vide pour toutes les class enfants
  */
  public function display_view_min($cID,$class=''){
    global  $page;
    if (!empty($class)) {
      if (isset($this->modules[$class]) && $this->modules[$class]->enabled and (method_exists($module, 'display_view_min' ))){
        $this->modules[$class]->load_db_values($cID);
        return $this->modules[$class]->display_view_min($cID);
      }
    } else {
       $c='';
      foreach ($this->modules as $key=>$module) {
        if (($module->enabled)  and (method_exists($module, 'display_view_min' ))) {
          $this->modules[$key]->load_db_values($cID);
          $c .=$this->modules[$key]->display_view_min($cID);
        }
      }
      return $c;
    }
  }
}

?>