<?php if (!defined('HTTP_SERVER')) die('You can not access this file directly!');
/**
  @licence GPL 2005-2011  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  28/01/11, 23:41
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @brief multiple class for content
*/


/**
  @class cms_content
*/
class cms_content
  implements ExtModPage, InterfaceModule, InterfacedTJsonS,  InterfacedInnerHtml {

  const FILENAME = FILENAME_CMS_CONTENT;

  public static $code;

  public static $action;

  public static $list=array();
  /**
    @param object
  */
  public static $modules;
  /**
    @param object
  */
  public static $cInfo;
  /**
    @param array
  */
  public static $languages;
  /**
    @param bool
  */
  public static $enabled_status;
  /**
    @param bool
  */
  public static $disabled_status;

  /**
    class constructor
  */
  public function __construct() {
    self::GetConf();
  }

  /**
    @brief Load , adjust and define var environement exe for module
	Is use in module and class abstract for init value config this module
  */
  public static function GetConf(){
    global $languages_id;

    self::$code=__CLASS__;

    self::$action=(isset($_REQUEST['action'])? $_REQUEST['action'] : 'listing' );

    /**
      @remarks not load if not first init
    */
    if(defined('JSONSTATMENT')) return;

    //! active datatable in ajax, precise les GET necessaire
    if(!defined('JSONSTATMENT'))define('JSONSTATMENT', 'mod=page&type='.self::$code);
    //! detail item in ajax
    if(!defined('AJAXSTATMENTDETAIL'))define('AJAXSTATMENTDETAIL', 'mod=page&type='.self::$code);

    self::$modules=new ACAcontent;
    self::$modules->set_image_handler();

    self::$languages = tep_get_languages();
  }


  public function check_action($actions){
    global $messageStack,$oscss;

    $DB=Database::getInstance();
    self::$action=$actions;


  $cID=(isset($_GET['cID'])? $_GET['cID'] :'' );

  self::$modules-> set_image_handler();
  self::$languages = tep_get_languages();

  $actions['action'] = self::$action;
  $actions['display_file']='';
  $actions['action_class']=(isset($_GET['action_class']))? $_GET['action_class'] : '';
  $actions['action_method']=(isset($_GET['action_method']))? $_GET['action_method'] : '';

// Ask categories modules if want to change the action
  $actions = self::$modules->check_action($actions);
  $action = $actions['action'];

    if(((self::$action == 'update')||(self::$action == 'insert'))&&(isset($_POST['edit_x'])||isset($_POST['edit_y']))) self::$action = 'edit';

    switch (self::$action) {
    /**
	OPERATION SQL
    */
      case 'setflag':
	if ( ($_GET['flag'] == '0') || ($_GET['flag'] == '1') ) {
	    if (isset($_GET['cID'])) {
		tep_cms_set_content_status($_GET['cID'], $_GET['flag']);
	    }
	}
	tep_redirect(tep_href_link(self::FILENAME) );
      break;
      case 'viewflag':
	if (isset($_GET['cID'])) {
	  if ($_GET['flag'] == '0') $DB->query($sql="update " . TABLE_CONTENT . " set content_hidden = '0' where content_id = '" . (int)$_GET['cID'] . "'");
	  elseif($_GET['flag'] == '1') $DB->query($sql="update " . TABLE_CONTENT . " set content_hidden = '1' where content_id = '" . (int)$_GET['cID'] . "'");
	}
	tep_redirect(tep_href_link(self::FILENAME, tep_get_all_get_params(array( 'cID','flag','action'),false)) );
      break;

      case 'insert':
      case 'update':
	$content_name = tep_db_prepare_input($_POST['content_name']);
	$content_text = tep_db_prepare_input($_POST['content_text']);
	$content_title = tep_db_prepare_input($_POST['content_title']);
	$current_category_id=(isset($_POST['cPath'])) ? tep_db_prepare_input($_POST['cPath']) : 0;

	$sql_data_array = array('content_name' => tep_db_prepare_input($content_name),
				'content_status' => tep_db_prepare_input($_POST['content_status']));

	if (self::$action == 'insert') {
	  $insert_sql_data = array('date_added' => 'now()');
	  $sql_data_array = array_merge($sql_data_array, $insert_sql_data);

	  self::$modules->load_post_values($_POST);
	  $sql_data_array = array_merge($sql_data_array, self::$modules->get_insert_table_content ());

	  $resobj=tep_db_perform(TABLE_CONTENT, $sql_data_array);

	  $content_id =$resobj->__get('insertId');

	} elseif (self::$action == 'update') {
	  $content_id = tep_db_prepare_input($_GET['cID']);

	  $update_sql_data = array('last_modified' => 'now()');
	  $sql_data_array = array_merge($sql_data_array, $update_sql_data);

	  self::$modules->load_post_values($_POST);
	  $sql_data_array = array_merge($sql_data_array, self::$modules->get_update_table_content ());


	  tep_db_perform(TABLE_CONTENT, $sql_data_array, 'update', "content_id = '" . (int)$content_id . "'");
	}

	$DB->query("delete from " . TABLE_CONTENT_TO_CATEGORIES . " where content_id='" . (int)$content_id . "' ");
	if(!isset($_POST['categories']) || !is_array($_POST['categories']))
	  $DB->query($sql="insert into " . TABLE_CONTENT_TO_CATEGORIES . " (content_id, categories_id) values ('" . (int)$content_id . "', '1')");
	else
	foreach($_POST['categories'] as $value)
	  $DB->query($sql="insert into " . TABLE_CONTENT_TO_CATEGORIES . " (content_id, categories_id) values ('" . (int)$content_id . "', '" . (int)$value. "')");


	for ($i=0, $n=sizeof(self::$languages); $i<$n; $i++) {

	  $language_id = self::$languages[$i]['id'];
	  $sql_data_array = array('content_text' => tep_db_prepare_input($content_text[$language_id]),
				  'content_title' => str_replace('&','&amp;',tep_db_prepare_input($content_title[$language_id])));

	  if (self::$action == 'insert') {
	      $insert_sql_data = array('content_id' => $content_id, 'language_id' => $language_id);
	      $sql_data_array = array_merge($sql_data_array, $insert_sql_data);

	      $sql_data_array = array_merge($sql_data_array, self::$modules->get_insert_table_content_description ($language_id));

	      tep_db_perform(TABLE_CONTENT_DESCRIPTION, $sql_data_array);

	  } elseif (self::$action == 'update') {
	      $sql_data_array = array_merge($sql_data_array, self::$modules->get_update_table_content_description ($language_id));

	      tep_db_perform(TABLE_CONTENT_DESCRIPTION, $sql_data_array, 'update', "content_id = '" . (int)$content_id . "' and language_id = '" . (int)$language_id . "'");
	  }
	}

	self::$modules->after_update ($content_id);

	if(isset($_POST['up_and_close']) ) tep_redirect(tep_href_link(self::FILENAME, tep_get_all_get_params(array( 'cID','flag','action'),false)) );
	else tep_redirect(tep_href_link(self::FILENAME, 'page=' . $_GET['page'] . '&cID=' . $content_id.'&action=edit'));
      break;


      case 'deleteconfirm':
	$content_id = tep_db_prepare_input($_GET['cID']);
	tep_remove_cms($content_id);

	tep_redirect(tep_href_link(self::FILENAME, tep_get_all_get_params(array( 'cID','flag','action'),false)));
      break;

    /**
		POST AFFICHAGE
    */
      case 'edit':
      case 'new':

	self::load_db_values($_GET['cID']);

	$oscss->_add_ext(BO_WISIWYG_SELECTED,'editeur/');
	for ($i=0, $n=sizeof(self::$languages); $i<$n; $i++) {
	  echo $oscss->_call(BO_WISIWYG_SELECTED,'_top','content_text[' . self::$languages[$i]['id'] . ']','600','400');
	}
      break;

      default:
	//! Entretient liens avec  categorie
	self::UpdateOrphelin();
    }



    return self::$action;
  }

  public function get_header(){
    if (self::$action == 'new' || self::$action == 'edit') self::$modules->get_header_js(self::$action);
  }


  /**
    @fn load_db_values($ID)
    @brief this load db value function
      This method construct static var $cInfo
    @param $ID integer id content  | 0
    @return $cInfo
  */
  public static function load_db_values($ID){
    global $language_id;
    $DB=Database::getInstance();

	$cID = tep_db_prepare_input($ID);

	if(in_array(self::$action ,array('edit' ,'delete', 'detail') ) ){
	  $content_query = $DB->query("select c.content_id, content_name, date_added, last_modified, content_status  from " . TABLE_CONTENT . " c  where c.content_id = '" . (int)$cID . "' ");
	   $cInfo_array = tep_db_fetch_array($content_query);
	  tep_db_free_result($content_query);

	  for ($i=0, $n=sizeof(self::$languages); $i<$n; $i++) {
	    $language_id = self::$languages[$i]['id'];
	    $content_query = $DB->query("select cd.content_text, cd.content_title from " . TABLE_CONTENT . " c, " . TABLE_CONTENT_DESCRIPTION . " cd where c.content_id = '" . (int)$cID . "' and c.content_id = cd.content_id and language_id='" . $language_id . "'");
	    $content = tep_db_fetch_array($content_query);
	     $cInfo_array['text'][$language_id] = $content['content_text'];
	     $cInfo_array['title'][$language_id] = $content['content_title'];
	    tep_db_free_result($content_query);
	  }

	  $cat_query = $DB->query("select categories_id  from " . TABLE_CONTENT_TO_CATEGORIES . " where content_id='" . (int)$cID . "' ");
	  while($cat_l = tep_db_fetch_array($cat_query)){ $cat_list[$cat_l['categories_id']]=$cat_l; }
	   $cInfo_array['categories']=$cat_list;
	  tep_db_free_result($cat_query);

	} elseif(self::$action == 'new') {
	   $cInfo_array = array('content_id' => '', 'content_name' => '',  'date_added' => '', 'last_modified' => '', 'content_status' => '1', 'categories'=>array());
	  for ($i=0, $n=sizeof(self::$languages); $i<$n; $i++) {
	     $cInfo_array['text'][self::$languages[$i]['id']] = '';
	     $cInfo_array['title'][self::$languages[$i]['id']] = '';
	  }
	}
	self::$cInfo = new objectInfo($cInfo_array);

	if (!isset(self::$cInfo->content_status)) self::$cInfo->content_status = '1';
	switch (self::$cInfo->content_status) {
	  case '0': self::$enabled_status = false; self::$disabled_status = true; break;
	  case '1':
	  default:  self::$enabled_status = true;  self::$disabled_status = false;
	}

      // ACA START LOAD VALUES FROM DB
      self::$modules->load_db_values ($ID);

    return self::$cInfo;
  }

  /**
    @fn display_view()
    @brief this methode is switch for call gabarit action
  */
  public function display_view(){
    $action=self::$action;

    switch (self::$action) {
      case 'delete':
	self::load_db_values($_GET['cID']);
      break;
      case 'edit':
	self::load_db_values($_GET['cID']);
      case 'new':
	$action='edit';
      break;
      default:
	self::tep_get_list();
	$action='listing';
    }
    /// use master gabarit
    return MGabCont::CallGab($action,__FUNCTION__,__CLASS__);
  }




  /** public static InterfacedTJsonS */

  /**
    @fn get_item_action($content)
    @brief private model for row action
    @param $content array
  */
  private static function get_item_action($content){
    return  sprintf(
		  CsrtAction::getFormat('row_action'),
		  self::$modules->display_ColumnRowAction($content['content_id'])  ,
		  sprintf(CsrtAction::getLink('row_action_right', IMAGE_EDIT, 'edit'), '',  tep_href_link(self::FILENAME, 'cID=' . $content['content_id'] . '&amp;action=edit') ,'' ).
		  sprintf(CsrtAction::getLink('row_action_right', IMAGE_DELETE, 'delete'), 'fancy',  tep_href_link(self::FILENAME,  'cID=' . $content['content_id'] . '&amp;action=delete') ,'' )
		);
  }

  /**
    @fn get_item_status($content)
    @brief private model for row status
    @param $content array
  */
  private static function get_item_status($content){
    if($content['content_status'] == '1') return   tep_image(DIR_WS_ICONS . 'icon_status_green.gif', IMAGE_ICON_STATUS_GREEN) . ' <a href="' . tep_href_link(self::FILENAME, 'action=setflag&amp;flag=0&amp;cID=' . $content['content_id']) . '">' . tep_image(DIR_WS_ICONS . 'icon_status_red_light.gif', IMAGE_ICON_STATUS_RED_LIGHT) . '</a>';
    else return '<a href="' . tep_href_link(self::FILENAME, 'action=setflag&amp;flag=1&amp;cID=' . $content['content_id']) . '">' . tep_image(DIR_WS_ICONS . 'icon_status_green_light.gif', IMAGE_ICON_STATUS_GREEN_LIGHT) . '</a> ' . tep_image(DIR_WS_ICONS . 'icon_status_red.gif', IMAGE_ICON_STATUS_RED) ;
  }

  /**
    @fn get_item_content_hidden($content)
    @brief private model for row hidden
    @param $content array
  */
  private static function get_item_content_hidden($content){
    if($content['content_hidden'] == '1') return   tep_image(DIR_WS_ICONS . 'icon_status_green.gif', IMAGE_ICON_STATUS_GREEN) . ' <a href="' . tep_href_link(self::FILENAME, 'action=viewflag&amp;flag=0&amp;cID=' . $content['content_id']) . '">' . tep_image(DIR_WS_ICONS . 'icon_status_red_light.gif', IMAGE_ICON_STATUS_RED_LIGHT) . '</a>';
    else return '<a href="' . tep_href_link(self::FILENAME, 'action=viewflag&amp;flag=1&amp;cID=' . $content['content_id']) . '">' . tep_image(DIR_WS_ICONS . 'icon_status_green_light.gif', IMAGE_ICON_STATUS_GREEN_LIGHT) . '</a> ' . tep_image(DIR_WS_ICONS . 'icon_status_red.gif', IMAGE_ICON_STATUS_RED) ;
  }

  /**
    @fn emptyResult()
    @brief private methode for construct empty result retrun by tep_get_list
    @return array
  */
  private static function emptyResult(){
    return array(   'null',
		    'content_id',
                  'content_name',
                  'content_title',
                  'categories_name',
		  'date_added',
                  'content_status',
		  'content_hidden',
		    'action'
	  );
  }

  /**
    @fn tep_get_modele()
    @brief this array is rows in listing, the value boolean is sort active/inactive
    @return array
  */
  public static function tep_get_modele(){
    return array( 0=>false,
		  'content_id'=>true,
                  'content_name'=>true,
                  'content_title'=>true,
                  'categories_name'=>false,
		  'date_added'=>true,
                  'content_status'=>true,
		  'content_hidden'=>true,
		  'action'=>false
                );
  }

  /**
    @fn tep_get_list($page=1,$rowbyp=10,$sOrder='',$sWhere='',$options='')
    @brief Constructeur listing element cms content
    @param $page integer default(1) split page
    @param $rowbyp integer default(10) nbr line in page
    @param $sOrder string | null
    @param $sWhere string | null
    @param $options array
    @return Array
  */
  public static function tep_get_list($page=1,$rowbyp=10,$sOrder='',$sWhere='',$options=''){
    global $query_numrows,$languages_id;

    new self;

    $DB=Database::getInstance();

    $sWhere=str_replace('content_id','c.content_id',$sWhere);

    $query_raw = "select distinct  c.content_id, content_name, date_added, content_title, last_modified, content_status, content_hidden from " . TABLE_CONTENT . " c ," . TABLE_CONTENT_DESCRIPTION . " cd WHERE c.content_id =cd.content_id   AND cd.language_id='".(int)$languages_id."'  ".$sWhere." order by ".((!empty($sOrder)) ? $sOrder :'date_added DESC') ;
    $split = new splitPageResults($page, $rowbyp, $query_raw, $query_numrows);

    $_query = $DB->query($query_raw);

    while ($ressql = $_query->fetchAssoc() ) {
      $ressql['date_added']=tep_date_short($ressql['date_added']);
      $ressql['categories_name']='';
      $objres=$DB->query("SELECT categories_name FROM " . TABLE_CATEGORIES . " c,  " . TABLE_CATEGORIES_DESCRIPTION . " cd , " . TABLE_CONTENT_TO_CATEGORIES . " p2c    WHERE c.categories_id=cd.categories_id AND cd.language_id = '" . (int)$languages_id . "'  AND c.categories_id=p2c.categories_id and content_id='".$ressql['content_id']."' ");
      $res=$objres->fetchAllAssoc();

      foreach($res as $cat)
	$ressql['categories_name'] .=','.$cat['categories_name'];

      if(strlen($ressql['categories_name'])>25)$ressql['categories_name']= substr($ressql['categories_name'],0 ,20).'...';


      $ressql[0]=$ressql['content_id'];
      $ressql['content_status']=self::get_item_status($ressql);
      $ressql['content_hidden']=self::get_item_content_hidden($ressql);
      $ressql['action']=self::get_item_action($ressql);
      self::$list[]=$ressql;
    }

    $li=$res=array();
    foreach(self::$list as $item){
      foreach(self::tep_get_modele() as $k=>$v) $li[$k]=(tep_not_null($item[$k]))?$item[$k]:'&nbsp;';
      $res[]=$li;
    }

    if(count($res)==0) $res[]= self::emptyResult();
    return $res;
  }


 /** static InterfacedInnerHtml */

  /**
    @fn detail_row_page($id)
    @brief call Ajax , detail of line in listing
    @param $id int content_id
  */
  public static function detail_row_page($id){
    self::$action ='detail';
    self::GetConf();
    self::load_db_values((int)$id);
    return tep_get_include_contents(__CLASS__.'.inline');
  }


  /**
    @fn UpdateOrphelin()
    @brief call method for update in cat , the content in not category
  */
  private static function UpdateOrphelin(){
    $DB=Database::getInstance();
    $content_query = $DB->query("SELECT  p.content_id FROM " . TABLE_CONTENT . " p LEFT OUTER JOIN  " . TABLE_CONTENT_TO_CATEGORIES . " p2c ON p.content_id =p2c.content_id  WHERE  p2c.content_id is null");
    while ($content = tep_db_fetch_array($content_query))
      $DB->query("insert into " . TABLE_CONTENT_TO_CATEGORIES . " (content_id, categories_id) values ('" . (int)$content['content_id'] . "', '".ORPHELIN_COLLECTOR."')");
  }


/** Interface module */

  function check() { return false; }
  function install() { return false; }
  function remove() { return false;  }
  function keys() { return false; }
}







/**
  @class ACAcontent
*/

class ACAcontent
  extends aca
    implements mod_aca{
    var $modules=array();
    var $content_id;
    var $image_handler;

  /**
    class constructor
  */
  function __construct() {
    global $language, $languages_id, $lang,$oscss;
    $this-> name='content';
    $this-> content_id='';
    $this-> image_handler='';

    foreach(parent::initialise_type('MODULE_CONTENT_INSTALLED_BO','content') 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);
    }
  }

  /**
    Find which module will take care of saving images
    $handler is optional and can be used to force an image handler
  */
  public function set_image_handler ($handler='') {
    if ($handler=='') {
      foreach ($this->modules as $key=>$module)
	if (($module->enabled) and (method_exists($module,'get_content_image_handler' )))
	  $handler= $this->modules[$key]->get_content_image_handler($handler);
    }
    $this->image_handler = $handler;
    if ($handler!='') $this->modules[$handler]->is_image_handler = true;
  }

  /**
    Ask each module what to insert into content table
  */
  public function get_insert_table_content () {
    $sql_data_array=array();
    foreach ($this->modules as $key=>$module) {
      if (($module->enabled) and (method_exists($module, 'insert_table_content' ))) {
	$sql_module= $this->modules[$key]->insert_table_content();
	$sql_data_array=array_merge ($sql_data_array, $sql_module);
      }
    }
    return $sql_data_array;
  }

  public function get_update_table_content (){
    $sql_data_array=array ();
    foreach ($this->modules as $key=>$module) {
      if (($module->enabled) and (method_exists($module,'update_table_content' ))) {
	$sql_data_array= (array)$this->modules[$key]->update_table_content();

      }
    }
    return $sql_data_array;
  }

  public function get_insert_table_content_description ($language_id) {
    $sql_data_array=array();
    foreach ($this->modules as $key=>$module) {
	if (($module->enabled) and (method_exists($module,'insert_table_content_description' ))) {
	  $sql_module= $this->modules[$key]->insert_table_content_description($language_id);
	  $sql_data_array=array_merge ($sql_data_array, $sql_module);
	}
    }
    return $sql_data_array;
  }

  public function get_update_table_content_description ($language_id) {

    $sql_data_array = array();
    foreach ($this->modules as $key=>$module) {
      if (($module->enabled) and (method_exists($module,'update_table_content_description' ))) {
	$sql_module= $this->modules[$key]->update_table_content_description($language_id);
	$sql_data_array=array_merge ($sql_data_array, $sql_module);
      }
    }
    return $sql_data_array;
  }


  /**
  */
  public function after_update ($content_id){
    $this->content_id=$content_id;
    foreach ($this->modules as $key=>$module) {
      if (($module->enabled) and (method_exists($module,'after_update' )))
	$this->modules[$key]->after_update($this->content_id);
    }
    $languages = tep_get_languages();
    for ($i=0, $n=sizeof($languages); $i<$n; $i++) {
      $language_id = $languages[$i]['id'];
      foreach ($this->modules as $key=>$module) {
	if (($module->enabled) and (method_exists($module,'after_update_lang' )))
	  $this->modules[$key]->after_update_lang($language_id, $this->content_id);
      }
    }
  }


  /**
    Suppression apres confirmation
  */
  public function delete_product ($content_id){
    foreach ($this->modules as $key=>$module)
      if (($module->enabled) and  method_exists($module, 'delete_product' ))
	$this->modules[$key]->delete_product($content_id);
  }


  /**
    Load each module parameters from database
  */
  public function load_db_values ($content_id) {
    global $language, $languages_id;
    $this->content_id=$content_id;
    foreach ( $this->modules as $key=>$module) {
      if (($module->enabled) and  method_exists($module, 'load_db_values' ))  $this->modules[$key]->load_db_values($content_id);
    }
  }

  /**
    Load each module parameters from the  POST variables
  */
  public function load_post_values ($post) {
    $post = $this->check_post_array ($post);
    $this->content_id = @$_GET['pID']; // Save the product ID
    foreach ($this->modules as $key=>$module) {
      if (($module->enabled) and (method_exists($module, 'load_post_values' )) and (isset($post[$module->code])))
	$this->modules[$key]->load_post_values($post[$module->code]);
    }
  }


  /**
    Tabs in content
    Ask each module about what to dispay in the product editor of each module.
  */
//   function display_edit (&$contents) {
//   }

  public function display_image_preview (){
    // Returns the image path and name to show in the product preview
    return $this->modules[$this->image_handler]->display_image_preview ();
  }


  /**
    Return tableau complet des element à insrére dans la clause sql
  */
  public function shearch_in_product(){
    foreach ($this->modules as $key=>$module)
	if ($module->enabled && method_exists($module, 'shearch_in_product' ))
	  $contents[$key]=$this->modules[$key]->shearch_in_product();
   return $contents;
  }

}


?>