<?php
/**
* @author:  Bunzia Alexander <nifus@mail.ru> <http://www.weblancer.net/users/nifus/>
* @copyright: Copyright (c) 2010, Bunzia Alexander
* @version: 1.0
* @license: http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/


include_once(MAIN_SOURCE_PATH.'/modules/admin/lang/'.MAIN_LANG.'/lang.php');
include_once(MAIN_SOURCE_PATH.'/inc/class.objects.php');
include_once(MAIN_SOURCE_PATH.'/inc/class.query.php');

class filedsSetBlocks
{

  static function b_access($v){
    return !empty($v) ? 1 : 0;
  }
  
  static function b_name($v){
      
    if ( empty($v) ){
      throw new Exception(M_ADMIN_BLOCKS_EMPTY_NAME);
    }
    return $v;
  }
  
  static function b_parser_name($v){
    if ( empty($v) ){
      throw new Exception( M_ADMIN_BLOCKS_EMPTY_PARSER_NAME );
    }
    if ( preg_match('#[^0-9_a-z]#iUs',$v) ){
      throw new Exception( sprintf(M_ADMIN_BLOCKS_FALSE_PARSER_NAME,$v)  );
    }
    return $v;
  }
  
  static function b_type_content($v){
    if ( empty($v) ){
      return false;
    }
    
    $values = array('H','P','T');
    if ( !in_array($v,$values) ){
      throw new Exception( M_ADMIN_BLOCKS_FALSE_TYPE_CONTENT  );
    }
    return $v;
  }
	

}


class filedsGetBlocks
{

  static $__var = array();  //  для хранения временных переменных


  static function access_checked($v){
    return !empty($v) ? 'checked' : '';
  }

  static function var_name($v){
  global $ITEMS ;
    if ( !empty($v)){
      return $ITEMS[$v];
    }
  }

  static function type_content_php($v){
    if ( $v=='P'){
      return true;
    }else{
      return false;
    }
  }

  static function type_content_html($v){
    if ( $v=='H'){
      return true;
    }else{
      return false;
    }
  }

  static function type_content_tmpl($v){
    if ( $v=='T'){
      return true;
    }else{
      return false;
    }
  }
  

  /**
  * Список шаблонов для размещения блока
  *
  */
  static function tmplSelect($v){
    include_once(MAIN_SOURCE_PATH.'/modules/admin/inc/class.tmpl.php');
    $s_tmpl_list = tmpl::get_list();
    $s = new select_box();
    $s -> empty_record(false);
    foreach( $s_tmpl_list as $k=>$v ) { 
       $s -> set($v['t_id'],$v['t_name'] );
    }
    return $s -> get();  
  }

  static function groupsSelect($v){
  global $MAIN_DB;
      //  получим список групп вообще
    $groups = users::groups();
      //  получим список групп для  блока
    $v = intval($v);
    if ( empty($v) ){
      sys_error(500);
    }
    $add_groups = array();
    $sql = "SELECT g_id FROM ".MAIN_GRP_BLK_LINK_TBL." WHERE b_id='$v'";
    $res = $MAIN_DB -> query($sql);
    while( list($g_id) = $MAIN_DB -> fetch_array($res) ){
      $add_groups[]=$g_id;
    }
    
    
    $s = new select_box();
    $s -> selected_id($add_groups);
    $s -> empty_record(false);
    foreach( $groups AS $g_id => $g_name ){
      $s -> set($g_id,$g_name );
    }
    return $s -> get();
  }

  /**
  * Список шаблонов оформления блока
  *
  */
  static function tmplBlockSelect($v){

    $s = new select_box();
    $s -> selected_id($v);
    $s -> empty_record(true,false,'---');
    $s -> opt_open('Стандартные');
    if ( !is_dir(MAIN_PATH.'/source/tmpl/default/blocks') ){
      sys_error(ERROR_500,'Ошибка: нет каталога "'.MAIN_PATH.'/source/tmpl/default/blocks"');
    }
    $handle = opendir(MAIN_PATH.'/source/tmpl/default/blocks');
    while (false !== ($file = readdir($handle))) { 
     if ( preg_match('#\.html$#iUs',$file) ){
       $s -> set('default/blocks/'.$file,$file );
      }
    }
    $s -> opt_close();
    if ( !is_dir(MAIN_PATH.'/source/tmpl/project/blocks') ){
      sys_error(ERROR_500,'Ошибка: нет каталога "'.MAIN_PATH.'/source/tmpl/default/blocks"');
    }
    
    $handle = opendir(MAIN_PATH.'/source/tmpl/project/blocks');
    
    $s -> opt_open('Пользовательские');
    while (false !== ($file = readdir($handle))) { 
     if ( preg_match('#\.html$#iUs',$file) ){
       $s -> set('project/blocks/'.$file,$file );
      }
    }
    $s -> opt_close();
    return $s -> get();
  }

  static function countLinkTmpl($v){
  global $MAIN_DB;
    $sql = "SELECT COUNT(*) FROM ".$MAIN_DB -> prefix("system_tmpl_block_link")." WHERE b_id='$v'";
    list($count) = $MAIN_DB -> fetch_array( $MAIN_DB -> query($sql) );
    return $count;
  }
  
  

}




class blocksQuery extends query{
	
	var $fields_get = 'filedsGetBlocks';
		
	public function __construct($alias){
		$this -> set_table( MAIN_BLK_TBL );
		$this -> set_alias($alias);
	}
	
	
  public function include_pages_block_link($alias,$cols=''){
    $this -> include_table(MAIN_PLB_TBL,$alias,'b_id',$cols );
  }
  
  public function include_modules($alias,$cols=''){
    $this -> include_table(MAIN_MODULES_TBL,$alias,'m_path',$cols );
  }
  
  
  public function where_id($v){
    $v = intval($v);
    if ( empty($v)  ){
      return FALSE;
    }
    return $this -> set_where( $this -> alias.'.b_id',$v);
  }
  
  public function where_not_id($v){
    $v = intval($v);
    if ( empty($v)  ){
      return FALSE;
    }
    return $this -> set_anothe_where( $this -> alias.'.b_id!='.$v);
  }
  
  public function where_parser_name($v){
    
    if ( empty($v)  ){
      return FALSE;
    }
    return $this -> set_where( $this -> alias.'.b_parser_name',$v);
  }
  
  public function where_pid($id){
    $id = intval($id);
    if ( empty($id)  ){
      return false;
    }
    $alias = $this -> get_alias(MAIN_PLB_TBL);
    return $this -> set_where( $alias.'.t_id',$id);
  }
  
  
  public function where_func($v){
    if ( empty($v)  ){
      return false;
    }
    if ( preg_match('#[^a-z_0-9]#i',$v)  ){
      return false;
    }
    return $this -> set_where(  $this -> alias.'.b_func',$v);
  }
  
  public function where_path($v){
    if ( empty($v)  ){
      return false;
    }
    if ( preg_match('#[^a-z_0-9]#i',$v)  ){
      return false;
    }
    return $this -> set_where(  $this -> alias.'.m_path',$v);
  }

	public function orderby_sort($sort){
    $alias = $this -> get_alias(MAIN_PLB_TBL);
    $this -> set_orderby( $alias.'.sort',$sort);
  }
  public function orderby_path($sort){
    $this -> set_orderby( $this -> alias.'.m_path',$sort);
  }
  public function orderby_name($sort){
    $this -> set_orderby( $this -> alias.'.b_name',$sort);
  }
  public function orderby_id($sort){
    $alias = $this -> get_alias(MAIN_PLB_TBL);
    $this -> set_orderby( $alias.'.id',$sort);
  }
  public function orderby_parser_name($sort){
    $this -> set_orderby( $this -> alias.'.b_parser_name',$sort);
  }
	


	


} //  end modulesQuery


class blocks extends objects{
	
	public $table = "system_blocks";
  public $key = "b_id";
	public $fields = 'filedsSetBlocks';
	


		//	загрузка модуля по его id
	static function searchById($id){
		$m = blocks::query('m');
		if ( false===$m -> where_id($id) ){
			return FALSE;
		}
		$m -> get('*');
		if (  $m -> get_count_rows()==0 ){
			return FALSE;
		}
		return new blocks($id,$m -> row());
	}
	
	static function searchByPath($id){
		$m =  modules::query('m');
		if ( !$m -> where_path($id) ){
			return false;
		}
		$m -> get('*');
		if (  $m -> get_count_rows()==0 ){
			return FALSE;
		}
		$row = $m -> row();
		return new modules($row['m_id'],$row);
	}


	static function create(){
		return new blocks(0, array('b_id'=>0) );
	}

	static function query($alias){
		return new blocksQuery( $alias );
	}

	

	

	public function delete(){
  global $MAIN_DB;
		$id = $this -> id();
		if ( empty($id) ){
			throw new Exception(A_EMPTY_ID);
		}

    $sql = "DELETE FROM ".MAIN_BLK_TBL." WHERE b_id='$id'";
    $MAIN_DB -> query($sql);
    
    $sql = "DELETE FROM ".MAIN_GRP_BLK_LINK_TBL." WHERE b_id='$id'";
    $MAIN_DB -> query($sql);
  
    $sql = "DELETE FROM ".MAIN_PLB_TBL." WHERE b_id='$id'";
    $MAIN_DB -> query($sql);
		return parent::delete();
	}

	public function id(){
		return $this -> info['b_id']; 
	}
	

  public function title(){
    return $this -> info['b_title'];
  } 




  static function set_groups($b_id,$v){
  global $MAIN_DB;
    
    if ( !is_array($v) ){
      $v = array();
    }
    $b_id = intval($b_id);
    if ( empty($b_id) ){
      sys_error(500,'');
    }
    
    $sql = "DELETE FROM ".MAIN_GRP_BLK_LINK_TBL." WHERE b_id = '".$b_id."'";
    $MAIN_DB -> query($sql);
    foreach($v as $g ){
      $g = intval($g);
      if ( empty($g) ){
        continue;
      }
      $sql = "INSERT INTO  ".MAIN_GRP_BLK_LINK_TBL." SET g_id='$g', b_id = '".$b_id."'";
      $MAIN_DB -> query($sql);
    }
    return true;
  }

  static function exists_parser_name($v,$id=0){
    $b = blocks::query('b');
    $b -> where_not_id($id);
    if ( !$b -> where_parser_name($v) ){
      sys_error(500);
    }
    //$b -> set_debug(1);
    $b -> get('COUNT(*)',false);
    list($count) = $b -> row();
    if ( $count >0 ){
      return true;
    }
    return false;
  }
	


    //  для совместимости
  static function load_id($id){
    return self::searchById($id);
  }
  static function load_path($path){
    return self::searchByPath($path);
  }

}