<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 租售宝（经纪人版本）管理系统
 *
 * 基于Codeigniter的经纪人房源管理系统
 * 
 * 租售宝（经纪人版本）管理系统是服务于房产经纪人的后台房源管理系统
 * 
 *
 * @package         applications
 * @author          xz
 * @copyright       Copyright (c) 2006 - 2012, HOUSE365.com.
 * @link            http://nj.zsb.house365.com/
 * @version         4.0
 */

// ------------------------------------------------------------------------

/**
 * 逻辑控制器类
 * （Codeigniter所有的控制器都必须继承CI_Controller类，但CI_Controller类位于esf_system目录下，
 *  不方便修改，所以创建MY_Controller，用来继承CI_Controller）
 *
 * 所有的控制器都继承MY_Controller， MY_Controller加载一些公用帮助函数、公用类库等
 *
 * @package         admincp
 * @subpackage      core
 * @category        MY_Controller
 * @author          xz
 */
class MY_Controller extends CI_Controller 
{
    protected $user_arr = array();     //已登陆用户信息
        
    /**
    * Constructor
    * @param string $type 区分不同模块来加载不同的共用函数、类库（备用扩展）
    */
    public function __construct( $type = NULL ) 
    {
        parent::__construct();



        //加载memcached
        $this->load->library('My_memcached3','','mc');

        //判断是否在线，非在线状态将自动跳转登陆
        $this->_check_online();

        //为user_arr属性复制
        $this->_init_user_info();

	    /* 
		//记录访问量
		$count = $this->mc->get('getHitNum_MY_Controller_055');
		if(!$count['time']){
			$data = array('time'=>time(),'num'=>$count['num']+1);
			$this->mc->set('getHitNum_MY_Controller_055',$data,86400);
		}else{
			$count['num'] = $count['num']+1;
			$this->mc->set('getHitNum_MY_Controller_055',$count,86400);
		} */

        // 弱密码,并且当前请求不是修改密码或退出则跳转到修改密码页面
        if ($this->session->userdata('zsb_user_weak_password') && ($_SERVER['REQUEST_URI'] != '/ucenter_information/edit_password/' && $_SERVER['REQUEST_URI'] != '/login/quit/')) {
            header("Location: /ucenter_information/edit_password");
            exit;
        }

    }
    
    /**
     * Init user info, this function is just let us get user's info easier
     */
    private function _init_user_info()
    {
        //加载broker模型类
        $this->load->model('broker_model');
        //把SESSION中的用户信息赋给user_arr，方便使用
        $this->user_arr = $this->broker_model->get_user_session();

    }


    //日志:wjy
    function writelog($log, $type = 'sql')
    {
        $path = '../log/'.date('Ym').'/';
        $filename = $path . $type . ".log";
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        $handle = fopen($filename, "a+");
        fwrite($handle, date('m-d H:i:s') . "  " . $log . "\r\n");
        fclose($handle);
    }
    
    /**
     * Check online function
     * If you want to make someone pass this check all the time, you just need to add it in the config array.
     */
    private function _check_online()
    {

        //定位
        $router = where_am_i();
        $class  = $router['class'];
        $method  = $router['method'];
		
        //加载配置
        $no_login_check_arr = $this->config->item('no_login_check');

        if(is_array($no_login_check_arr) && !empty($no_login_check_arr))
        {
            //加载broker模型类
            $this->load->model('broker_model');
            //判断是否在线

            $isonline = isset($no_login_check_arr[$class]) 
                    && is_array($no_login_check_arr[$class]) 
                    && !empty($no_login_check_arr[$class]) 
                    && in_array($method, $no_login_check_arr[$class]) 
                    ? TRUE : $this->broker_model->check_online();
         
            //检查三方后台进入加判断，防止串号
            if($isonline)
            {
                $broker_id = $this->input->cookie('broker_id', TRUE);
                $broker_id = intval($broker_id);
				
                $u_session = $this->broker_model->get_user_session();
                $uid = intval($u_session['uid']);
                if($broker_id > 0 && $u_session['uid'] != $broker_id)
                {
                    //清空之前的登陆数据
                    $this->broker_model->logout();

                    $isonline = FALSE;
                }
				
            }

            //不在线跳出登陆
            if(!$isonline)
            {
                //跳转到登录页面
                $this->redirectLogin();
                exit;
            }
        }
    }
    
    
    protected function redirectLogin() 
    {

        if($this->isAjax()) 
        {
            if(strpos($_SERVER['HTTP_ACCEPT'],'json')!==false) 
            {
                echo json_encode(array('errorCode'=>401));
            } 
            else 
            {
                echo 'errorCode401';
            }
        } 
        else 
        {
            $this->jump(GB_WO_URL.'/login/');
        }
    }
    
    
    //页面跳转
    public function jump($url, $msg = '', $time = 2000)
    {
		//$templateName = $this->config->item('templateName');
        $time = intval($time);
        $goto_url = '' != $url ? $url : GB_WO_URL;

        if('' != $msg && $time > 0)
        {
            $data_arr['url'] = $goto_url;
            $data_arr['msg'] = $msg;
            $data_arr['time'] = $time;

            //调用跳转页面
            $this->load->view('jump', $data_arr);
        }
        else
        {
            redirect($goto_url);
        }
    }
    
    //显示页面
    public function view($menu_key  = 'index', $page_key  = 'index', $data = array())
    {

        global $gb_sql_num, $gb_sql_arr;

        $data['gb_sql_num'] = $gb_sql_num;
        $data['gb_sql_arr'] = $gb_sql_arr;
        $data['admin_debug'] = $this->input->cookie('admin_debug', TRUE);

        $left_arr = $this->config->item('left_menu');

        $no_show_arr = array();//array('index'); 
		

        /****虚假房源举报屏蔽免费经纪人start****/
        if($this->user_arr['groupid'] == 2){
            $no_show_arr[] = 'complain';
            $no_show_arr[] = 'my_list';
        } 
        /*****虚假房源举报屏蔽屏蔽免费经纪人end****/

        $this->load->model('package_model');
        $package = $this->package_model->find_by_id($this->user_arr['package_id']);

        if ($menu_key == 'house_manage')//控制发布出售和出租的权限
        {
            if (isset($package['package_sell_purview']) 
                    && $package['package_sell_purview'] != 1) //没有发布出售的权限
            {
                $no_show_arr[] = 'sell_modify';
                $no_show_arr[] = 'sell_manage';
                $no_show_arr[] = 'sell_manage_invalid';
                $no_show_arr[] = 'sell_manage_frozen';
                //$no_show_arr[] = 'buy_match_manage';
                
            }
            if (isset($package['package_rent_purview']) 
                    && $package['package_rent_purview'] != 1) //没有发布出租的权限
            {
                $no_show_arr[] = 'rent_modify';
                $no_show_arr[] = 'rent_manage';
                $no_show_arr[] = 'rent_manage_invalid';
                $no_show_arr[] = 'rent_manage_frozen';
                //$no_show_arr[] = 'rent_match_manage';
            }
        }
        
        //头部房源管理链接
        $header_house_url = '/sell/manage/active/';
        if(isset($package['package_sell_purview']) 
                    && $package['package_sell_purview'] != 1){
            $header_house_url = '/rent/manage/active/';
        }

        $data['header_data_arr'] = $this->user_arr;
        $this->load->model('message_model');
        $data['message_num'] = $this->message_model->get_message_no_read($this->user_arr['uid']);
        $data['memu_key'] = $menu_key;
        $data['memu'] = $left_arr;
        $data['header_house_url'] = $header_house_url;

		//$templateName = $this->config->item('templateName');

        //获取关闭的菜单配置
        /*$close_menu = $this->config->item('close_menu');
        $data['close_menu'] = $close_menu ? $close_menu : array();
        if(in_array($menu_key ,$data['close_menu']))
        {
            die('该功能暂未开放！');
        }*/
		
		$functionSwitch = $this->config->item('functionSwitch');
        $data['functionSwitch'] = !empty($functionSwitch) ? $functionSwitch : array();
        $realHouse = $this->config->item('is_open_real_house');

        if (!empty($realHouse) && $realHouse == 1) {
            $this->load->model('broker_model');

            $packageId = $this->user_arr['package_id'];

            $realNumLimit =$this->broker_model->get_realnum_by_packageid($packageId);

            $data['realNumLimit'] = $realNumLimit;

        }
		if(!empty($_GET['testw']))
		{
			$this->load->view('header_wang', $data);
		}
		else
		{
			$this->load->view('header', $data);
		}

      // echo $page_key;
        //print_r($page_key);
	    //var_dump($page_key);

	    if(isset($left_arr[$menu_key])
                && is_array($left_arr[$menu_key]) && count($left_arr[$menu_key]) > 0 
                && $this->my_in_array($page_key, $left_arr[$menu_key]))
        {

            $left_menu_num = count($left_arr[$menu_key]);

            if( count($no_show_arr) > 0 && (GB_CITY=='nj' || GB_CITY=='hf'))
            {   
				

                //去掉不显示的菜单项
               foreach ( $left_arr[$menu_key] as $key =>$value)
                {   
                   if( is_array($value) && !empty($value))
                   {    
                        foreach($value as $sub_key => $sub_val)
                        {   
							
                            if( in_array( $sub_val , $no_show_arr) )
                            {   
                                unset($left_arr[$menu_key][$key][$sub_key]);
                            }
                        }
                   }
                   else
                   {
                        if( in_array( $value , $no_show_arr))
                        {   
                            unset($left_arr[$menu_key][$key]);
                        }
                   }
                }
            }

            $menu_left_arr = array_values(array_filter($left_arr[$menu_key]));

            if(is_array($menu_left_arr) && !empty($menu_left_arr))
            {

                $this->load->view('left', array('menu_left_arr'=>$menu_left_arr, 'page_key'=>$page_key));
            }
        }

        $this->load->view($page_key,$data);
        $this->load->view('footer');
    }
    

    private function my_in_array($v,$arr) {

        $flag = false;
        foreach ($arr as $va) {
            if(!is_array($va)) {
                if($va == $v) {
                    $flag =  true;
                    break;
                } else {
                    continue;
                }
            } else {
                $flag = $this->my_in_array($v, $va);
                if($flag) {
                    break;
                } else {
                    continue;
                }
            }
        }
        return $flag;
    }
    
    public function isAjax() {

        return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
    }



	public function __destruct(){
		if(isset($this->mc)){
		    $this->mc->close();
		}		
	}

	/*
	 * 数组编码转换
	 */
	public function array_iconv($arr,$in_charset='gbk', $out_charset='utf-8' )
	{
		foreach ($arr as $k => $v) {
			if (is_array($v)) {
				$arr[$k] = $this->array_iconv($v,$in_charset,$out_charset);
			} else {
				$v = iconv($in_charset, $out_charset, $v);
				$arr[$k] = $v;
			}
		}
		return $arr;
	}

}
/* End of file MY_Controller.php */
/* Location: ./applications/core/MY_Controller.php */