<?php 
/*

*/

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Sys_ajax extends CI_Controller {

   public function __construct(){
		parent::__construct();
		//$this->output->enable_profiler(true);//全站显示调试信息
		error_reporting(0);
	}

/*
测试后台邮箱配置
*/

	 
   public  function ajax_test_email(){	
   
      $config['protocol'] = 'smtp';
      $config['smtp_host'] = $_POST['smtp_host'];
      $config['smtp_user'] = $_POST['smtp_user'];
      $config['smtp_pass'] = $_POST['smtp_pass'];
	  $config['smtp_port'] = $_POST['smtp_port'];
      $config['mailtype'] = 'html';
      $config['validate'] = true;
      $config['priority'] = 1;
      $config['charset'] = 'utf-8';
      $config['wordwrap'] = TRUE;
	  $config['crlf']="\r\n";  
	  $config['newline']="\r\n"; 
      $this->load->library('email');
	  $this->email->initialize($config);
	
	 
	 $this->email->from($config['smtp_user'], '测试邮件');//发件人
	 $this->email->subject('cicms 邮件测试');
	 $this->email->to($_POST['test_email']);
	 $this->email->message("恭喜您，邮箱配置正确<br>this is a test mail from cicms team");

		if ($this->email->send()){
            exit('测试邮件发送成功！');
         }else{
		     exit('测试邮件发送失败！请检查配置');
		 }
    }
	


public function api_add($uploadedfile) {
		$uploadfield = array();
		$uploadfield = $uploadedfile;
		unset($uploadfield['fn']);
		$uploadfield = new_addslashes($uploadfield);
		$this->insert($uploadfield);
		$aid = $this->insert_id();
		$uploadedfile['aid'] = $aid;
		return $aid;
	}
public function api_update($content, $keyid, $isurl = 0) {
		if(pc_base::load_config('system','attachment_stat') == 0) return false;
		$keyid = trim($keyid);
		$isurl = intval($isurl);
		if($isurl==2 || empty($content)) {
			$this->api_update_cookie($keyid);
		} else {
			$att_index_db = pc_base::load_model('attachment_index_model');
			$upload_url = pc_base::load_config('system','upload_url');
			if(strpos($upload_url,'://')!==false) {
				$pos = strpos($upload_url,"/",8);
				$domain = substr($upload_url,0,$pos).'/';
				$dir_name = substr($upload_url,$pos+1);
			}
			if($isurl == 0) {
				$pattern = '/(href|src)=\"(.*)\"/isU';
				preg_match_all($pattern,$content,$matches);
				if(is_array($matches) && !empty($matches)) {
					$att_arr = array_unique($matches[2]);
					foreach ($att_arr as $_k=>$_v) $att_arrs[$_k] = md5(str_replace(array($domain,$dir_name), '', $_v));
				}
			} elseif ($isurl == 1) {
				if(is_array($content)) {
					$att_arr = array_unique($content);
					foreach ($att_arr as $_k=>$_v) $att_arrs[$_k] = md5(str_replace(array($domain,$dir_name), '', $_v));
				} else {
					$att_arrs[] = md5(str_replace(array($domain,$dir_name), '', $content));
				}
			}
			$att_index_db->delete(array('keyid'=>$keyid));	
			if(is_array($att_arrs) && !empty($att_arrs)) {
				foreach ($att_arrs as $r) {
					$infos = $this->get_one(array('authcode'=>$r),'aid');
					if($infos){
						$this->update(array('status'=>1),array('aid'=>$infos['aid']));
						$att_index_db->insert(array('keyid'=>$keyid,'aid'=>$infos['aid']));
					}
				}
			}
		}
		param::set_cookie('att_json','');
		return true;
	}
	private function api_update_cookie($keyid) {
		if(pc_base::load_config('system','attachment_stat') == 0) return false;
		$att_index_db = pc_base::load_model('attachment_index_model');
		$att_json = param::get_cookie('att_json');
		if($att_json) {
			$att_cookie_arr = explode('||', $att_json);
			$att_cookie_arr = array_unique($att_cookie_arr);
		} else {
			return false;
		}
			
	}
	public function api_delete($keyid) {
		if(pc_base::load_config('system','attachment_stat') == 0) return false;
		$keyid = trim($keyid);
		if($keyid=='') return false;
		$att_index_db = pc_base::load_model('attachment_index_model');
		$attachment = pc_base::load_sys_class('attachment');
		$info = $att_index_db->select(array('keyid'=>$keyid),'aid');
		if($info) {
			$att_index_db->delete(array('keyid'=>$keyid));
			foreach ($info as $_v) {
				if(!$att_index_db->get_one(array('aid'=>$_v['aid']))) {
					$attachment->delete(array('aid'=>$_v['aid']));
				}
			}
			return true;
		} else {
			return false;
		}		
	}
	
function gbk_to_utf8($gbstr) {
	global $CODETABLE;
	if(empty($CODETABLE)) {
		$filename = CODETABLEDIR.'gb-unicode.table';
		$fp = fopen($filename, 'rb');
		while($l = fgets($fp,15)) { 
			$CODETABLE[hexdec(substr($l, 0, 6))] = substr($l, 7, 6); 
		}
		fclose($fp);
	}
	$ret = '';
	$utf8 = '';
	while($gbstr) {
		if(ord(substr($gbstr, 0, 1)) > 0x80) {
			$thisW = substr($gbstr, 0, 2);
			$gbstr = substr($gbstr, 2, strlen($gbstr));
			$utf8 = '';
			@$utf8 = unicode_to_utf8(hexdec($CODETABLE[hexdec(bin2hex($thisW)) - 0x8080]));
			if($utf8 != '') {
				for($i = 0; $i < strlen($utf8); $i += 3) $ret .= chr(substr($utf8, $i, 3));
			}
		} else {
			$ret .= substr($gbstr, 0, 1);
			$gbstr = substr($gbstr, 1, strlen($gbstr));
		}
	}
	return $ret;
}
public function creat_ch_ad(){
      $data=$this->input->post();
	   $this->load->model("Publicm");
	  $return= $this->Publicm->creat_ch_ad($data);
	  exit($return);
}
function big5_to_gbk($Text) {
	global $BIG5_DATA;
	if(empty($BIG5_DATA)) {
		$filename = CODETABLEDIR.'big5-gb.table';
		$fp = fopen($filename, 'rb');
		$BIG5_DATA = fread($fp, filesize($filename));
		fclose($fp);
	}
	$max = strlen($Text)-1;
	for($i = 0; $i < $max; $i++) {
		$h = ord($Text[$i]);
		if($h >= 0x80) {
			$l = ord($Text[$i+1]);
			if($h==161 && $l==64) {
				$gbstr = '　';
			} else {
				$p = ($h-160)*510+($l-1)*2;
				$gbstr = $BIG5_DATA[$p].$BIG5_DATA[$p+1];
			}
			$Text[$i] = $gbstr[0];
			$Text[$i+1] = $gbstr[1];
			$i++;
		}
	}
	return $Text;
}
function gbk_to_big5($Text) {
	global $GB_DATA;
	if(empty($GB_DATA)) {
		$filename = CODETABLEDIR.'gb-big5.table';
		$fp = fopen($filename, 'rb');
		$gb = fread($fp, filesize($filename));
		fclose($fp);
	}
	$max = strlen($Text)-1;
	for($i = 0; $i < $max; $i++) {
		$h = ord($Text[$i]);
		if($h >= 0x80) {
			$l = ord($Text[$i+1]);
			if($h==161 && $l==64) {
				$big = '　';
			} else {
				$p = ($h-160)*510+($l-1)*2;
				$big = $GB_DATA[$p].$GB_DATA[$p+1];
			}
			$Text[$i] = $big[0];
			$Text[$i+1] = $big[1];
			$i++;
		}
	}
	return $Text;
}
public function add() {
		if(isset($_POST['dosubmit'])) {
			$_POST['info']['siteid'] = $this->siteid;
			$_POST['info']['category_template'] = $_POST['setting']['category_template'];
			$_POST['info']['list_template'] = $_POST['setting']['list_template'];
			$_POST['info']['show_template'] = $_POST['setting']['show_template'];
			if (isset($_POST['other']) && $_POST['other']) {
				$_POST['info']['admin_list_template'] = $_POST['setting']['admin_list_template'];
				$_POST['info']['member_add_template'] = $_POST['setting']['member_add_template'];
				$_POST['info']['member_list_template'] = $_POST['setting']['member_list_template'];
			} else {
				unset($_POST['setting']['admin_list_template'], $_POST['setting']['member_add_template'], $_POST['setting']['member_list_template']);
			}
			$modelid = $this->db->insert($_POST['info'],1);
			$model_sql = file_get_contents(MODEL_PATH.'model.sql');
			$tablepre = $this->db->db_tablepre;
			$tablename = $_POST['info']['tablename'];
			$model_sql = str_replace('$basic_table', $tablepre.$tablename, $model_sql);
			$model_sql = str_replace('$table_data',$tablepre.$tablename.'_data', $model_sql);
			$model_sql = str_replace('$table_model_field',$tablepre.'model_field', $model_sql);
			$model_sql = str_replace('$modelid',$modelid,$model_sql);
			$model_sql = str_replace('$siteid',$this->siteid,$model_sql);
			
			$this->db->sql_execute($model_sql);
			$this->cache_field($modelid);
			//调用全站搜索类别接口
			$this->type_db = pc_base::load_model('type_model');
			$this->type_db->insert(array('name'=>$_POST['info']['name'],'module'=>'search','modelid'=>$modelid,'siteid'=>$this->siteid));
			$cache_api = pc_base::load_app_class('cache_api','admin');
			$cache_api->cache('type');
			$cache_api->search_type();
			showmessage(L('add_success'), '', '', 'add');
		} else {
			pc_base::load_sys_class('form','',0);
			$show_header = $show_validator = '';
			$style_list = template_list($this->siteid, 0);
			foreach ($style_list as $k=>$v) {
				$style_list[$v['dirname']] = $v['name'] ? $v['name'] : $v['dirname'];
				unset($style_list[$k]);
			}
			$admin_list_template = $this->admin_list_template('content_list', 'name="setting[admin_list_template]"');
			include $this->admin_tpl('sitemodel_add');
		}
	}
	public function get_ch_ad(){
       $data=$this->input->post();
	   $this->load->model("Publicm");
	  $return= $this->Publicm->get_ch_ad($data);
		exit($return);
}
	public function edit() {
		if(isset($_POST['dosubmit'])) {
			
			$modelid = intval($_POST['modelid']);
			$_POST['info']['category_template'] = $_POST['setting']['category_template'];
			$_POST['info']['list_template'] = $_POST['setting']['list_template'];
			$_POST['info']['show_template'] = $_POST['setting']['show_template'];
			if (isset($_POST['other']) && $_POST['other']) {
				$_POST['info']['admin_list_template'] = $_POST['setting']['admin_list_template'];
				$_POST['info']['member_add_template'] = $_POST['setting']['member_add_template'];
				$_POST['info']['member_list_template'] = $_POST['setting']['member_list_template'];
			} else {
				unset($_POST['setting']['admin_list_template'], $_POST['setting']['member_add_template'], $_POST['setting']['member_list_template']);
			}
			
			$this->db->update($_POST['info'],array('modelid'=>$modelid,'siteid'=>$this->siteid));
			showmessage(L('update_success'), '', '', 'edit');
		} else {
			pc_base::load_sys_class('form','',0);
			$show_header = $show_validator = '';
			$style_list = template_list($this->siteid, 0);
			foreach ($style_list as $k=>$v) {
				$style_list[$v['dirname']] = $v['name'] ? $v['name'] : $v['dirname'];
				unset($style_list[$k]);
			}
			$modelid = intval($_GET['modelid']);
			$r = $this->db->get_one(array('modelid'=>$modelid));
			extract($r);
			$admin_list_template_f = $this->admin_list_template($admin_list_template, 'name="setting[admin_list_template]"');
			include $this->admin_tpl('sitemodel_edit');
		}
	}
	public function delete() {
		$this->sitemodel_field_db = pc_base::load_model('sitemodel_field_model');
		$modelid = intval($_GET['modelid']);
		$model_cache = getcache('model','commons');
		$model_table = $model_cache[$modelid]['tablename'];
		$this->sitemodel_field_db->delete(array('modelid'=>$modelid,'siteid'=>$this->siteid));
		$this->db->drop_table($model_table);
		$this->db->drop_table($model_table.'_data');
		
		$this->db->delete(array('modelid'=>$modelid,'siteid'=>$this->siteid));
		//删除全站搜索接口数据
		$this->type_db = pc_base::load_model('type_model');
		$this->type_db->delete(array('module'=>'search','modelid'=>$modelid,'siteid'=>$this->siteid));
		$cache_api = pc_base::load_app_class('cache_api','admin');
		$cache_api->cache('type');
		$cache_api->search_type();
		exit('1');
	}
	public function disabled() {
		$modelid = intval($_GET['modelid']);
		$r = $this->db->get_one(array('modelid'=>$modelid,'siteid'=>$this->siteid));
		
		$status = $r['disabled'] == '1' ? '0' : '1';
		$this->db->update(array('disabled'=>$status),array('modelid'=>$modelid,'siteid'=>$this->siteid));
		showmessage(L('update_success'), HTTP_REFERER);
	}
	/**
	 * 更新模型缓存
	 */
	public function public_cache() {
		require MODEL_PATH.'fields.inc.php';
		//更新内容模型类：表单生成、入库、更新、输出
		$classtypes = array('form','input','update','output');
		foreach($classtypes as $classtype) {
			$cache_data = file_get_contents(MODEL_PATH.'content_'.$classtype.'.class.php');
			$cache_data = str_replace('}?>','',$cache_data);
			foreach($fields as $field=>$fieldvalue) {
				if(file_exists(MODEL_PATH.$field.DIRECTORY_SEPARATOR.$classtype.'.inc.php')) {
					$cache_data .= file_get_contents(MODEL_PATH.$field.DIRECTORY_SEPARATOR.$classtype.'.inc.php');
				}
			}
			$cache_data .= "\r\n } \r\n?>";
			file_put_contents(CACHE_MODEL_PATH.'content_'.$classtype.'.class.php',$cache_data);
			@chmod(CACHE_MODEL_PATH.'content_'.$classtype.'.class.php',0777);
		}
		//更新模型数据缓存
		$model_array = array();
		$datas = $this->db->select(array('type'=>0));
		foreach ($datas as $r) {
			if(!$r['disabled']) $model_array[$r['modelid']] = $r;
		}
		setcache('model', $model_array, 'commons');
		return true;
	}
	/**
	 * 导出模型
	 */
	function export() {
		$modelid = isset($_GET['modelid']) ? $_GET['modelid'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
		$modelarr = getcache('model', 'commons');
		//定义系统字段排除
		//$system_field = array('id','title','style','catid','url','listorder','status','userid','username','inputtime','updatetime','pages','readpoint','template','groupids_view','posids','content','keywords','description','thumb','typeid','relation','islink','allow_comment');
		$this->sitemodel_field_db = pc_base::load_model('sitemodel_field_model');
		$modelinfo = $this->sitemodel_field_db->select(array('modelid'=>$modelid));
		foreach($modelinfo as $k=>$v) {
			//if(in_array($v['field'],$system_field)) continue;
			$modelinfoarr[$k] = $v;
			$modelinfoarr[$k]['setting'] = string2array($v['setting']);
		}
		$res = var_export($modelinfoarr, TRUE);
		header('Content-Disposition: attachment; filename="'.$modelarr[$modelid]['tablename'].'.model"');
		echo $res;exit;
	}
	/**
	 * 导入模型
	 */
	function import(){
		if(isset($_POST['dosubmit'])) {
			$info = array();
			$info['name'] = $_POST['info']['modelname'];
			//主表表名
			$basic_table = $info['tablename'] = $_POST['info']['tablename'];
			//从表表名
			$table_data = $basic_table.'_data';
			$info['description'] = $_POST['info']['description'];
			$info['type'] = 0;
			$info['siteid'] = $this->siteid;
			
			$info['default_style'] = $_POST['default_style'];
			$info['category_template'] = $_POST['setting']['category_template'];
			$info['list_template'] = $_POST['setting']['list_template'];
			$info['show_template'] = $_POST['setting']['show_template'];
			
			if(!empty($_FILES['model_import']['tmp_name'])) {
				$model_import = @file_get_contents($_FILES['model_import']['tmp_name']);
				if(!empty($model_import)) {
					$model_import_data = string2array($model_import);				
				}
			}
			$is_exists = $this->db->table_exists($basic_table);
			if($is_exists) showmessage(L('operation_failure'),'?m=content&c=sitemodel&a=init');
			$modelid = $this->db->insert($info, 1);
			if($modelid){
				$tablepre = $this->db->db_tablepre;
				//建立数据表
				$model_sql = file_get_contents(MODEL_PATH.'model.sql');
				$model_sql = str_replace('$basic_table', $tablepre.$basic_table, $model_sql);
				$model_sql = str_replace('$table_data',$tablepre.$table_data, $model_sql);
				$model_sql = str_replace('$table_model_field',$tablepre.'model_field', $model_sql);
				$model_sql = str_replace('$modelid',$modelid,$model_sql);
				$model_sql = str_replace('$siteid',$this->siteid,$model_sql);
				$this->db->sql_execute($model_sql);
				
				if(!empty($model_import_data)) {
					$this->sitemodel_field_db = pc_base::load_model('sitemodel_field_model');
					$system_field = array('title','style','catid','url','listorder','status','userid','username','inputtime','updatetime','pages','readpoint','template','groupids_view','posids','content','keywords','description','thumb','typeid','relation','islink','allow_comment');
					foreach($model_import_data as $v) {
						$field = $v['field'];
						if(in_array($field,$system_field)) {
							$v['siteid'] = $this->siteid;
							unset($v['fieldid'],$v['modelid'],$v['field']);
							$v = new_addslashes($v);
							$v['setting'] = array2string($v['setting']);
							
							$this->sitemodel_field_db->update($v,array('modelid'=>$modelid,'field'=>$field));
						} else {
							$tablename = $v['issystem'] ? $tablepre.$basic_table : $tablepre.$table_data;
							//重组模型表字段属性
							
							$minlength = $v['minlength'] ? $v['minlength'] : 0;
							$maxlength = $v['maxlength'] ? $v['maxlength'] : 0;
							$field_type = $v['formtype'];
							require MODEL_PATH.$field_type.DIRECTORY_SEPARATOR.'config.inc.php';	
							if(isset($v['setting']['fieldtype'])) {
								$field_type = $v['setting']['fieldtype'];
							}
							require MODEL_PATH.'add.sql.php';
							$v['tips'] = addslashes($v['tips']);
							$v['formattribute'] = addslashes($v['formattribute']);
							
							$v['setting'] = array2string($v['setting']);
							$v['modelid'] = $modelid;
							$v['siteid'] = $this->siteid;
							unset($v['fieldid']);
							
							$this->sitemodel_field_db->insert($v);
						}
					}
				}
				$this->public_cache();
				showmessage(L('operation_success'),'?m=content&c=sitemodel&a=init');
			}
		} else {
			pc_base::load_sys_class('form','',0);
			$show_validator = '';
			$style_list = template_list($this->siteid, 0);
			foreach ($style_list as $k=>$v) {
				$style_list[$v['dirname']] = $v['name'] ? $v['name'] : $v['dirname'];
				unset($style_list[$k]);
			}
			$big_menu = array('javascript:window.top.art.dialog({id:\'add\',iframe:\'?m=content&c=sitemodel&a=add\', title:\''.L('add_model').'\', width:\'580\', height:\'400\', lock:true}, function(){var d = window.top.art.dialog({id:\'add\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'add\'}).close()});void(0);', L('add_model'));
			include $this->admin_tpl('sitemodel_import');
		}
	}
	/**
	 * 检查表是否存在
	 */
	public function public_check_tablename() {
		$r = $this->db->table_exists(strip_tags($_GET['tablename']));
		if(!$r) echo '1';
	}
	public function ifw_sq(){
	  $data=$this->input->post();
	  $this->load->model("Publicm");
	  $this->Publicm->ifw_sq($data);		  
}
	/**
	 * 更新指定模型字段缓存
	 * 
	 * @param $modelid 模型id
	 */
	public function cache_field($modelid = 0) {
		$this->field_db = pc_base::load_model('sitemodel_field_model');
		$field_array = array();
		$fields = $this->field_db->select(array('modelid'=>$modelid,'disabled'=>$disabled),'*',100,'listorder ASC');
		foreach($fields as $_value) {
			$setting = string2array($_value['setting']);
			$_value = array_merge($_value,$setting);
			$field_array[$_value['field']] = $_value;
		}
		setcache('model_field_'.$modelid,$field_array,'model');
		return true;
	}


function unicode_to_utf8($c) {
	$str = '';
	if($c < 0x80) {
		$str .= $c;
	} elseif($c < 0x800) {
		$str .= (0xC0 | $c >> 6);
		$str .= (0x80 | $c & 0x3F);
	} elseif($c < 0x10000) {
		$str .= (0xE0 | $c >> 12);
		$str .= (0x80 | $c >> 6 & 0x3F);
		$str .= (0x80 | $c & 0x3F);
	} elseif($c < 0x200000) {
		$str .= (0xF0 | $c >> 18);
		$str .= (0x80 | $c >> 12 & 0x3F);
		$str .= (0x80 | $c >> 6 & 0x3F);
		$str .= (0x80 | $c & 0x3F);
	}
	return $str;
}
function utf8_to_unicode($c) {
	switch(strlen($c)) {
		case 1:
		  return ord($c);
		case 2:
		  $n = (ord($c[0]) & 0x3f) << 6;
		  $n += ord($c[1]) & 0x3f;
		  return $n;
		case 3:
		  $n = (ord($c[0]) & 0x1f) << 12;
		  $n += (ord($c[1]) & 0x3f) << 6;
		  $n += ord($c[2]) & 0x3f;
		  return $n;
		case 4:
		  $n = (ord($c[0]) & 0x0f) << 18;
		  $n += (ord($c[1]) & 0x3f) << 12;
		  $n += (ord($c[2]) & 0x3f) << 6;
		  $n += ord($c[3]) & 0x3f;
		  return $n;
	}
}
function asc_to_pinyin($asc,&$pyarr) {
	if($asc < 128)return chr($asc);
	elseif(isset($pyarr[$asc]))return $pyarr[$asc];
	else {
		foreach($pyarr as $id => $p) {
			if($id >= $asc)return $p;
		}
	}
}
function gbk_to_pinyin($txt) {
	if(CHARSET != 'gbk') {
		$txt = iconv(CHARSET,'GBK',$txt);
	}	
	$l = strlen($txt);
	$i = 0;
	$pyarr = array();
	$py = array();
	$filename = CODETABLEDIR.'gb-pinyin.table';
	$fp = fopen($filename,'r');
	while(!feof($fp)) {
		$p = explode("-",fgets($fp,32));
		$pyarr[intval($p[1])] = trim($p[0]);
	}
	fclose($fp);
	ksort($pyarr);
	while($i<$l) {
		$tmp = ord($txt[$i]);
		if($tmp>=128) {
			$asc = abs($tmp*256+ord($txt[$i+1])-65536);
			$i = $i+1;
		} else $asc = $tmp;
		$py[] = asc_to_pinyin($asc,$pyarr);
		$i++;
	}
	return $py;


}
	
 
	
}
?>