<?php
/**
 * Copyright (C) LJCMS All rights reserved.
 * <E-Mail：aspcms@qq.com>
 * Url http://www.liangjing.org
 *     http://www.8CMS.com
 * Update 2016.03.19
 */

class oabase extends X {
    protected $cpfile; 
    protected $cptpl; 
    protected $pagesize = 20;
    protected $page = 1;
    protected $gb_c = "";
    protected $gb_a = "";

    
    public function __construct() {
		
        $badge_count=$this->badge_count();
        $this->gb_c = GB_LJCMS_C;
        $this->gb_a = GB_LJCMS_A;
    
        if ($this->gb_c != "Public") {   			          
		   $this->checkLogin(); 
           $top_menu= $this->get_top_menu($badge_count);
		}
		
        //$this->checkAuth($this->gb_a);       
        $this->cpfile = 'oa.php';
        $this->cptpl = 'tpl/oa/';
       
        $top_menu_data=$this->get_top_menu_data();


        $left_menu=$this->get_left_menu($top_menu_data['id'],$badge_count);
        $this->page = intval(XRequest::getArgs('page'));
        if ($this->page<1) {
            $this->page = 1;
        }
        $config=$this->get_system_config();
      
        $_var_array = array(
            "c"=>$this->gb_c,
            "a"=>$this->gb_a,
            "time"=>time(),
            "cpfile"=>$this->cpfile,
            'oapath'=>'tpl/oa/',
            'user_name'=>$_SESSION['user_name'],
            'top_menu'=>$top_menu,
            'top_menu_name'=>$top_menu_data['name'],
            'left_menu_html'=>$left_menu,
            'config'=>$config,
            'badge_count'=>$badge_count
        );
        TPL::assign($_var_array);
//        if (isset($_GET['ljcms'])) {
//            X::poweredBy();
//        }
       // echo 123;die;
    }
    
    public function checkLogin() {
          $auth_id = $_SESSION['USER_AUTH_KEY'];
		if (!isset($auth_id)) {
			            XHandle::halt('对不起，您还没有登录！', $this->cpfile.'?c=Public&a=login', 4);

		}          
    }

    
    public function checkAuth($value) {
        $auth = parent::model('login', 'am');
        $auth->checkAuth($value);
        unset($auth);
    }


        public function log($em, $oplog = '', $result = 1) {
        
        require_once BASE_ROOT.'source/include/elements.php';
        $emarray = array();
        $emarray = auth_get_em_array();

        
        $log_string = '';
        if (!empty($em)) {
            $log_string = $emarray[$em];
        }
        if (!empty($oplog)) {
            $log_string .= !empty($log_string) ? '-'.$oplog : $oplog;
        }

        
        if (!empty($log_string)) {
            $logid = parent::$obj->fetch_newid("SELECT MAX(logid) FROM ".DB_PREFIX."log", 1);
            $log_array = array(
                'logid'=>$logid,
                'username'=>parent::$wrap_admin['adminname'],
                'ip'=>XRequest::getip(),
                'content'=>$log_string,
                'logtype'=>1,
                'timeline'=>time(),
                'success'=>$result,
            );
            parent::$obj->insert(DB_PREFIX.'log', $log_array);
            unset($log_array);
        }
    }

    public function get_system_config() {
	$model = parent::model('system', 'oa');
        $system_data=$model->getconfig("system");
        $data=array();
        foreach($system_data as $val){
            $data[$val['code']]=$val['val'];
        }
        return $data;
}

    public function saveLoginLog($username, $content, $success=0) {
        $logid = parent::$obj->fetch_newid("SELECT MAX(logid) FROM ".DB_PREFIX."log", 1);
        $log_array = array(
            'logid'=>$logid,
            'username'=>$username,
            'ip'=>XRequest::getip(),
            'content'=>$content,
            'logtype'=>1,
            'timeline'=>time(),
            'success'=>$success,
        );
        parent::$obj->insert(DB_PREFIX.'log', $log_array);
        unset($username, $content, $success, $logid, $log_array);
    }
    public function get_top_menu($badge_count){
			
          $model = parent::model('node', 'oa');
		  $data=$model->get_top_menu();
	//	  echo 123;die;
          foreach ($data as $k=>$v){
              $data[$k]['count']=$badge_count[$v['id']];
          }
          if(empty($data)){
                XHandle::halt('对不起，您还没有权限！', $this->cpfile.'?c=Public&a=login', 4);
          }
          return $data;
    }
    public function get_top_menu_data(){
        	//读取数据库模块列表生成菜单项
                $model = parent::model('node', 'oa');
		$menu = $model->access_list();
		$system_folder_menu = $model->get_folder_menu();
		$user_folder_menu = $model->get_userfolder_menu();
		$menu = array_merge($menu, $system_folder_menu, $user_folder_menu);
		$menu = $this->sort_by($menu, 'sort');
              
                //读取数据库模块列表生成菜单项
                $url="?c=".$this->gb_c;
                if($this->gb_a!='' and $this->gb_a!='run'){
                    $url.="&a=".$this->gb_a;
                }
               $top_menu = $this->get_top_menu_id($url, $menu);
               $data=$model->get_top_menu_data($top_menu);
               return $data;
        
    }
    public function get_left_menu($id,$badge_count){
        $model = parent::model('node', 'oa');
        $menu=$model->get_user_menu();
        $left_menu = $this->list_to_tree($menu, $id); 
        
       // print_r($badge_count);
        $left_menu_html= $this->tree_nav($left_menu,$badge_count);
        return $left_menu_html;
    }
    protected function c() { 
        return $this->gb_c;
    }
    
    public function badge_count(){
                $model = parent::model('node', 'oa');
                $node_list = $model->get_user_menu();
                
		$system_folder_menu = $model -> get_folder_menu();
		$user_folder_menu = $model -> get_userfolder_menu();
		$node_list = array_merge($node_list, $system_folder_menu, $user_folder_menu);
              //  print_r($node_list);
                $count = parent::model('count', 'oa');
		foreach ($node_list as $val) {
			$badge_function = $val['badge_function'];
               
                      //   print_r($badge_function);
			if (!empty($badge_function) and ($badge_function != 'badge_sum')) {
                                if ($badge_function == 'badge_count_system_folder' or $badge_function == 'badge_count_user_folder') {
					$badge_count[$val['id']] = $count->$badge_function($val['fid']);
				} else {
					$badge_count[$val['id']] = $count->$badge_function();
                                }
			}
		}
                $publicmodel=parent::model('public', 'oa');

		foreach ($node_list as $key => $val) {
			if ($val['badge_function'] == 'badge_sum') {
				$child_menu = $publicmodel->list_to_tree($node_list, $val['id']);
                               
				$child_menu = $publicmodel->tree_to_list($child_menu);

				$child_menu_id = $publicmodel->rotate($child_menu);
				$count = 0;
				if (isset($child_menu_id['id'])) {
					$child_menu_id = $child_menu_id['id'];
					
					foreach ($child_menu_id as $k1 => $v1) {
						if (!empty($badge_count[$v1])) {
							$count += $badge_count[$v1];
						}
					}
				}
				$badge_sum[$val['id']] = $count;
			}
		}
		if (!empty($badge_count)) {
			if (!empty($badge_sum)) {
				$total = $badge_count + $badge_sum;
			} else {
				$total = $badge_count;
			}
                        return $total;
		}       
    }

    protected  function get_top_menu_id($url, $menu = null) {
            if($url=="?c=Contact&a=add"){
                $url="?c=Contact";
            }elseif ($url=="?c=Schedule&a=day_view" || $url=="?c=Schedule&a=add" || $url=="?c=Schedule&a=edit") {
                  $url="?c=Schedule";
            }elseif ($url=="?c=Todo&a=add" || $url=="?c=Todo&a=edit") {
                  $url="?c=Todo";
            }elseif ($url=="?c=Message&a=add" || $url=="?c=Message&a=read") {
                  $url="?c=Message";
            }elseif ($url=="?c=Customer&a=add" || $url=="?c=Customer&a=read") {
                  $url="?c=Customer";
            }elseif ($url=="?c=Supplier&a=add" || $url=="?c=Supplier&a=read") {
                  $url="?c=Supplier";
            }elseif ($url=="?c=Work&a=add" || $url=="?c=Work&a=edit") {
                  $url="?c=Work";
            }elseif ($url=="?c=Task&a=add" || $url=="?c=Task&a=read") {
                  $url="?c=Task";
            }elseif ($url=="?c=Finance&a=add" || $url=="?c=Finance&a=account_list" || $url=="?c=Finance&a=add_account" || $url=="?c=Finance&a=add_income" || $url=="?c=Finance&a=add_payment" || $url=="?c=Finance&a=add_transfer" || $url=="?c=Finance&a=read") {
                  $url="?c=Finance";
            }
            if (empty($menu)) {
                    $model = parent::model('node', 'oa');
		    $menu = $model->access_list();
                    $menu = $this->sort_by($menu, 'sort');
            }
            $publicmodel=parent::model('public', 'oa');
            $menu = $publicmodel->tree_to_list($publicmodel->list_to_tree($menu));
       
            foreach ($menu as $key => $val) {
                    if ($val['url'] == $url) {
                            $return = $val['id'];                  
                    }
            }
          //  echo $return;
            arsort($menu);
            foreach ($menu as $key => $val) {
                    if ($val['id'] == $return) {         
                            if ($val['pid'] != 0) {                              
                                    $return = $val['pid'];
                            }
                    }
            }
            foreach ($menu as $key => $val) {
                    if ($val['id'] == $return) {         
                            if ($val['pid'] != 0) {                              
                                    $return = $val['pid'];
                            }
                    }
            }
            return $return;
    }
    protected function url($url_items=null) { 
        $_url = $this->cpfile."?c=".$this->c();
        if (!empty($url_items)) {
            $_url .= "&".$url_items;
        }
        return $_url;
    }
    protected function list_to_tree($list, $root = 0, $pk = 'id', $pid = 'pid', $child = '_child') {
	// 创建Tree
	$tree = array();
	if (is_array($list)) {
		// 创建基于主键的数组引用

		$refer = array();
		foreach ($list as $key => $data) {
			$refer[$data[$pk]] = &$list[$key];
		}

		foreach ($list as $key => $data) {
			// 判断是否存在parent
			$parentId = 0;
			if (isset($data[$pid])) {
				$parentId = $data[$pid];
			}
			if ((string)$root == $parentId) {
				$tree[] = &$list[$key];
			} else {
				if (isset($refer[$parentId])) {
					$parent = &$refer[$parentId];
					$parent[$child][] = &$list[$key];
				}
			}
		}
	}
	return $tree;
}
protected function tree_nav($tree, $badge_count, $level = 0) {
   	$level++;
		$html = "";
		if (is_array($tree)) {
			if ($level > 1) {
				$html = "<ul class='submenu collapse'>\r\n";
			} else {
				$html = "<ul id='side-menu' class='nav nav-list'>\r\n";
			}
			foreach ($tree as $val) {
				if (isset($val["name"])) {
					$title = $val["name"];
					if (!empty($val["url"])) {
					
							$url = $val['url'];
						
					} else {
						$url = "#";
					}
                                        
					if (empty($val["id"])) {
						$id = $val["name"];
					} else {
						$id = $val["id"];
					}

					$icon = "fa fa-angle-right";

					if (isset($val['_child'])) {
						$html .= "<li>\r\n";
						$html .= "<a node=\"$id\" href=\"" . "$url\">";
						$html .= "<i class=\"$icon\"></i>";
						$html .= "<span class=\"menu-text\">$title</span>";
						$html .= "<span class=\"fa arrow\"></span>";
						if (!empty($badge_count[$val['id']])) {
							$html .= "<span class=\"pull-right label label-primary\">" . $badge_count[$val['id']] . "</span>";
						}
						$html .= "</a>\r\n";
						$html .= $this -> tree_nav($val['_child'], $badge_count, $level);
						$html = $html . "</li>\r\n";
					} else {
						$html .= "<li>\r\n";
						$html .= "<a  node=\"$id\" href=\"" . "$url\">\r\n";
						$html .= "<i class=\"$icon\"></i>";
						$html .= "<span class=\"menu-text\">$title</span>";
						if (!empty($badge_count[$val['id']])) {
							$html .= "<span class=\"pull-right label label-primary\">" . $badge_count[$val['id']] . "</span>";
						}
						$html .= "</a>\r\n</li>\r\n";
					}
				}
			}
			$html = $html . "</ul>\r\n";
		}
		return $html;
	}
        function sub_tree_menu($tree, $level = 0) {
	$level++;
	$html = "";
	if (is_array($tree)) {
		$html = "<ul class=\"tree_menu\">\r\n";
		foreach ($tree as $val) {
			if (isset($val["name"])) {
				$title = $val["name"];
				$id = $val["id"];
				if (empty($val["id"])) {
					$id = $val["name"];
				}
				if (isset($val['_child'])) {
					$html = $html . "<li>\r\n<a node=\"$id\"><i class=\"fa fa-angle-right level$level\"></i><span>$title</span></a>\r\n";
					$html = $html . sub_tree_menu($val['_child'], $level);
					$html = $html . "</li>\r\n";
				} else {
					$html = $html . "<li>\r\n<a  node=\"$id\" ><i class=\"fa fa-angle-right level$level\"></i><span>$title</span></a>\r\n</li>\r\n";
				}
			}
		}
		$html = $html . "</ul>\r\n";
	}
	return $html;
}
       protected function sort_by($array, $keyname = null, $sortby = 'asc') {
	//dump($array);
	$myarray = $inarray = array();
	# First store the keyvalues in a seperate array
	foreach ($array as $i => $befree) {
		$myarray[$i] = $array[$i][$keyname];
	}
	//dump($array);
	# Sort the new array by
	switch ($sortby) {
		case 'asc' :
			# Sort an array and maintain index association...
			asort($myarray, SORT_STRING);
			break;
		case 'desc' :
		case 'arsort' :
			# Sort an array in reverse order and maintain index association
			arsort($myarray, SORT_STRING);
			break;
		case 'natcasesor' :
			# Sort an array using a case insensitive "natural order" algorithm
			natcasesort($myarray);
			break;
	}
	# Rebuild the old array
	foreach ($myarray as $key => $befree) {
		$inarray[] = $array[$key];
	}
	return $inarray;
}
function show_contact($str, $mode = "show") {
	$tmp = '';

	if (!empty($str)) {
		$contacts = array_filter(explode(';', $str));
		if (count($contacts) > 1) {
			foreach ($contacts as $contact) {
				$arr = explode('|', $contact);
				$name = htmlspecialchars(rtrim($arr[0]));
				$data = htmlspecialchars(rtrim($arr[1]));
				if ($mode == "edit") {
					$tmp = $tmp . "<span data=\"$data\"><nobr><b  title=\"$name - $data\">$name</b><a class=\"del\" title=\"删除\"><i class=\"fa fa-times\"></i></a></nobr></span>";
				} else {
					$tmp = $tmp . "<a data=\"$data\" title=\"$name - $data\" >$name;</a>&nbsp;";
				}
			}
		} else {
			$arr = explode('|', $contacts[0]);
			$name = htmlspecialchars(rtrim($arr[0]));
			$data = htmlspecialchars(rtrim($arr[1]));
			$tmp = "";
			if ($mode == "edit") {
				$tmp = $tmp . "<span data=\"$data\"><nobr><b  title=\"$name - $data\">$name</b><a class=\"del\" title=\"删除\"><i class=\"fa fa-times\"></i></a></nobr></span>";
			} else {
				$tmp = $tmp . "<a title=\"$name\" >$name</a>";
			}
		}
	}
	return $tmp;
}
    /**
     * 防SQL注入和XSS攻击
     * @param $arr
     */
    public function SafeFilter($arr)
    {

       $ra=Array('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/','/script/','/javascript/','/vbscript/','/expression/','/applet/','/meta/','/xml/','/blink/','/link/','/style/','/embed/','/object/','/frame/','/layer/','/title/','/bgsound/','/base/','/onload/','/onunload/','/onchange/','/onsubmit/','/onreset/','/onselect/','/onblur/','/onfocus/','/onabort/','/onkeydown/','/onkeypress/','/onkeyup/','/onclick/','/ondblclick/','/onmousedown/','/onmousemove/','/onmouseout/','/onmouseover/','/onmouseup/','/onunload/','/eval/','/</','/>/','/on/');

       if (is_array($arr))
       {
         foreach ($arr as $key => $value)
         {
            if (!is_array($value))
            {
              if (!get_magic_quotes_gpc())             //不对magic_quotes_gpc转义过的字符使用addslashes(),避免双重转义。
              {
                 $value  = addslashes($value);           //给单引号（'）、双引号（"）、反斜线（\）与 NUL（NULL 字符）加上反斜线转义
              }
              $value       = preg_replace($ra,'',$value);     //删除非打印字符，粗暴式过滤xss可疑字符串
              $arr[$key]     = htmlentities(strip_tags($value)); //去除 HTML 和 PHP 标记并转换为 HTML 实体
            }
            else
            {
              $this->SafeFilter($arr[$key]);
            }
         }
       }
       return $arr;
    }
}
?>
