冯斌斌 vor 1 Jahr
Commit
d5a4ef348d
100 geänderte Dateien mit 18067 neuen und 0 gelöschten Zeilen
  1. 8 0
      .htaccess
  2. 26 0
      404.html
  3. 1491 0
      Ainaphp/Common/common.php
  4. 39 0
      Ainaphp/Conf/Admin/config.php
  5. 12 0
      Ainaphp/Conf/User/config.php
  6. 29 0
      Ainaphp/Conf/config.php
  7. 8 0
      Ainaphp/Conf/tags.php
  8. 4 0
      Ainaphp/Lang/cn/Home_order.php
  9. 6 0
      Ainaphp/Lang/cn/User.php
  10. 4 0
      Ainaphp/Lang/cn/User_order.php
  11. 5 0
      Ainaphp/Lang/cn/common.php
  12. 5 0
      Ainaphp/Lang/en/User.php
  13. 5 0
      Ainaphp/Lang/en/common.php
  14. 21 0
      Ainaphp/Lang/zh-cn/Admin_attachment.php
  15. 48 0
      Ainaphp/Lang/zh-cn/Admin_category.php
  16. 83 0
      Ainaphp/Lang/zh-cn/Admin_config.php
  17. 37 0
      Ainaphp/Lang/zh-cn/Admin_createhtml.php
  18. 11 0
      Ainaphp/Lang/zh-cn/Admin_dbsource.php
  19. 46 0
      Ainaphp/Lang/zh-cn/Admin_field.php
  20. 29 0
      Ainaphp/Lang/zh-cn/Admin_index.php
  21. 27 0
      Ainaphp/Lang/zh-cn/Admin_main.php
  22. 41 0
      Ainaphp/Lang/zh-cn/Admin_module.php
  23. 100 0
      Ainaphp/Lang/zh-cn/Admin_order.php
  24. 56 0
      Ainaphp/Lang/zh-cn/Admin_payment.php
  25. 17 0
      Ainaphp/Lang/zh-cn/Admin_role.php
  26. 25 0
      Ainaphp/Lang/zh-cn/Admin_slide.php
  27. 21 0
      Ainaphp/Lang/zh-cn/Admin_template.php
  28. 6 0
      Ainaphp/Lang/zh-cn/Admin_type.php
  29. 13 0
      Ainaphp/Lang/zh-cn/Admin_urlrule.php
  30. 227 0
      Ainaphp/Lang/zh-cn/common.php
  31. 84 0
      Ainaphp/Lib/Action/Admin/AccessAction.class.php
  32. 206 0
      Ainaphp/Lib/Action/Admin/AttachmentAction.class.php
  33. 66 0
      Ainaphp/Lib/Action/Admin/BlockAction.class.php
  34. 389 0
      Ainaphp/Lib/Action/Admin/CategoryAction.class.php
  35. 150 0
      Ainaphp/Lib/Action/Admin/ConfigAction.class.php
  36. 365 0
      Ainaphp/Lib/Action/Admin/ContentAction.class.php
  37. 573 0
      Ainaphp/Lib/Action/Admin/CreatehtmlAction.class.php
  38. 253 0
      Ainaphp/Lib/Action/Admin/DatabaseAction.class.php
  39. 18 0
      Ainaphp/Lib/Action/Admin/DbsourceAction.class.php
  40. 15 0
      Ainaphp/Lib/Action/Admin/EmptyAction.class.php
  41. 271 0
      Ainaphp/Lib/Action/Admin/FieldAction.class.php
  42. 185 0
      Ainaphp/Lib/Action/Admin/IndexAction.class.php
  43. 102 0
      Ainaphp/Lib/Action/Admin/LangAction.class.php
  44. 26 0
      Ainaphp/Lib/Action/Admin/LogAction.class.php
  45. 181 0
      Ainaphp/Lib/Action/Admin/LoginAction.class.php
  46. 169 0
      Ainaphp/Lib/Action/Admin/MainAction.class.php
  47. 97 0
      Ainaphp/Lib/Action/Admin/MenuAction.class.php
  48. 174 0
      Ainaphp/Lib/Action/Admin/ModuleAction.class.php
  49. 135 0
      Ainaphp/Lib/Action/Admin/NodeAction.class.php
  50. 18 0
      Ainaphp/Lib/Action/Admin/PosidAction.class.php
  51. 39 0
      Ainaphp/Lib/Action/Admin/RoleAction.class.php
  52. 231 0
      Ainaphp/Lib/Action/Admin/SlideAction.class.php
  53. 194 0
      Ainaphp/Lib/Action/Admin/TemplateAction.class.php
  54. 52 0
      Ainaphp/Lib/Action/Admin/ThemeAction.class.php
  55. 133 0
      Ainaphp/Lib/Action/Admin/TypeAction.class.php
  56. 17 0
      Ainaphp/Lib/Action/Admin/UrlruleAction.class.php
  57. 126 0
      Ainaphp/Lib/Action/Admin/UserAction.class.php
  58. 803 0
      Ainaphp/Lib/Action/AdminbaseAction.class.php
  59. 418 0
      Ainaphp/Lib/Action/BaseAction.class.php
  60. 401 0
      Ainaphp/Lib/Action/BaseAction1.class.php
  61. 149 0
      Ainaphp/Lib/Action/Home/AjaxAction.class.php
  62. 62 0
      Ainaphp/Lib/Action/Home/EmptyAction.class.php
  63. 64 0
      Ainaphp/Lib/Action/Home/FormatAction.class.php
  64. 65 0
      Ainaphp/Lib/Action/Home/IndexAction.class.php
  65. 105 0
      Ainaphp/Lib/Action/Home/SearchAction.class.php
  66. 85 0
      Ainaphp/Lib/Behavior/CheckLangBehavior.class.php
  67. 21 0
      Ainaphp/Lib/Model/Admin/AccessModel.class.php
  68. 10 0
      Ainaphp/Lib/Model/Admin/CategoryModel.class.php
  69. 20 0
      Ainaphp/Lib/Model/Admin/FieldModel.class.php
  70. 12 0
      Ainaphp/Lib/Model/Admin/MenuModel.class.php
  71. 12 0
      Ainaphp/Lib/Model/Admin/NodeModel.class.php
  72. 11 0
      Ainaphp/Lib/Model/Admin/RoleModel.class.php
  73. 50 0
      Ainaphp/Lib/Model/Admin/UserModel.class.php
  74. 154 0
      Ainaphp/Lib/ORG/Cxml.class.php
  75. 643 0
      Ainaphp/Lib/ORG/Form.class.php
  76. 537 0
      Ainaphp/Lib/ORG/Http.class.php
  77. 756 0
      Ainaphp/Lib/ORG/Image.class.php
  78. 63 0
      Ainaphp/Lib/ORG/Online.class.php
  79. 2674 0
      Ainaphp/Lib/ORG/PHPMailer.class.php
  80. 147 0
      Ainaphp/Lib/ORG/Page.class.php
  81. 165 0
      Ainaphp/Lib/ORG/Page_home.class.php
  82. 489 0
      Ainaphp/Lib/ORG/Phpzip.class.php
  83. 240 0
      Ainaphp/Lib/ORG/RBAC.class.php
  84. 123 0
      Ainaphp/Lib/ORG/String.class.php
  85. 68 0
      Ainaphp/Lib/ORG/SysCrypt.class.php
  86. 93 0
      Ainaphp/Lib/ORG/Tree.class.php
  87. 631 0
      Ainaphp/Lib/ORG/UploadFile.class.php
  88. 412 0
      Ainaphp/Lib/ORG/class.pop3.php
  89. 957 0
      Ainaphp/Lib/ORG/class.smtp.php
  90. 154 0
      Ainaphp/Lib/Pay/Alipay.class.php
  91. 34 0
      Ainaphp/Lib/Pay/Balance.class.php
  92. 35 0
      Ainaphp/Lib/Pay/Bank.class.php
  93. 101 0
      Ainaphp/Lib/Pay/Chinabank.class.php
  94. 78 0
      Ainaphp/Tpl/Admin/Default/Access_index.html
  95. 78 0
      Ainaphp/Tpl/Admin/Default/Admin_header.html
  96. 6 0
      Ainaphp/Tpl/Admin/Default/Attachment_filelist.html
  97. 161 0
      Ainaphp/Tpl/Admin/Default/Attachment_index.html
  98. 30 0
      Ainaphp/Tpl/Admin/Default/Block_edit.html
  99. 32 0
      Ainaphp/Tpl/Admin/Default/Block_index.html
  100. 199 0
      Ainaphp/Tpl/Admin/Default/Category_edit.html

+ 8 - 0
.htaccess

@@ -0,0 +1,8 @@
+Options +FollowSymLinks
+RewriteEngine On
+RewriteCond %{HTTP_HOST} ^bangju.com 
+RewriteRule ^(.*)$ http://www.bangju.com/$1 [R=permanent,L]
+RewriteCond %{REQUEST_FILENAME} !-f
+RewriteCond %{REQUEST_FILENAME} !-d
+RewriteRule ^(.*)$ /index.php?s=$1 [QSA,PT,L]
+RewriteRule ^(.*)Ainaphp/Tpl/(.*).html$ /403.html [QSA,PT,L]

+ 26 - 0
404.html

@@ -0,0 +1,26 @@
+<!doctype html>
+<html>
+<head>
+<meta charset="utf-8">
+<meta http-equiv="X-UA-Compatible" content="IE=edge">
+<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
+<title>404</title>
+<style>
+	body{
+		background-color:#444;
+		font-size:14px;
+	}
+	h3{
+		font-size:60px;
+		color:#eee;
+		text-align:center;
+		padding-top:30px;
+		font-weight:normal;
+	}
+</style>
+</head>
+
+<body>
+<h3>404,您请求的文件不存在!</h3>
+</body>
+</html>

+ 1491 - 0
Ainaphp/Common/common.php

@@ -0,0 +1,1491 @@
+<?php
+/**
+ *
+ * Common.php (项目公共函数库)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+
+//判断是否为移动端
+function is_mobile() {
+	$user_agent = $_SERVER['HTTP_USER_AGENT'];
+	$mobile_agents = Array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi","android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio","au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu","cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ","fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi","htc","huawei","hutchison","inno","ipaq","ipod","jbrowser","kddi","kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo","mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mot-","moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia","nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-","playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo","samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank","sony","spice","sprint","spv","symbian","talkabout","tcl-","teleca","telit","tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin","vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce","wireless","xda","xde","zte");
+	$is_mobile = false;
+	foreach ($mobile_agents as $device) {
+		if (stristr($user_agent, $device)) {
+			$is_mobile = true;
+			break;
+		}
+	}
+	return $is_mobile;
+}
+//判断是否为微信
+function is_weixin(){
+	if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
+	  return true;
+	}
+	  return false;
+}
+//curl解析json
+function http_request_json($url){
+        $ch = curl_init();
+        curl_setopt($ch, CURLOPT_URL, $url);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+        $result = curl_exec($ch);
+        curl_close($ch);
+        return $result;
+}
+function fieldoption($fields,$value=null,$space=''){
+	$options = explode("\n",$fields['setup']['options']);
+	foreach($options as $r) {
+		$v = explode("|",$r);
+		$k = trim($v[1]);
+		$optionsarr[$k] = $v[0];
+	}
+	if(isset($value)){
+		if(strpos($value,',')){
+			$value =explode(",",$value);
+			$data=array();
+			foreach((array)$value as $val){
+			$data[]= $optionsarr[$val];
+			}
+			if($space!=''){
+			return implode(stripcslashes($space),$data);
+			}else{
+			return $data;
+			}
+		}else{
+			return $optionsarr[$value];
+		}
+	}else{
+		return $optionsarr;
+	}
+}
+
+function picstoarr($str=''){
+	$data=array();
+	$v = explode(":::",$str);
+	foreach((array)$v as $r){
+		$r=explode('|',$r);
+		$res['file']=$r[0];
+		$res['desc']=$r[1];
+		$data[]=$res;
+	}
+	return $data;
+}
+
+function get_arrparentid($pid, $array=array(),$arrparentid='') {
+		if(!is_array($array) || !isset($array[$pid])) return $pid;
+		$parentid = $array[$pid]['parentid'];
+		$arrparentid = $arrparentid ? $parentid.','.$arrparentid : $parentid;
+		if($parentid) {
+			$arrparentid = get_arrparentid($parentid,$array, $arrparentid);
+		}else{
+			$data = array();
+			$data['bid'] = $pid;
+			$data['arrparentid'] = $arrparentid;
+		}
+
+		return $arrparentid;
+}
+
+function getform($form,$info,$value=''){
+	return  $form->$info['type']($info,$value);
+}
+
+function getvalidate($info){
+        $validate_data=array();
+        if($info['minlength']) $validate_data['minlength'] = ' minlength:'.$info['minlength'];
+		if($info['maxlength']) $validate_data['maxlength'] = ' maxlength:'.$info['maxlength'];
+		if($info['required']) $validate_data['required'] = ' required:true';
+		if($info['pattern']) $validate_data['pattern'] = ' '.$info['pattern'].':true';
+        if($info['errormsg']) $errormsg = ' title="'.$info['errormsg'].'"';
+        $validate= implode(',',$validate_data);
+        $validate= $validate ? 'validate="'.$validate.'" ' : '';
+        $parseStr = $validate.$errormsg;
+        return $parseStr;
+}
+
+function sendmail($tomail,$subject,$body,$config=''){
+
+		if(!$config)$config = F('Config');
+
+		import("@.ORG.PHPMailer");
+		$mail = new PHPMailer();
+
+		if($config['mail_type']==1){
+			$mail->IsSMTP();
+		}elseif($config['mail_type']==2){
+			$mail->IsMail();
+		}else{
+			if($config['sendmailpath']){
+				$mail->Sendmail =$config['mail_sendmail'];
+			}else{
+				$mail->Sendmail =ini_get('sendmail_path');
+			}
+			$mail->IsSendmail();
+		}
+		if($config['mail_auth']){
+			$mail->SMTPAuth = true; // 开启SMTP认证
+		}else{
+			$mail->SMTPAuth = false; // 开启SMTP认证
+		}
+
+		$mail->PluginDir=LIB_PATH."ORG/";
+		$mail->CharSet='utf-8';
+		$mail->SMTPDebug  = false;        // 改为2可以开启调试
+		$mail->Host = $config['mail_server'];      // GMAIL的SMTP
+		//$mail->SMTPSecure = "ssl"; // 设置连接服务器前缀
+		//$mail->Encoding = "base64";
+		$mail->Port = $config['mail_port'];    // GMAIL的SMTP端口号
+		$mail->Username = $config['mail_user']; // GMAIL用户名,必须以@gmail结尾
+		$mail->Password = $config['mail_password']; // GMAIL密码
+		//$mail->From ="coo@ainatec.com";
+		//$mail->FromName = "Aina系统";
+		$mail->SetFrom($config['mail_from'], $config['site_name']);     //发送者邮箱
+		$mail->AddAddress($tomail); //可同时发多个
+		//$mail->AddReplyTo('287804931@qq.com', 'ainaphp'); //回复到这个邮箱
+		//$mail->WordWrap = 50; // 设定 word wrap
+		//$mail->AddAttachment("/var/tmp/file.tar.gz"); // 附件1
+		//$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // 附件2
+		$mail->IsHTML(true); // 以HTML发送
+		$mail->Subject = $subject;
+		$mail->Body = $body;
+		//$mail->AltBody = "This is the body when user views in plain text format";		//纯文字时的Body
+		if(!$mail->Send())
+		{
+			return false;
+		}else{
+			return true;
+		}
+}
+
+function delattach($map=''){
+		$model = M('Attachment');
+		$att= $model->field('aid,filepath')->where($map)->select();
+		$aids=array();
+		foreach((array)$att as $key=> $r){
+			$aids[]=$r['aid'];
+			@unlink(__ROOT__.$r['filepath']);
+		}
+		$r =$model->delete(implode(',',$aids));
+		return  false!==$r ? true : false;
+}
+
+function template_file($module='',$path='',$ext='html'){
+	$sysConfig = F('sys.config');
+	$path= $path ? $path : TMPL_PATH.'Home/'.$sysConfig['DEFAULT_THEME'].'/';
+	$tempfiles = dir_list($path,$ext);
+	foreach ($tempfiles as $key=>$file){
+		$dirname = basename($file);
+		if($module){
+			if(strstr($dirname,$module.'_')) {
+				$arr[$key]['name'] =  substr($dirname,0,strrpos($dirname, '.'));
+				$arr[$key]['value'] =  substr($arr[$key]['name'],strpos($arr[$key]['name'], '_')+1);
+				$arr[$key]['filename'] = $dirname;
+				$arr[$key]['filepath'] = $file;
+			}
+		}else{
+			$arr[$key]['name'] = substr($dirname,0,strrpos($dirname, '.'));
+			$arr[$key]['value'] =  substr($arr[$key]['name'],strpos($arr[$key]['name'], '_')+1);
+			$arr[$key]['filename'] = $dirname;
+			$arr[$key]['filepath'] = $file;
+		}
+	}
+	return  $arr;
+}
+
+function fileext($filename) {
+	return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
+}
+
+function dir_path($path) {
+	$path = str_replace('\\', '/', $path);
+	if(substr($path, -1) != '/') $path = $path.'/';
+	return $path;
+}
+
+function dir_create($path, $mode = 0777) {
+	if(is_dir($path)) return TRUE;
+	$ftp_enable = 0;
+	$path = dir_path($path);
+	$temp = explode('/', $path);
+	$cur_dir = '';
+	$max = count($temp) - 1;
+	for($i=0; $i<$max; $i++) {
+		$cur_dir .= $temp[$i].'/';
+		if (@is_dir($cur_dir)) continue;
+		@mkdir($cur_dir, $mode,true);
+		@chmod($cur_dir, $mode);
+	}
+	return is_dir($path);
+}
+
+function mk_dir($dir, $mode = 0777) {
+    if (is_dir($dir) || @mkdir($dir, $mode))
+        return true;
+    if (!mk_dir(dirname($dir), $mode))
+        return false;
+    return @mkdir($dir, $mode);
+}
+
+function dir_copy($fromdir, $todir) {
+	$fromdir = dir_path($fromdir);
+	$todir = dir_path($todir);
+	if (!is_dir($fromdir)) return FALSE;
+	if (!is_dir($todir)) dir_create($todir);
+	$list = glob($fromdir.'*');
+	if (!empty($list)) {
+		foreach($list as $v) {
+			$path = $todir.basename($v);
+			if(is_dir($v)) {
+				dir_copy($v, $path);
+			} else {
+				copy($v, $path);
+				@chmod($path, 0777);
+			}
+		}
+	}
+    return TRUE;
+}
+
+function dir_list($path, $exts = '', $list= array()) {
+	$path = dir_path($path);
+	$files = glob($path.'*');
+	foreach($files as $v) {
+		$fileext = fileext($v);
+		if (!$exts || preg_match("/\.($exts)/i", $v)) {
+			$list[] = $v;
+			if (is_dir($v)) {
+				$list = dir_list($v, $exts, $list);
+			}
+		}
+	}
+	return $list;
+}
+
+function dir_tree($dir, $parentid = 0, $dirs = array()) {
+	if ($parentid == 0) $id = 0;
+	$list = glob($dir.'*');
+	foreach($list as $v) {
+		if (is_dir($v)) {
+            $id++;
+			$dirs[$id] = array('id'=>$id,'parentid'=>$parentid, 'name'=>basename($v), 'dir'=>$v.'/');
+			$dirs = dir_tree($v.'/', $id, $dirs);
+		}
+	}
+	return $dirs;
+}
+
+
+function dir_delete($dir) {
+	//$dir = dir_path($dir);
+	if (!is_dir($dir)) return FALSE;
+	$handle = opendir($dir); //打开目录
+	while(($file = readdir($handle)) !== false) {
+	        if($file == '.' || $file == '..')continue;
+			$d = $dir.DIRECTORY_SEPARATOR.$file;
+	        is_dir($d) ? dir_delete($d) : @unlink($d);
+	}
+	closedir($handle);
+	return @rmdir($dir);
+}
+
+function toDate($time, $format = 'Y-m-d H:i:s') {
+	if (empty ( $time )) {
+		return '';
+	}
+	$format = str_replace ( '#', ':', $format );
+	return date ($format, $time );
+}
+function savecache($name = '',$id='') {
+	unlink(RUNTIME_FILE);
+	$Model = M ( $name );
+	if($name=='Lang'){
+		$list = $Model->order('listorder')->select ();
+		$pkid = $Model->getPk ();
+		$data = array ();
+		foreach ( $list as $key => $val ) {
+			$data [$val ['mark']] = $val;
+		}
+		F($name,$data);
+
+	}elseif($name=='Module'){
+		$list = $Model->order('listorder')->select ();
+		$pkid = $Model->getPk ();
+		$data = array ();
+		foreach ( $list as $key => $val ){
+			$data [$val [$pkid]] = $val;
+			$smalldata[$val['name']] =  $val [$pkid];
+		}
+		F($name,$data);
+		F('Mod',$smalldata);
+		//savecache
+
+	}elseif($name=='Config'){
+
+		$list = $Model->select ();
+		$data=$sysdata=$temp=$memberconfig=array();
+		foreach($list as $key=>$r) {
+			if($r['groupid']==6){
+				$sysdata[$r['varname']]=$r['value'];
+			}elseif($r['groupid']==3){
+				if(APP_LANG)
+					$memberconfig_temp[$r['lang']][$r['varname']]=$r['value'];
+				else
+					$memberconfig[$r['varname']]=$r['value'];
+			}else{
+				if(APP_LANG)
+					if($r['lang']){$temp[$r['lang']][$r['varname']]=$r['value'];}else{$data[$r['varname']]=$r['value'];}
+				else
+					$data[$r['varname']]=$r['value'];
+			}
+		}
+		if(APP_LANG){
+			$lang=F('Lang');
+			foreach((array)$lang as $key=>$r){
+				$data1=array();
+				$data1 = array_merge($temp[$r['id']],$data);
+				F('Config_'.$key,$data1);
+				F('member.config_'.$key,$memberconfig_temp[$r['id']]);
+				if(empty($data1['HOME_ISHTML'])){
+					@unlink('./index.html');
+					@unlink('./'.$key.'/index.html');
+				}
+			}
+		}else{
+			F('Config',$data);
+			F('member.config',$memberconfig);
+			if(empty($data['HOME_ISHTML']))@unlink('./index.html');
+		}
+
+		$langs = M('Lang')->field('mark')->select();foreach((array)$langs as $r ) $lang1[]=$r['mark'];
+		$sysdata['LANG_LIST'] = 'zh-cn,'.implode(',',$lang1);
+
+		F('sys.config',$sysdata);
+
+	}elseif($name=='Category'){
+
+		$data=$smalldata=$temp=array();
+
+		if(APP_LANG){
+			$lang=F('Lang');
+			foreach((array)$lang as $key=>$r){
+				$langid =$r['id'];
+				if($langid){
+					$lang = $key;
+					$list = $Model->where('lang='.$langid)->order('listorder')->select ();
+					$pkid = $Model->getPk ();
+					$data = array ();
+					foreach ( $list as $key => $val ) {
+						$data [$val [$pkid]] = $val;
+						$smalldata[$val['catdir']] =  $val [$pkid];
+					}
+					F('Category_'.$lang,$data);
+					F('Cat_'.$lang,$smalldata);
+				}
+			}
+		}else{
+			$list = $Model->order('listorder')->select ();
+			$pkid = $Model->getPk ();
+			$data = array ();
+			foreach ( $list as $key => $val ) {
+				$data [$val [$pkid]] = $val;
+				$smalldata[$val['catdir']] =  $val [$pkid];
+			}
+			F($name,$data);
+			F('Cat',$smalldata);
+		}
+
+	}elseif($name=='Field'){
+		if($id){
+			$list = $Model->order('listorder')->where('moduleid='.$id)->select ();
+			$pkid = 'field';
+			$data = array ();
+			foreach ( $list as $key => $val ) {
+				$data [$val [$pkid]] = $val;
+			}
+			$name=$id.'_'.$name;
+			F($name,$data);
+		}else{
+			$module = F('Module');
+			foreach ( $module as $key => $val ) {
+				savecache($name,$key);
+			}
+		}
+	}elseif($name=='Dbsource'){
+		$list = $Model->select ();
+		$data = array ();
+		foreach ( $list as $key => $val ) {
+			$data [$val ['name']] = $val;
+		}
+		F($name,$data);
+	}else{
+		$list = $Model->order('listorder')->select ();
+		$pkid = $Model->getPk ();
+		$data = array ();
+		foreach ( $list as $key => $val ) {
+			$data [$val [$pkid]] = $val;
+		}
+		F($name,$data);
+		if($name=='Urlrule'){
+			$config = F('sys.config');
+			if($config['URL_URLRULE'])routes_cache($config['URL_URLRULE']);
+		}
+	}
+
+	return true;
+}
+
+
+function checkfield($fields,$postdata){
+		foreach ( $postdata as $key => $val ) {
+				$setup=$fields[$key]['setup'];
+
+				if(!empty($fields[$key]['required']) && empty($postdata[$key])) return '';
+				//$setup=string2array($fields[$key]['setup']);
+				if($setup['multiple'] || $setup['inputtype']=='checkbox' || $fields[$key]['type']=='checkbox'){
+					//$postdata[$key] =  safe_replace(strip_tags($postdata[$key]));
+					$postdata[$key] = implode(',',$postdata[$key]);
+				}elseif($fields[$key]['type']=='datetime'){
+					$postdata[$key] =strtotime($postdata[$key]);
+				}elseif($fields[$key]['type']=='textarea'){
+					$postdata[$key]=addslashes_array($postdata[$key]);
+				}elseif($fields[$key]['type']=='images' || $fields[$key]['type']=='files'){
+					$name = $key.'_name';
+					$arrdata =array();
+					foreach($postdata[$key] as $k=>$res){
+						if(!empty($postdata[$key][$k])) $arrdata[]= safe_replace(strip_tags($postdata[$key][$k].'|'.$postdata[$name][$k]));
+					}
+					$postdata[$key]=implode(':::',$arrdata);
+				}elseif($fields[$key]['type']=='editor'){
+					//自动提取摘要
+					if(isset($postdata['add_description']) && $postdata['description'] == '' && isset($postdata['content'])) {
+						$content = stripslashes($postdata['content']);
+						$description_length = intval($postdata['description_length']);
+						$postdata['description'] = str_cut(str_replace(array("\r\n","\t",'[page]','[/page]','&ldquo;','&rdquo;'), '', strip_tags($content)),$description_length);
+						$postdata['description'] = addslashes_array($postdata['description']);
+					}
+					//自动提取缩略图
+					if(isset($postdata['auto_thumb']) && $postdata['thumb'] == '' && isset($postdata['content'])) {
+						$content = $content ? $content : stripslashes($postdata['content']);
+						$auto_thumb_no = intval($postdata['auto_thumb_no']) * 3;
+						if(preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)) {
+							$postdata['thumb'] = $matches[$auto_thumb_no][0];
+						}
+					}
+				}elseif($fields[$key]['type']=='title' || $fields[$key]['type']=='text'){
+					$postdata[$key] =  safe_replace(strip_tags($postdata[$key]));
+				}
+		}
+		return $postdata;
+}
+
+function string2array($info) {
+        if($info == '') return array();
+        $info=stripcslashes($info);
+        eval("\$r = $info;");
+        return $r;
+}
+
+
+function array2string($info) {
+	if($info == '') return '';
+	if(!is_array($info)) $string = stripslashes($info);
+	foreach($info as $key => $val) $string[$key] = stripslashes($val);
+	return addslashes(var_export($string, TRUE));
+}
+
+/**
+	 +----------------------------------------------------------
+ * 产生随机字串,可用来自动生成密码
+ * 默认长度6位 字母和数字混合 支持中文
+	 +----------------------------------------------------------
+ * @param string $len 长度
+ * @param string $type 字串类型
+ * 0 字母 1 数字 其它 混合
+ * @param string $addChars 额外字符
+	 +----------------------------------------------------------
+ * @return string
+	 +----------------------------------------------------------
+ */
+function rand_string($len = 6, $type = '', $addChars = '') {
+	$str = '';
+	switch ($type) {
+		case 0 :
+			$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars;
+			break;
+		case 1 :
+			$chars = str_repeat ( '0123456789', 3 );
+			break;
+		case 2 :
+			$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars;
+			break;
+		case 3 :
+			$chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars;
+			break;
+		default :
+			// 默认去掉了容易混淆的字符oOLl和数字01,要添加请使用addChars参数
+			$chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars;
+			break;
+	}
+	if ($len > 10) { //位数过长重复字符串一定次数
+		$chars = $type == 1 ? str_repeat ( $chars, $len ) : str_repeat ( $chars, 5 );
+	}
+	if ($type != 4) {
+		$chars = str_shuffle ( $chars );
+		$str = substr ( $chars, 0, $len );
+	} else {
+		// 中文随机字
+		for($i = 0; $i < $len; $i ++) {
+			$str .= msubstr ( $chars, floor ( mt_rand ( 0, mb_strlen ( $chars, 'utf-8' ) - 1 ) ), 1 );
+		}
+	}
+	return $str;
+}
+function sysmd5($str,$key='',$type='sha1'){
+	$key =  $key ?  $key : C('ADMIN_ACCESS');
+	return hash ( $type, $str.$key );
+}
+function pwdHash($password, $type = 'md5') {
+	return hash ( $type, $password );
+}
+
+/**
+* @param string $string 原文或者密文
+* @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE
+* @param string $key 密钥
+* @param int $expiry 密文有效期, 加密时候有效, 单位 秒,0 为永久有效
+* @return string 处理后的 原文或者 经过 base64_encode 处理后的密文
+*
+* @example
+*
+*  $a = authcode('abc', 'ENCODE', 'key');
+*  $b = authcode($a, 'DECODE', 'key');  // $b(abc)
+*
+*  $a = authcode('abc', 'ENCODE', 'key', 3600);
+*  $b = authcode('abc', 'DECODE', 'key'); // 在一个小时内,$b(abc),否则 $b 为空
+*/
+function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0)
+{
+	$ckey_length = 4;
+	// 随机密钥长度 取值 0-32;
+	// 加入随机密钥,可以令密文无任何规律,即便是原文和密钥完全相同,加密结果也会每次不同,增大破解难度。
+	// 取值越大,密文变动规律越大,密文变化 = 16 的 $ckey_length 次方
+	// 当此值为 0 时,则不产生随机密钥
+
+
+	$keya = md5(substr($key, 0, 16));
+	$keyb = md5(substr($key, 16, 16));
+	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
+
+	$cryptkey = $keya.md5($keya.$keyc);
+	$key_length = strlen($cryptkey);
+
+	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
+	$string_length = strlen($string);
+
+	$result = '';
+	$box = range(0, 255);
+
+	$rndkey = array();
+	for($i = 0; $i <= 255; $i++)
+	{
+		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
+	}
+
+	for($j = $i = 0; $i < 256; $i++)
+	{
+		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
+		$tmp = $box[$i];
+		$box[$i] = $box[$j];
+		$box[$j] = $tmp;
+	}
+
+	for($a = $j = $i = 0; $i < $string_length; $i++)
+	{
+		$a = ($a + 1) % 256;
+		$j = ($j + $box[$a]) % 256;
+		$tmp = $box[$a];
+		$box[$a] = $box[$j];
+		$box[$j] = $tmp;
+		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
+	}
+
+	if($operation == 'DECODE')
+	{
+		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16))
+		{
+			return substr($result, 26);
+		}
+		else
+		{
+			return '';
+		}
+	}
+	else
+	{
+		return $keyc.str_replace('=', '', base64_encode($result));
+	}
+}
+
+
+
+//字符串截取
+function str_cut($sourcestr,$cutlength,$suffix='...')
+{
+	$str_length = strlen($sourcestr);
+	if($str_length <= $cutlength) {
+		return $sourcestr;
+	}
+	$returnstr='';
+	$n = $i = $noc = 0;
+	while($n < $str_length) {
+			$t = ord($sourcestr[$n]);
+			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
+				$i = 1; $n++; $noc++;
+			} elseif(194 <= $t && $t <= 223) {
+				$i = 2; $n += 2; $noc += 2;
+			} elseif(224 <= $t && $t <= 239) {
+				$i = 3; $n += 3; $noc += 2;
+			} elseif(240 <= $t && $t <= 247) {
+				$i = 4; $n += 4; $noc += 2;
+			} elseif(248 <= $t && $t <= 251) {
+				$i = 5; $n += 5; $noc += 2;
+			} elseif($t == 252 || $t == 253) {
+				$i = 6; $n += 6; $noc += 2;
+			} else {
+				$n++;
+			}
+			if($noc >= $cutlength) {
+				break;
+			}
+	}
+	if($noc > $cutlength) {
+			$n -= $i;
+	}
+	$returnstr = substr($sourcestr, 0, $n);
+
+
+	if ( substr($sourcestr, $n, 6)){
+          $returnstr = $returnstr . $suffix;//超过长度时在尾处加上省略号
+      }
+	return $returnstr;
+}
+
+function IP($ip='',$file='UTFWry.dat') {
+	import("@.ORG.IpLocation");
+	$iplocation = new IpLocation($file);
+	$location = $iplocation->getlocation($ip);
+	return $location;
+}
+
+function byte_format($input, $dec=0)
+{
+  $prefix_arr = array("B", "K", "M", "G", "T");
+  $value = round($input, $dec);
+  $i=0;
+  while ($value>1024)
+  {
+     $value /= 1024;
+     $i++;
+  }
+  $return_str = round($value, $dec).$prefix_arr[$i];
+  return $return_str;
+}
+
+/**
+ +----------------------------------------------------------
+ * 获取登录验证码 默认为4位数字
+ +----------------------------------------------------------
+ * @param string $fmode 文件名
+ +----------------------------------------------------------
+ * @return string
+ +----------------------------------------------------------
+ */
+function build_verify ($length=4,$mode=1) {
+    return rand_string($length,$mode);
+}
+
+
+function make_urlrule($url,$lang,$action,$MOREREQUEST=''){
+		preg_match_all ("/{([\w\$]+)}/",$url, $matches);
+		//$REQUEST= implode(',',$matches[0]);
+
+		if(strstr($url,'{$parentdir') && C('URL_PATHINFO_DEPR')=='/'){
+			if(APP_LANG){
+				foreach((array)$lang as $r){
+					$Category = F('Category_'.$r);
+					foreach((array)$Category as $key =>$r){
+						if($r['parentid']==0)$pcatdir[]=$r['catdir'];
+					}
+				}
+			}else{
+				$Category = F('Category');
+				foreach((array)$Category as $key =>$r){
+					if($r['parentid']==0)$pcatdir[]=$r['catdir'];
+				}
+			}
+			unset($Category);
+			$parent_rule = '('.implode('|',$pcatdir).')\/';
+			//if(preg_match("/^[\w]+$/",$str)){ }
+		}
+
+		$REQUEST=str_replace(array('{$parentdir}','{$module}','{$moduleid}','{$catdir}','{$year}','{$month}','{$day}','{$catid}','{$id}','{$page}'),array('','module','moduleid','catdir','year','month','day','catid','id',C('VAR_PAGE')),$matches[0]);
+		$rule=str_replace(array('{$parentdir}','{$module}','{$moduleid}','{$catdir}','{$year}','{$month}','{$day}','{$catid}','{$id}','{$page}','/',C('URL_HTML_SUFFIX')),array('','([A-Z]{1}[a-z]+)','(\d+)','([\w^_]+)','(\d+)','(\d+)','(\d+)','(\d+)','(\d+)','(\d+)','\/',''),$url);
+
+		$i=0;$j=1;$k=2;$n=3;$m=4;
+		foreach($REQUEST as $key =>$r){
+			if($r){
+			$i=$i+1;
+			$request .=$r.'=:'.$i.'&';
+			$j=$j+1;
+			$request_lang .=$r.'=:'.$j.'&';
+			$k=$k+1;
+			$request_lang_2 .=$r.'=:'.$k.'&'; //二级
+			$n=$n+1;
+			$request_lang_3 .=$r.'=:'.$n.'&'; //三级
+			}
+		}
+
+		if(APP_LANG){
+			$langrule = '('.implode('|',$lang).')\/';
+
+			if($parent_rule){
+				$data[] = '\'/^'.$langrule.$parent_rule.'([\w^_]+)\/'.$rule.'$/\' => \'Urlrule/'.$action.'?l=:1&parentdir=:2&'.$request_lang_3.$MOREREQUEST.$langrequest.'\'';
+				$data[] = '\'/^'.$langrule.$parent_rule.$rule.'$/\' => \'Urlrule/'.$action.'?l=:1&parentdir=:2&'.$request_lang_2.$MOREREQUEST.$langrequest.'\'';
+				$data[] = '\'/^'.$parent_rule.'([\w^_]+)\/'.$rule.'$/\' => \'Urlrule/'.$action.'?parentdir=:1&'.$request_lang_2.$MOREREQUEST.$langrequest.'\'';
+				$data[] = '\'/^'.$parent_rule.$rule.'$/\' => \'Urlrule/'.$action.'?parentdir=:1&'.$request_lang.$MOREREQUEST.$langrequest.'\'';
+
+				if(strstr($url,'{$page')){
+					$data[] = '\'/^'.$langrule.$parent_rule.'(\d+)$/\' => \'Urlrule/'.$action.'?l=:1&catdir=:2&p=:3\'';
+					$data[] = '\'/^'.$parent_rule.'(\d+)$/\' => \'Urlrule/'.$action.'?catdir=:1&p=:2\'';
+				}else{
+					$data[] = '\'/^'.$langrule.$parent_rule.'$/\' => \'Urlrule/'.$action.'?l=:1&catdir=:2\'';
+					$data[] = '\'/^'.$parent_rule.'$/\' => \'Urlrule/'.$action.'?catdir=:1\'';
+				}
+			}else{
+				$data[] = '\'/^'.$langrule.$rule.'$/\' => \'Urlrule/'.$action.'?l=:1&'.$request_lang.$MOREREQUEST.$langrequest.'\'';
+				$data[]='\'/^'.$rule.'$/\' => \'Urlrule/'.$action.'?'.$request.$MOREREQUEST.'\'';
+			}
+			$data = str_replace('\/$','$',$data);
+			$data= implode(",\n",$data);
+		}else{
+			if($parent_rule){
+				$data[] = '\'/^'.$parent_rule.'([\w^_]+)\/'.$rule.'$/\' => \'Urlrule/'.$action.'?parentdir=:1&'.$request_lang_2.$MOREREQUEST.$langrequest.'\'';
+				$data[] = '\'/^'.$parent_rule.$rule.'$/\' => \'Urlrule/'.$action.'?parentdir=:1&'.$request_lang.$MOREREQUEST.$langrequest.'\'';
+				if(strstr($url,'{$page')){
+					$data[] = '\'/^'.$parent_rule.'(\d+)$/\' => \'Urlrule/'.$action.'?catdir=:1&p=:2\'';
+				}else{
+					$data[] = '\'/^'.$parent_rule.'$/\' => \'Urlrule/'.$action.'?catdir=:1\'';
+				}
+			}else{
+				$urlrule='\'/^'.$rule.'$/\' => \'Urlrule/'.$action.'?'.$request.$MOREREQUEST.'\'';
+				$data = str_replace('\/$','$',$urlrule);
+			}
+		}
+		return $data;
+}
+
+function routes_cache($URL_URLRULE=''){
+
+			$urlstr .=  '\':l'.C('URL_PATHINFO_DEPR').'Tags'.C('URL_PATHINFO_DEPR').':module'.C('URL_PATHINFO_DEPR').':tag'.C('URL_PATHINFO_DEPR').':p\' => \'Home/Tags/index\','."\n";
+			$urlstr .=  '\':l'.C('URL_PATHINFO_DEPR').'Tags'.C('URL_PATHINFO_DEPR').':tag'.C('URL_PATHINFO_DEPR').':p\' => \'Home/Tags/index\','."\n";
+			$urlstr .=  '\':l'.C('URL_PATHINFO_DEPR').'Tags'.C('URL_PATHINFO_DEPR').':module'.C('URL_PATHINFO_DEPR').':tag\' => \'Home/Tags/index\','."\n";
+			$urlstr .=  '\':l'.C('URL_PATHINFO_DEPR').'Tags'.C('URL_PATHINFO_DEPR').':p\d\' => \'Home/Tags/index\','."\n";
+			$urlstr .=  '\':l'.C('URL_PATHINFO_DEPR').'Tags'.C('URL_PATHINFO_DEPR').':tag\' => \'Home/Tags/index\','."\n";
+			$urlstr .=  '\':l'.C('URL_PATHINFO_DEPR').'Tags\' => \'Home/Tags/index\','."\n";
+
+			$urlstr .=  '\'Tags'.C('URL_PATHINFO_DEPR').':module'.C('URL_PATHINFO_DEPR').':tag'.C('URL_PATHINFO_DEPR').':p\' => \'Home/Tags/index\','."\n";
+			$urlstr .=  '\'Tags'.C('URL_PATHINFO_DEPR').':tag'.C('URL_PATHINFO_DEPR').':p\' => \'Home/Tags/index\','."\n";
+			$urlstr .=  '\'Tags'.C('URL_PATHINFO_DEPR').':module'.C('URL_PATHINFO_DEPR').':tag\' => \'Home/Tags/index\','."\n";
+			$urlstr .=  '\'Tags'.C('URL_PATHINFO_DEPR').':p\d\' => \'Home/Tags/index\','."\n";
+			$urlstr .=  '\'Tags'.C('URL_PATHINFO_DEPR').':tag\' => \'Home/Tags/index\','."\n";
+			$urlstr .=  '\'Tags\' => \'Home/Tags/index\','."\n";
+			/*
+			$urlstr .=  '\'^Tags$\' => \'Home/Tags/index\','."\n";
+			$urlstr .=  '\'/^Tags\/(\d+).html$/\' => \'Home/Tags/index?p=:1\','."\n";
+			*/
+			if(APP_LANG){
+				$Lang=F('Lang');
+				foreach((array)$Lang as $key =>$r){$langarr[]=$key;}
+				$urlstr .=  '\'/^('.implode('|',$langarr).')$/\' => \'Index/index?l=:1\','."\n";
+			}
+
+
+
+			$URL_URLRULE = $URL_URLRULE ? $URL_URLRULE : C('URL_URLRULE');
+			$urlrule = is_array($URL_URLRULE) ?  $URL_URLRULE : explode(':::',$URL_URLRULE);
+			$list=explode('|',$urlrule[1]);
+			$show=explode('|',$urlrule[0]);
+			$listurls[]= make_urlrule($show[1],$langarr,'show');
+			$listurls[]= make_urlrule($show[0],$langarr,'show');
+			$listurls[]= make_urlrule($list[1],$langarr,'index');
+			$listurls[]= make_urlrule($list[0],$langarr,'index');
+
+			$url = implode(",\n",$listurls);
+			file_put_contents(DATA_PATH.'Routes.php', "<?php\nreturn array(\n" . $urlstr.$url . "\n);\n?>");
+			if(is_file(RUNTIME_PATH.'~runtime.php'))@unlink(RUNTIME_PATH.'~runtime.php');
+			if(is_file(RUNTIME_PATH.'~allinone.php'))@unlink(RUNTIME_PATH.'~allinone.php');
+}
+
+function HOMEURL($lang){
+	if(C('URL_M')==1)$index='/index.php/';
+	$lang= C('URL_LANG')!=$lang ? $lang : '';
+	if(C('URL_M') > 0){
+		$url =$lang ? __ROOT__.$index.$lang.'/' :  __ROOT__.'/';
+	}else{
+		if(C('HOME_ISHTML')){
+			$url = $lang ? '/'.$lang.'/' : '/';
+		}else{
+			$url =$lang ?  __ROOT__.'/index.php?l='.$lang :  __ROOT__.'/';
+		}
+	}
+	return $url;
+}
+function URL($url='',$params=array()) {
+
+	if(APP_LANG)$lang = getlang();
+
+	if(!empty($url)){
+		list($path, $query) = explode('?',$url);
+		list($group, $a) = explode('/',$path);
+		list($g, $m) = explode('-',$group);
+		$params= http_build_query($params);
+		$params = !empty($params) ? '&' . $params : '';
+		$query =  !empty($query) ? '&'.$query : '';
+		//parse_str($_SERVER['QUERY_STRING'],$urlarr);
+		if($lang) $langurl = '&l='.$lang;
+		if (strcasecmp($g,'Home')== 0){
+			$url = __ROOT__.'/index.php?m='.$m.'&a='.$a.$query.$params.$langurl;
+		}else{
+			$url = __ROOT__.'/index.php?g='.$g.'&m='.$m.'&a='.$a.$query.$params.$langurl;
+		}
+	}else{
+		if(C('URL_M')==1)$index='/index.php/';
+		if(C('URL_M') > 0){
+			$url = $lang ? __ROOT__.$index.$lang.'/' :  __ROOT__.'/';
+		}else{
+			$url = $lang ? __ROOT__.'/index.php?l='.$lang :  __ROOT__.'/';
+		}
+	}
+	return $url;
+}
+
+
+
+function TAGURL($data,$p=''){
+	$index= C('URL_M')==1 ? __ROOT__.'index.php/' : __ROOT__.'/';
+	if(APP_LANG)$lang=getlang();
+	if(C('URL_M')==0){
+			if($data['moduleid'] > 0 && $data['moduleid']!=2) $params['moduleid']=$data['moduleid'] ;
+			if($data['slug']) $params['tag']=$data['slug'] ;
+			if($lang)$params['l']=$lang;
+			$url=URL('Home-Tags/index',$params);
+			if($p)$url=$url.'&p={$page}';
+	}else{
+			$tag = $data['slug'] ? '/'.$data['slug'] : '';
+			$module = ($data['moduleid'] > 0 && $data['moduleid']!=2) ?  '/'.$data['module'] : '';
+			$langurl = $lang ? $lang.'/' : '' ;
+			$url=$index.$langurl.'Tags'.$module.$tag.'/';
+			if($p)$url=$url.'{$page}'.C('URL_HTML_SUFFIX');
+	}
+	return $url;
+}
+
+function getlang($have=''){
+	if($have){
+		if(strcasecmp(GROUP_NAME,'Admin')== 0)
+			$lang =  LANG_NAME;
+		else
+			$lang =  $_REQUEST['l'] ? $_REQUEST['l'] : C('URL_LANG');
+	}else{
+		if(strcasecmp(GROUP_NAME,'Admin')== 0)
+			$lang =  C('URL_LANG')!= LANG_NAME ? LANG_NAME : '';
+		else
+			$lang = $_REQUEST['l'] && C('URL_LANG')!=$_REQUEST['l'] ? $_REQUEST['l'] : '';
+	}
+	return $lang;
+}
+
+function geturl($cat,$data='',$Urlrule=''){
+		//$Urlrule =F('Urlrule');
+		$id=$data['id'];
+		$URL_MODEL =C('URL_M');
+		if(APP_LANG)$lang = getlang();
+
+		$parentdir = $cat['parentdir'];
+		$catdir = $cat['catdir'];
+		$year = date('Y',$data['createtime']);
+		$month = date('m',$data['createtime']);
+		$day = date('d',$data['createtime']);
+		$module = $cat['module'];
+		$moduleid =$cat['moduleid'];
+		$catid=$cat['id'];
+
+		if($cat['ishtml']){
+			if($cat['urlruleid'] && $Urlrule){
+				$showurlrule = $Urlrule[$cat['urlruleid']]['showurlrule'];
+				$listurlrule = $Urlrule[$cat['urlruleid']]['listurlrule'];
+			}else{
+				echo 'This cat has not urlruleid or no Urlrule.';exit;
+			}
+		}else{
+			if($URL_MODEL==0){
+				$langurl = $lang ?  '&l='.LANG_NAME : '';
+				if($id){
+					$url[] = U("Home/$cat[module]/show?id=$id".$langurl);
+					$url[] = U("Home/$cat[module]/show?id=".$id.$langurl.'&'.C('VAR_PAGE').'={$page}');
+				}else{
+					$url[] = U("Home/$cat[module]/index?id=$cat[id]".$langurl);
+					$url[] = U("Home/$cat[module]/index?id=$cat[id]$langurl&".C('VAR_PAGE').'={$page}');
+				}
+				$urls = str_replace('g=Admin&','',$url);
+				$urls = str_replace('g=Home&','',$url);
+			}else{
+				$urlrule = explode(':::',C('URL_URLRULE'));
+				$showurlrule = $urlrule[0];
+				$listurlrule = $urlrule[1];
+			}
+		}
+		if(empty($urls)){
+			$index =  $URL_MODEL==1 ? __ROOT__.'/index.php/' : __ROOT__.'/';
+			$langurl = $lang ? $lang.'/' : '';
+			if($id){
+				$urls = str_replace(array('{$parentdir}','{$module}','{$moduleid}','{$catdir}','{$year}','{$month}','{$day}','{$catid}','{$id}'),array($parentdir,$module,$moduleid,$catdir,$year,$month,$day,$catid,$id),$showurlrule);
+			}else{
+				$urls = str_replace(array('{$parentdir}','{$module}','{$moduleid}','{$catdir}','{$year}','{$month}','{$day}','{$catid}','{$id}'),array($parentdir,$module,$moduleid,$catdir,$year,$month,$day,$catid,$id),$listurlrule);
+			}
+			$urls = explode('|',$urls);
+			$urls[0]=$index.$langurl.$urls[0];
+			$urls[1]=$index.$langurl.$urls[1];
+		}
+		return $urls;
+}
+
+
+function content_pages($num, $p,$pageurls) {
+
+	$multipage = '';
+	$page = 11;
+	$offset = 4;
+	$pages = $num;
+	$from = $p - $offset;
+	$to = $p + $offset;
+	$more = 0;
+	if($page >= $pages) {
+		$from = 2;
+		$to = $pages-1;
+	} else {
+		if($from <= 1) {
+			$to = $page-1;
+			$from = 2;
+		} elseif($to >= $pages) {
+			$from = $pages-($page-2);
+			$to = $pages-1;
+		}
+		$more = 1;
+	}
+	if($p>0) {
+		$perpage = $p == 1 ? 1 : $p-1;
+		if($perpage==1){
+			$multipage .= '<a class="a1" href="'.$pageurls[$perpage][0].'">'.L('previous').'</a>';
+		}else{
+			$multipage .= '<a class="a1" href="'.$pageurls[$perpage][1].'">'.L('previous').'</a>';
+		}
+		if($p==1) {
+			$multipage .= ' <span>1</span>';
+		} elseif($p>6 && $more) {
+			$multipage .= ' <a href="'.$pageurls[1][0].'">1</a>..';
+		} else {
+			$multipage .= ' <a href="'.$pageurls[1][0].'">1</a>';
+		}
+	}
+	for($i = $from; $i <= $to; $i++) {
+		if($i != $p) {
+			$multipage .= ' <a href="'.$pageurls[$i][1].'">'.$i.'</a>';
+		} else {
+			$multipage .= ' <span>'.$i.'</span>';
+		}
+	}
+	if($p<$pages) {
+		if($p<$pages-5 && $more) {
+			$multipage .= ' ..<a href="'.$pageurls[$pages][1].'">'.$pages.'</a> <a class="a1" href="'.$pageurls[$p+1][1].'">'.L('next').'</a>';
+		} else {
+			$multipage .= ' <a href="'.$pageurls[$pages][1].'">'.$pages.'</a> <a class="a1" href="'.$pageurls[$p+1][1].'">'.L('next').'</a>';
+		}
+	} elseif($p==$pages) {
+		$multipage .= ' <span>'.$pages.'</span> <a class="a1" href="'.$pageurls[$p][1].'">'.L('next').'</a>';
+	}
+	return $multipage;
+}
+
+function thumb($f, $tw=300, $th=300 ,$autocat=0, $nopic = 'nopic.jpg',$t=''){
+	if(strstr($f,'://')) return $f;
+	if(empty($f)) return __ROOT__.'/Public/Images/'.$nopic;
+	$f= '.'.str_replace(__ROOT__,'',$f);
+
+	$temp = array(1=>'gif', 2=>'jpeg', 3=>'png');
+	list($fw, $fh, $tmp) = getimagesize($f);
+	if(empty($t)){
+		if($fw>$tw && $fh>$th){
+			$pathinfo = pathinfo($f);
+			$t = $pathinfo['dirname'].'/thumb_'.$tw.'_'.$th.'_'.$pathinfo['basename'];
+			if(is_file($t)){
+				return  __ROOT__.substr($t,1);
+			}
+		}else{
+			return  __ROOT__.substr($f,1);
+		}
+	}
+
+	if(!$temp[$tmp]){	return false; }
+
+	if($autocat){
+		if($fw/$tw > $fh/$th){
+		$fw = $tw * ($fh/$th);
+		}else{
+		$fh = $th * ($fw/$tw);
+		}
+	}else{
+
+		 $scale = min($tw/$fw, $th/$fh); // 计算缩放比例
+            if($scale>=1) {
+                // 超过原图大小不再缩略
+                $tw   =  $fw;
+                $th  =  $fh;
+            }else{
+                // 缩略图尺寸
+                $tw  = (int)($fw*$scale);
+                $th = (int)($fh*$scale);
+            }
+
+
+	}
+
+	$tmp = $temp[$tmp];
+	$infunc = "imagecreatefrom$tmp";
+	$outfunc = "image$tmp";
+	$fimg = $infunc($f);
+
+	if($tmp != 'gif' && function_exists('imagecreatetruecolor')){
+		$timg = imagecreatetruecolor($tw, $th);
+	}else{
+		$timg = imagecreate($tw, $th);
+	}
+
+
+	if(function_exists('imagecopyresampled'))
+		imagecopyresampled($timg, $fimg, 0,0, 0,0, $tw,$th, $fw,$fh);
+	else
+		imagecopyresized($timg, $fimg, 0,0, 0,0, $tw,$th, $fw,$fh);
+	if($tmp=='gif' || $tmp=='png') {
+		$background_color  =  imagecolorallocate($timg,  0, 255, 0);  //  指派一个绿色
+		imagecolortransparent($timg, $background_color);  //  设置为透明色,若注释掉该行则输出绿色的图
+	}
+	$outfunc($timg, $t);
+	imagedestroy($timg);
+	imagedestroy($fimg);
+	return  __ROOT__.substr($t,1);
+}
+
+
+
+
+/*!
+ * ubb2html support for php
+ * @requires xhEditor
+ *
+ * @author Yanis.Wang<yanis.wang@gmail.com>
+ * @site http://xheditor.com/
+ * @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
+ *
+ * @Version: 0.9.10 (build 110801)
+ */
+function ubb2html($sUBB)
+{
+	$sHtml=$sUBB;
+
+	global $emotPath,$cnum,$arrcode,$bUbb2htmlFunctionInit;$cnum=0;$arrcode=array();
+	$emotPath='../xheditor_emot/';//表情根路径
+
+	if(!$bUbb2htmlFunctionInit){
+	function saveCodeArea($match)
+	{
+		global $cnum,$arrcode;
+		$cnum++;$arrcode[$cnum]=$match[0];
+		return "[\tubbcodeplace_".$cnum."\t]";
+	}}
+	$sHtml=preg_replace_callback('/\[code\s*(?:=\s*((?:(?!")[\s\S])+?)(?:"[\s\S]*?)?)?\]([\s\S]*?)\[\/code\]/i','saveCodeArea',$sHtml);
+
+	$sHtml=preg_replace("/&/",'&amp;',$sHtml);
+	$sHtml=preg_replace("/</",'&lt;',$sHtml);
+	$sHtml=preg_replace("/>/",'&gt;',$sHtml);
+	$sHtml=preg_replace("/\r?\n/",'<br />',$sHtml);
+
+	$sHtml=preg_replace("/\[(\/?)(b|u|i|s|sup|sub)\]/i",'<$1$2>',$sHtml);
+	$sHtml=preg_replace('/\[color\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/i','<span style="color:$1;">',$sHtml);
+	if(!$bUbb2htmlFunctionInit){
+	function getSizeName($match)
+	{
+		$arrSize=array('10px','13px','16px','18px','24px','32px','48px');
+		if(preg_match("/^\d+$/",$match[1]))$match[1]=$arrSize[$match[1]-1];
+		return '<span style="font-size:'.$match[1].';">';
+	}}
+	$sHtml=preg_replace_callback('/\[size\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/i','getSizeName',$sHtml);
+	$sHtml=preg_replace('/\[font\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/i','<span style="font-family:$1;">',$sHtml);
+	$sHtml=preg_replace('/\[back\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/i','<span style="background-color:$1;">',$sHtml);
+	$sHtml=preg_replace("/\[\/(color|size|font|back)\]/i",'</span>',$sHtml);
+
+	for($i=0;$i<3;$i++)$sHtml=preg_replace('/\[align\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\](((?!\[align(?:\s+[^\]]+)?\])[\s\S])*?)\[\/align\]/','<p align="$1">$2</p>',$sHtml);
+	$sHtml=preg_replace('/\[img\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/img\]/i','<img src="$1" alt="" />',$sHtml);
+	if(!$bUbb2htmlFunctionInit){
+	function getImg($match)
+	{
+		$alt=$match[1];$p1=$match[2];$p2=$match[3];$p3=$match[4];$src=$match[5];
+		$a=$p3?$p3:(!is_numeric($p1)?$p1:'');
+		return '<img src="'.$src.'" alt="'.$alt.'"'.(is_numeric($p1)?' width="'.$p1.'"':'').(is_numeric($p2)?' height="'.$p2.'"':'').($a?' align="'.$a.'"':'').' />';
+	}}
+	$sHtml=preg_replace_callback('/\[img\s*=([^,\]]*)(?:\s*,\s*(\d*%?)\s*,\s*(\d*%?)\s*)?(?:,?\s*(\w+))?\s*\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*)?\s*\[\/img\]/i','getImg',$sHtml);
+	if(!$bUbb2htmlFunctionInit){
+	function getEmot($match)
+	{
+		global $emotPath;
+		$arr=split(',',$match[1]);
+		if(!isset($arr[1])){$arr[1]=$arr[0];$arr[0]='default';}
+		$path=$emotPath.$arr[0].'/'.$arr[1].'.gif';
+		return '<img src="'.$path.'" alt="'.$arr[1].'" />';
+	}}
+	$sHtml=preg_replace_callback('/\[emot\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\/\]/i','getEmot',$sHtml);
+	$sHtml=preg_replace('/\[url\]\s*(((?!")[\s\S])*?)(?:"[\s\S]*?)?\s*\[\/url\]/i','<a href="$1">$1</a>',$sHtml);
+	$sHtml=preg_replace('/\[url\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]\s*([\s\S]*?)\s*\[\/url\]/i','<a href="$1">$2</a>',$sHtml);
+	$sHtml=preg_replace('/\[email\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/email\]/i','<a href="mailto:$1">$1</a>',$sHtml);
+	$sHtml=preg_replace('/\[email\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]\s*([\s\S]+?)\s*\[\/email\]/i','<a href="mailto:$1">$2</a>',$sHtml);
+	$sHtml=preg_replace("/\[quote\]([\s\S]*?)\[\/quote\]/i",'<blockquote>$1</blockquote>',$sHtml);
+	if(!$bUbb2htmlFunctionInit){
+	function getFlash($match)
+	{
+		$w=$match[1];$h=$match[2];$url=$match[3];
+		if(!$w)$w=480;if(!$h)$h=400;
+		return '<embed type="application/x-shockwave-flash" src="'.$url.'" wmode="opaque" quality="high" bgcolor="#ffffff" menu="false" play="true" loop="true" width="'.$w.'" height="'.$h.'" />';
+	}}
+	$sHtml=preg_replace_callback('/\[flash\s*(?:=\s*(\d+)\s*,\s*(\d+)\s*)?\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/flash\]/i','getFlash',$sHtml);
+	if(!$bUbb2htmlFunctionInit){
+	function getMedia($match)
+	{
+		$w=$match[1];$h=$match[2];$play=$match[3];$url=$match[4];
+		if(!$w)$w=480;if(!$h)$h=400;
+		return '<embed type="application/x-mplayer2" src="'.$url.'" enablecontextmenu="false" autostart="'.($play=='1'?'true':'false').'" width="'.$w.'" height="'.$h.'" />';
+	}}
+	$sHtml=preg_replace_callback('/\[media\s*(?:=\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+)\s*)?)?\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/media\]/i','getMedia',$sHtml);
+	if(!$bUbb2htmlFunctionInit){
+	function getTable($match)
+	{
+		return '<table'.(isset($match[1])?' width="'.$match[1].'"':'').(isset($match[2])?' bgcolor="'.$match[2].'"':'').'>';
+	}}
+	$sHtml=preg_replace_callback('/\[table\s*(?:=(\d{1,4}%?)\s*(?:,\s*([^\]"]+)(?:"[^\]]*?)?)?)?\s*\]/i','getTable',$sHtml);
+	if(!$bUbb2htmlFunctionInit){
+	function getTR($match){return '<tr'.(isset($match[1])?' bgcolor="'.$match[1].'"':'').'>';}}
+	$sHtml=preg_replace_callback('/\[tr\s*(?:=(\s*[^\]"]+))?(?:"[^\]]*?)?\s*\]/i','getTR',$sHtml);
+	if(!$bUbb2htmlFunctionInit){
+	function getTD($match){
+		$col=isset($match[1])?$match[1]:0;$row=isset($match[2])?$match[2]:0;$w=isset($match[3])?$match[3]:null;
+		return '<td'.($col>1?' colspan="'.$col.'"':'').($row>1?' rowspan="'.$row.'"':'').($w?' width="'.$w.'"':'').'>';
+	}}
+	$sHtml=preg_replace_callback("/\[td\s*(?:=\s*(\d{1,2})\s*,\s*(\d{1,2})\s*(?:,\s*(\d{1,4}%?))?)?\s*\]/i",'getTD',$sHtml);
+	$sHtml=preg_replace("/\[\/(table|tr|td)\]/i",'</$1>',$sHtml);
+	$sHtml=preg_replace("/\[\*\]((?:(?!\[\*\]|\[\/list\]|\[list\s*(?:=[^\]]+)?\])[\s\S])+)/i",'<li>$1</li>',$sHtml);
+	if(!$bUbb2htmlFunctionInit){
+	function getUL($match)
+	{
+		$str='<ul';
+		if(isset($match[1]))$str.=' type="'.$match[1].'"';
+		return $str.'>';
+	}}
+	$sHtml=preg_replace_callback('/\[list\s*(?:=\s*([^\]"]+))?(?:"[^\]]*?)?\s*\]/i','getUL',$sHtml);
+	$sHtml=preg_replace("/\[\/list\]/i",'</ul>',$sHtml);
+	$sHtml=preg_replace("/\[hr\/\]/i",'<hr />',$sHtml);
+
+	for($i=1;$i<=$cnum;$i++)$sHtml=str_replace("[\tubbcodeplace_".$i."\t]", $arrcode[$i],$sHtml);
+
+	if(!$bUbb2htmlFunctionInit){
+	function fixText($match)
+	{
+		$text=$match[2];
+		$text=preg_replace("/\t/",'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',$text);
+		$text=preg_replace("/ /",'&nbsp;',$text);
+		return $match[1].$text;
+	}}
+	$sHtml=preg_replace_callback('/(^|<\/?\w+(?:\s+[^>]*?)?>)([^<$]+)/i','fixText',$sHtml);
+
+	$bUbb2htmlFunctionInit=true;
+
+	return $sHtml;
+}
+
+
+function Pinyin($_String) {
+$_DataKey = "a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha".
+   "|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|".
+   "cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er".
+   "|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui".
+   "|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang".
+   "|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang".
+   "|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue".
+   "|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne".
+   "|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen".
+   "|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang".
+   "|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|".
+   "she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|".
+   "tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu".
+   "|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you".
+   "|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|".
+   "zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo";
+$_DataValue = "-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990".
+   "|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725".
+   "|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263".
+   "|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003".
+   "|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697".
+   "|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211".
+   "|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922".
+   "|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468".
+   "|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664".
+   "|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407".
+   "|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959".
+   "|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652".
+   "|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369".
+   "|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128".
+   "|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914".
+   "|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645".
+   "|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149".
+   "|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087".
+   "|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658".
+   "|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340".
+   "|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888".
+   "|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585".
+   "|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847".
+   "|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055".
+   "|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780".
+   "|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274".
+   "|-10270|-10262|-10260|-10256|-10254";
+$_TDataKey   = explode('|', $_DataKey);
+$_TDataValue = explode('|', $_DataValue);
+$_Data =  array_combine($_TDataKey, $_TDataValue);
+arsort($_Data);
+reset($_Data);
+$_String= auto_charset($_String,'utf-8','gbk');
+$_Res = '';
+for($i=0; $i<strlen($_String); $i++) {
+      $_P = ord(substr($_String, $i, 1));
+      if($_P>160) { $_Q = ord(substr($_String, ++$i, 1)); $_P = $_P*256 + $_Q - 65536; }
+      $_Res .= _Pinyin($_P, $_Data);
+}
+return preg_replace("/[^a-z0-9]*/", '', $_Res);
+}
+
+// 自动转换字符集 支持数组转换
+function auto_charset($fContents, $from='gbk', $to='utf-8') {
+    $from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
+    $to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
+    if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) {
+        //如果编码相同或者非字符串标量则不转换
+        return $fContents;
+    }
+    if (is_string($fContents)) {
+        if (function_exists('mb_convert_encoding')) {
+            return mb_convert_encoding($fContents, $to, $from);
+        } elseif (function_exists('iconv')) {
+            return iconv($from, $to, $fContents);
+        } else {
+            return $fContents;
+        }
+    } elseif (is_array($fContents)) {
+        foreach ($fContents as $key => $val) {
+            $_key = auto_charset($key, $from, $to);
+            $fContents[$_key] = auto_charset($val, $from, $to);
+            if ($key != $_key)
+                unset($fContents[$key]);
+        }
+        return $fContents;
+    }
+    else {
+        return $fContents;
+    }
+}
+
+function _Pinyin($_Num, $_Data) {
+   if    ($_Num>0      && $_Num<160   ) return chr($_Num);
+   elseif($_Num<-20319 || $_Num>-10247) return '';
+   else {
+        foreach($_Data as $k=>$v){ if($v<=$_Num) break; }
+        return $k;
+   }
+}
+
+function return_url($code){
+		$config = APP_LANG ?  F('Config_'.LANG_NAME) :  F('Config');
+		return $config['site_url'].'/index.php?g=User&m=Pay&a=respond&code='.$code;
+}
+function order_pay_status($sn,$value){
+	$cart['status'] =1;
+	$cart['pay_status'] =$value;
+	if($value==2)$cart['pay_time'] =time();
+	$r = M('Order')->where("sn='{$sn}'")->save($cart);
+	return $r;
+}
+
+function addslashes_array($array){
+	if(get_magic_quotes_gpc())return $array;
+	if(!is_array($array))return addslashes($array);
+	foreach($array as $k => $val) $array[$k] = addslashes_array($val);
+	return $array;
+}
+
+function stripslashes_array($array) {
+	if(!is_array($array)) return stripslashes($array);
+	foreach($array as $k => $val) $array[$k] = stripslashes_array($val);
+	return $array;
+}
+
+function htmlspecialchars_array($array) {
+	if(!is_array($array)) return htmlspecialchars($array,ENT_QUOTES);
+	foreach($array as $k => $val) $array[$k] = htmlspecialchars_array($val);
+	return $array;
+}
+
+function safe_replace($string) {
+	$string = trim($string);
+	$string = str_replace(array('\\',';','\'','%2527','%27','%20','&', '"', '<', '>'), array('','','','','','','&amp;', '&quot;', '&lt;', '&gt;'), $string);
+	$string=nl2br($string);
+	return $string;
+}
+function get_safe_replace($array){
+	if(!is_array($array)) return safe_replace(strip_tags($array));
+	foreach($array as $k => $val) $array[$k] = get_safe_replace($val);
+	return $array;
+}
+
+function  sql_split($sql,$tablepre) {
+
+	if($tablepre != "aina_") $sql = str_replace("aina_", $tablepre, $sql);
+	//$sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=utf8",$sql);
+
+	if($r_tablepre != $s_tablepre) $sql = str_replace($s_tablepre, $r_tablepre, $sql);
+	$sql = str_replace("\r", "\n", $sql);
+	$ret = array();
+	$num = 0;
+	$queriesarray = explode(";\n", trim($sql));
+	unset($sql);
+	foreach($queriesarray as $query)
+	{
+		$ret[$num] = '';
+		$queries = explode("\n", trim($query));
+		$queries = array_filter($queries);
+		foreach($queries as $query)
+		{
+			$str1 = substr($query, 0, 1);
+			if($str1 != '#' && $str1 != '-') $ret[$num] .= $query;
+		}
+		$num++;
+	}
+	return $ret;
+}
+function prevnext($mod,$id,$catid,$num=''){
+	$prev = D($mod)->where("id < $id and catid = $catid")->order("id desc")->find();
+	$next = D($mod)->where("id > $id and catid = $catid")->order("id asc")->find();
+	if(!$prev){
+		$prev[content] = '没有了';
+	}else{
+		if($num){
+			$prev[sort_title] = str_cut($prev[title],$num);
+		}else{
+			$prev[sort_title] = $prev[title];
+		}
+		$prev[content] = '<a href="'.$prev[url].'" title="'.$prev[title].'">'.$prev[sort_title].'</a>';
+	}
+	if(!$next){
+		$next[content] = '没有了';
+	}else{
+		if($num){
+			$next[sort_title] = str_cut($next[title],$num);
+		}else{
+			$next[sort_title] = $next[title];
+		}
+		$next[content] = '<a href="'.$next[url].'" title="'.$next[title].'">'.$next[sort_title].'</a>';
+	}
+	$prevnext = "<p class=\"fl\">上一篇:$prev[content]</p><p class=\"fr\">下一篇:$next[content]</p>";
+	return $prevnext;
+}
+//导出excel功能
+function exportexcel($data=array(),$title=array(),$filename='report'){
+    header("Content-type:application/octet-stream");
+    header("Accept-Ranges:bytes");
+    header("Content-type:application/vnd.ms-excel");
+    header("Content-Disposition:attachment;filename=".$filename.".xls");
+    header("Pragma: no-cache");
+    header("Expires: 0");
+    //导出xls 开始
+    if (!empty($title)){
+        foreach ($title as $k => $v) {
+            $title[$k]=iconv("UTF-8", "GB2312",$v);
+        }
+        $title= implode("\t", $title);
+        echo "$title\n";
+    }
+    if (!empty($data)){
+        foreach($data as $key=>$val){
+            foreach ($val as $ck => $cv) {
+                $data[$key][$ck]=iconv("UTF-8", "GB2312", $cv);
+            }
+            $data[$key]=implode("\t", $data[$key]);
+
+        }
+        echo implode("\n",$data);
+    }
+}
+// Xml 转 数组, 包括根键,忽略空元素和属性,尚有重大错误
+function xml_to_array($xml)
+{
+	$reg = "/<(\\w+)[^>]*?>([\\x00-\\xFF]*?)<\\/\\1>/";
+	if(preg_match_all($reg, $xml, $matches))
+	{
+		$count = count($matches[0]);
+		$arr = array();
+		for($i = 0; $i < $count; $i++)
+		{
+			$key = $matches[1][$i];
+			$val = $this->xml_to_array( $matches[2][$i] );  // 递归
+			if(array_key_exists($key, $arr)){
+				if(is_array($arr[$key])){
+					if(!array_key_exists(0,$arr[$key])){
+						$arr[$key] = array($arr[$key]);
+					}
+				}else{
+					$arr[$key] = array($arr[$key]);
+				}
+				$arr[$key][] = $val;
+			}else{
+				$arr[$key] = $val;
+			}
+		}
+		return $arr;
+	}else{
+		return $xml;
+	}
+}
+// Xml 转 数组, 不包括根键
+function xmltoarray( $xml )
+{
+	$arr = $this->xml_to_array($xml);
+	$key = array_keys($arr);
+	return $arr[$key[0]];
+}
+//为了方便多选判断是否选中  $arr为数组,$key为当前的value
+function checked($arr,$key){
+	if(in_array($key,$arr)){
+	return "checked";
+	}
+}
+?>

+ 39 - 0
Ainaphp/Conf/Admin/config.php

@@ -0,0 +1,39 @@
+<?php
+$config	= array(
+        'DEFAULT_THEME'		=> 'Default',
+		'LANG_AUTO_DETECT'=> false,
+		'LANG_SWITCH_ON' => true,
+		'DEFAULT_LANG'   => 'zh-cn',
+		'URL_ROUTER_ON'		=> false,
+		'TMPL_CACHE_ON'		=> false,
+		'TMPL_CACHE_TIME'	=> -1,
+		'URL_DISPATCH_ON'	=> 0,
+		'URL_MODEL'			=> '0',
+
+		'USER_AUTH_ON'			=>true,
+		'USER_AUTH_TYPE'		=>1,		// 默认认证类型 1 登录认证 2 实时认证
+		'USER_AUTH_KEY'			=>'authId',	// 用户认证SESSION标记
+		'ADMIN_AUTH_KEY'		=>'administrator',
+		'USER_AUTH_MODEL'		=>'User',	// 默认验证数据表模型
+		'AUTH_PWD_ENCODER'		=>'md5',	// 用户认证密码加密方式
+		'USER_AUTH_GATEWAY'	    =>'?g=Admin&m=Login',	// 默认认证网关
+		'NOT_AUTH_MODULE'		=>'',		// 默认无需认证模块
+		'REQUIRE_AUTH_MODULE'	=>'',		// 默认需要认证模块
+		'NOT_AUTH_ACTION'		=>'',		// 默认无需认证操作
+		'REQUIRE_AUTH_ACTION'	=>'',		// 默认需要认证操作
+		'GUEST_AUTH_ON'         => false,    // 是否开启游客授权访问
+		'GUEST_AUTH_ID'         =>    0,     // 游客的用户ID
+		'DB_LIKE_FIELDS'		=>	'name|remark',
+		'RBAC_ROLE_TABLE'		=>	C('DB_PREFIX').'role',
+		'RBAC_USER_TABLE'		=>	C('DB_PREFIX').'role_user',
+		'RBAC_ACCESS_TABLE'		=>	C('DB_PREFIX').'access',
+		'RBAC_NODE_TABLE'		=>  C('DB_PREFIX').'node',
+		'DEFAULT_HOME_THEME' => C('DEFAULT_THEME'),
+		'LAYOUT_ON'=> true,
+		'TMPL_CACHE_ON'		=> true,
+		'TMPL_CACHE_TIME'	=> 3600,
+		//'TMPL_DETECT_THEME'     => true
+		//'LANG_SWITCH_ON'		=> true,
+);
+return $config	;
+?>

+ 12 - 0
Ainaphp/Conf/User/config.php

@@ -0,0 +1,12 @@
+<?php
+$default_theme = is_dir(TMPL_PATH.'User/'.C('DEFAULT_THEME')) ? C('DEFAULT_THEME') : 'Default';
+$config=array(
+		'DEFAULT_THEME'		=> $default_theme,
+		'URL_ROUTER_ON'		=> false,
+		'TMPL_CACHE_ON'		=> false,
+		'TMPL_CACHE_TIME'	=> 3600,
+		'URL_MODEL'			=> 0,
+		'LANG_SWITCH_ON'		=> true
+);
+return $config;
+?>

+ 29 - 0
Ainaphp/Conf/config.php

@@ -0,0 +1,29 @@
+<?php
+$database = require (RUNTIME_PATH.'config.php');
+$sys_config =  include DATA_PATH.  'sys.config.php';
+if(empty($sys_config)){$sys_config=array();$sys_config['LAYOUT_ON']=1;}
+if($sys_config['URL_MODEL']) $RULES = include DATA_PATH.  'Routes.php';
+$config	= array(
+		'DEFAULT_THEME'		=> 'Default',
+		'DEFAULT_CHARSET' => 'utf-8',
+		'APP_GROUP_LIST' => 'Home,Admin,User',
+		'DEFAULT_GROUP' =>'Home',
+		'TMPL_FILE_DEPR' => '_',
+		'DB_FIELDS_CACHE' => false,
+		'DB_FIELDTYPE_CHECK' => true,
+		'URL_ROUTER_ON' => true,
+		'DEFAULT_LANG'   => 'cn',
+		'LANG_SWITCH_ON'		=> true,
+		'TAGLIB_LOAD' => true,
+		'TAGLIB_PRE_LOAD' => 'Yp',
+		'TMPL_ACTION_ERROR' => APP_PATH.'/Tpl/Home/Default/Public/success.html',
+		'TMPL_ACTION_SUCCESS' =>  APP_PATH.'/Tpl/Home/Default/Public/success.html',
+		'COOKIE_PREFIX'=>'YP_',
+		'COOKIE_EXPIRE'=>'',
+		'VAR_PAGE' => 'p',
+		'LAYOUT_HOME_ON'=>$sys_config['LAYOUT_ON'],
+		'URL_ROUTE_RULES' => $RULES,
+		'TMPL_EXCEPTION_FILE' => APP_PATH.'/Tpl/Home/Default/Public/exception.html'
+);
+return array_merge($database, $config ,$sys_config);
+?>

+ 8 - 0
Ainaphp/Conf/tags.php

@@ -0,0 +1,8 @@
+<?php
+// 系统默认的核心行为扩展列表文件
+return array(
+    'app_begin'=>array(  //因为项目中也可能用到语言行为,最好放在项目开始的地方
+        'CheckLang'      //检测语言
+    ),
+);
+?>

+ 4 - 0
Ainaphp/Lang/cn/Home_order.php

@@ -0,0 +1,4 @@
+<?php
+return array (
+
+); ?>

+ 6 - 0
Ainaphp/Lang/cn/User.php

@@ -0,0 +1,6 @@
+<?php
+return array (
+
+
+);
+?>

+ 4 - 0
Ainaphp/Lang/cn/User_order.php

@@ -0,0 +1,4 @@
+<?php
+return array (
+
+); ?>

+ 5 - 0
Ainaphp/Lang/cn/common.php

@@ -0,0 +1,5 @@
+<?php
+return array (
+  'HOME_FONT' => '网站首页',
+);
+?>

+ 5 - 0
Ainaphp/Lang/en/User.php

@@ -0,0 +1,5 @@
+<?php
+return array (
+
+);
+?>

+ 5 - 0
Ainaphp/Lang/en/common.php

@@ -0,0 +1,5 @@
+<?php
+return array (
+  'HOME_FONT' => 'Home',
+);
+?>

+ 21 - 0
Ainaphp/Lang/zh-cn/Admin_attachment.php

@@ -0,0 +1,21 @@
+<?php
+return array(
+	'uploadfiles' => '文件上传',
+	'upload_file' => '上传文件',
+	'upload_url' => '网络地址',
+	'upload_list_file' => '浏览图库',
+	'upload_unuse_file' => '未处理文件',
+	'upload_say1' => '最多上传',
+	'upload_say2' => '个附件,单文件最大 ',
+	'upload_say3' => 'MB ',
+	'upload_say4' => '支持 ',
+	'upload_say5' => '格式。',
+	'upload_add_water' => '是否添加水印',
+	'upload_say6' => '共选择了',
+	'upload_say7' => '个附件,上传失败 ',
+	'upload_say8' => '个,成功上传',
+	'upload_say9' => '个',
+	'upload_fileurl' => '请输入网络地址',
+	'NO_USE_FILES'=>'清理未使用的图片',
+);
+?>

+ 48 - 0
Ainaphp/Lang/zh-cn/Admin_category.php

@@ -0,0 +1,48 @@
+<?php
+return array(
+	'chose_module'=>'请选择模型',
+	'chose_parentid'=>'上级栏目',
+	'catimage'=>'栏目图片',
+	'ismenu'=>'是否在导航显示',
+	'seo_title'=>'SEO栏目标题',
+	'seo_keywords'=>'SEO栏目关键词',
+	'seo_description'=>'SEO栏目简介',
+	'select_parentid'=>'作为一级栏目',
+	'other_url'=>'外部链接地址',
+	'Module_url'=>'外部链接',
+	'add_catname'=>'添加子栏目',
+	'chose_module'=>'请选择模型',
+	'chose_notop_module'=>'子栏目必须与上级栏目模型相同',
+	'readgroup' => '访问权限',
+	'pagesize' => '分页条数',
+	'catdir' => '栏目目录',
+	'template_index' => '大栏目页模板',
+	'template_list' => '列表页模板',
+	'template_show' => '内容页模板',
+	'pagesize_desc' => '为空时默认值为系统设置的值',
+	'template_show' => '内容页模板',
+	'error_catname_is_empty' => '栏目名称必须填写且为3-30个字符',
+	'ERROR_CATDIR_IS_EMPTY'=>'栏目目录为3-30个字符',
+	'listtype' => '是否为封面栏目',
+	'cat_link_url' => '外部链接地址',
+	'cat_link_url_desc' => '填写链接地址后其他设置无效',
+	'ISHTML' => '是否生成html',
+	'chage_all'=>'将以下设置应用到所有子栏目',
+	'chage_is'=>'多栏目设置',
+	'base_setup'=> '基本设置',
+	'seo_setup'=>'SEO设置',
+	'category_does_not_allow_delete' => '栏目下存有信息不能删除',
+	'edit_page'=>'修改内容',
+	'ismenu'=>'导航',
+	'postgroup'=>'允许投稿会员组',
+	'chargesetup'=>'收费设置',
+	'presentpoint'=>'投稿奖励',
+	'defaultchargepoint'=>'默认收取',
+	'repeatchargedays'=>'重复收费设置',
+	'dian'=>'点',
+	'yuan'=>'元',
+	'tian'=>'天',
+	'urlrule'=>'URL规则',
+	'add_content'=>'添加内容',
+);
+?>

+ 83 - 0
Ainaphp/Lang/zh-cn/Admin_config.php

@@ -0,0 +1,83 @@
+<?php
+return array(
+	'seo_title' => '网站标题',
+	'seo_keywords' => '关键词',
+	'seo_description' => '网站简介',
+	'APP_DEBUG' => '调试模式',
+	'URL_ROUTER_ON' => '路由模式',
+	'URL_MODEL' => 'URL访问模式',
+	'URL_MODEL0' => '普通模式',
+	'URL_MODEL1' => 'PATHINFO模式',
+	'URL_MODEL2' => 'REWRITE模式',
+	'URL_MODEL3' => '兼容模式',
+	'URL_PATHINFO_DEPR' => '参数分割符',
+	'URL_HTML_SUFFIX' => 'URL伪静态后缀',
+	'TMPL_CACHE_ON' => '默认模板',
+	'TOKEN_ON' => '令牌验证',
+	'TOKEN_NAME' => '令牌表单字段',
+	'TMPL_CACHE_ON' => '模板编译缓存',
+	'TMPL_CACHE_TIME' => '模板缓存有效期',
+	'HTML_CACHE_ON' => '静态缓存',
+	'HTML_CACHE_TIME' => '缓存有效期',
+	'HTML_READ_TYPE' => '缓存读取方式',
+	'HTML_FILE_SUFFIX' => '静态文件后缀',
+	'var_name' => '变量名称',
+	'var_info' => '变量介绍',
+	'var_type' => '变量类型',
+	'var_value' => '变量值',
+	'var_group' => '变量分组',
+	'var_number' => '数字',
+	'var_varchar' => '字符串',
+	'config_site' => '站点配置',
+	'config_sys' => '系统参数',
+	'config_seo' => 'SEO配置',
+	'config_user' => '自定义变量',
+	'config_mail'=> '系统邮箱',
+	'config_attach' => '附件设置',
+	'config_mail_md' => '邮件发送模式',
+	'config_mail_smtp' => 'SMTP 函数发送',
+	'config_mail_mailfun' => 'mail 模块发送',
+	'config_mail_server' => '邮件服务器',
+	'config_mail_port' => '邮件发送端口',
+	'config_mail_from' => '发件人地址',
+	'config_mail_auth' => 'AUTH LOGIN验证',
+	'config_mail_user' => '验证用户名',
+	'config_mail_password' => '验证密码',
+	'config_mail_test' => '邮件设置测试',
+	'config_mail_testsed' => '测试发送',
+	'config_attach_maxsize' => '允许上传附件大小',
+	'config_attach_allowext' => '允许上传附件类型',
+	'config_attach_watermark_enable' => '是否开启图片水印',
+	'config_attach_watermark_minwidth' => '水印添加条件',
+	'config_attach_watermark_img' => '水印图片',
+	'config_attach_watermark_img_tip' => '水印图片路路径/Public/Images/',
+	'config_attach_watermark_pct' => '水印透明度',
+	'config_attach_watermark_quality' => 'JPEG 水印质量',
+	'config_attach_watermark_pos' => '水印位置',
+	'config_attach_watermark_pos_padding' => '水印边距',
+	'config_attach_watermark_pos_rand' => '随机位置',
+	'config_attach_watermark_pos_1' => '顶部居左',
+	'config_attach_watermark_pos_2' => '顶部居中',
+	'config_attach_watermark_pos_3' => '顶部居右',
+	'config_attach_watermark_pos_4' => '左部居中',
+	'config_attach_watermark_pos_5' => '左部居左',
+	'config_attach_watermark_pos_6' => '左部居右',
+	'config_attach_watermark_pos_7' => '底部居左',
+	'config_attach_watermark_pos_8' => '底部居中',
+	'config_attach_watermark_pos_9' => '底部居右',
+	'config_attach_watemard_text' => '水印文字内容',
+	'config_attach_watemard_text_size' => '文字大小',
+	'config_attach_watemard_text_color' => '文字颜色',
+	'config_attach_watemard_text_face' => '字体',
+	'config_attach_watemard_text_color_tip' => '#FFFFF为白色 #000000为黑色',
+	'config_attach_watemard_text_face_tip' => '若水印为中文放中文字体在Public/Images/font/目录下',
+	'ISHTML' => '生成html',
+	'URL_URLRULE'=> 'URL规则',
+	'URL_SHOW_URLRULE'=> '内容页',
+	'URL_LIST_URLRULE'=> '列表页',
+	'LAYOUT_ON'=>'布局模板',
+	'ADMIN_VERIFY'=>'后台登陆验证码',
+	'COOKIE_PATH'=>'cookie路径',
+	'COOKIE_DOMAIN'=>'cookie域名',
+);
+?>

+ 37 - 0
Ainaphp/Lang/zh-cn/Admin_createhtml.php

@@ -0,0 +1,37 @@
+<?php
+return array(
+	'no_enable_createhtml'=>'系统没有开启生成HTML页',
+	'index_create_OK'=>'首页更新完成',
+	'createhtml_desc'=>'1、在系统设置 > 系统参数 > 开启生成html的功能后 , 才可以生成HTML首页<br>2、生成栏目列表页和内容页前请确定之前添加的栏目和文章的地址已经更新成为静态页URL<br>',
+	'chose_module' => '选择模型更新',
+	'chose_category' => '选择栏目范围',
+	'chose_manage' => '选择操作内容',
+	'module_select' => '不限模型',
+	'category_alt' => '按住“Ctrl”或“Shift”键可以多选,按住“Ctrl”可取消选择',
+	'category_select' => '不限栏目',
+	'create_pagesize_1' => '每轮更新',
+	'create_pagesize_2' => '条信息',
+	'create_all' => '更新所有信息',
+	'start_create' => '开始更新',
+	'create_update_success' => '更新完成',
+	'create_update_count' => ' 共需要更新<font color="red">',
+	'create_update_num' => '</font>条信息 - 已完成<font color="red">',
+	'items' => '</font>条(<font color="red">',
+	'items1' => '%</font>)',
+	'start_updating' => '开始更新',
+	'updating' => '正在更新',
+	'create_update_list_num' => '</font>页 - 已完成<font color="red">',
+	'items_list' => '</font>页(<font color="red">',
+	'Createlist' => '开始更新列表页',
+	'Createshow' => '开始更新内容页',
+	'Updateurl' => '开始更新URL',
+	'Createindex' => '生成首页HTML文件',
+	'Createsitemap' => '生成地图',
+	'YES_NO_CREATE'=>'是否生成',
+	'sitemap_info'=>'网站地图有助于确保搜索引擎了解您网站上的所有网页,包括在正常抓取过程中可能找不到的网址.<br> 建议每周生成一次 ',
+	'HTML_SITEMAP'=>'HTML地图',
+	'XML_SITEMAP'=>'XML地图',
+	'GOTO'=>'访问',
+	'MODULE_NUMBER'=>'模型信息生成数量',
+);
+?>

+ 11 - 0
Ainaphp/Lang/zh-cn/Admin_dbsource.php

@@ -0,0 +1,11 @@
+<?php
+return array(
+	'db_host' => '数据库地址',
+	'db_name' => '数据源名称',
+	'db_port' => '数据库端口',
+	'db_username' => '数据库帐号',
+	'db_password' => '数据库密码',
+	'db_dbname'=> '数据库名称',
+	'db_dbtablepre'=> '数据库表前缀',
+);
+?>

+ 46 - 0
Ainaphp/Lang/zh-cn/Admin_field.php

@@ -0,0 +1,46 @@
+<?php
+return array(
+	'field_field' => '字段名',
+	'field_name' => '别名',
+	'field_type' => '类型',
+	'field_issystem' => '系统字段',
+	'field_add' => '添加字段',
+	'field_edit' => '编辑字段',
+	'field_manage' => '字段管理',
+	'field_required' => '是否必填项',
+	'field_lange' => '限制字符串长度范围',
+	'field_minlength' => '最小几个字符',
+	'field_maxlength' => '最大几个字符',
+	'field_size' => '文本框大小',
+	'field_pattern' => '验证规则',
+	'field_errormsg' => '验证失败错误信息',
+	'field_type' => '字段类型',
+	'field_tips' => '字段提示',
+	'field_setup' => '字段相关设置',
+	'field_class' => '字段class名称',
+	'field_empty_type'=>'字段类型不能为空',
+	'field_empty_field'=>'字段名不能为空',
+	'field_empty_name'=>'字段别名不能为空',
+	'field_required' => '必填',
+
+	'pattern_email' => '电子邮件地址',
+	'pattern_url' => '网址',
+	'pattern_date' => '日期',
+	'pattern_number'=> '有效的数值',
+	'pattern_digits'=>  '数字',
+	'pattern_creditcard'=> '信用卡号码',
+	'pattern_equalTo'=> '再次输入相同的值.',
+	'pattern_ip4'=>  'IP地址',
+	'pattern_mobile'=> '手机号码',
+	'pattern_zipcode'=> '邮编',
+	'pattern_qq'=> 'QQ号码',
+	'pattern_idcard'=> '身份证号',
+	'pattern_chinese'=> '中文字符',
+	'pattern_cn_username'=>'中文英文和数字和下划线',
+	'pattern_tel'=> '电话号码',
+	'pattern_english'=> '英文',
+	'pattern_en_num'=> '英文和数字和下划线',
+	'field_post'=> '在前台投稿中显示',
+	'field_unpost_group'=> '禁止设置字段值的会员组',
+);
+?>

+ 29 - 0
Ainaphp/Lang/zh-cn/Admin_index.php

@@ -0,0 +1,29 @@
+<?php
+return array(
+		'Profile_info'=>'个人信息',
+		'Site_Stats'=>'网站统计',
+		'Help_News'=>'官方动态',
+		'view_new_VERSION'=>'查看最新版本',
+		'miao'=>'秒',
+		'PHP_OS'=>'操作系统',
+		'SERVER_SOFTWARE'=>'运行环境',
+		'mysql_get_server_info' => 'PHP运行方式',
+		'ainaphp_VERSION'=>'Ainatec版本',
+		'MYSQL_VERSION'=>'MYSQL版本',
+		'upload_max_filesize' => '上传附件限制',
+		'max_execution_time'=>'执行时间限制',
+		'disk_free_space' => '剩余空间',
+		'user_counts'=>'会员总数',
+		'Category_counts' => '栏目总数',
+		'username'=> '会员名',
+		'groupname'=>'所属会员组',
+		'logintime'=>'最后登陆时间',
+		'login_count'=>'登陆次数',
+		'last_ip'=>'最后登陆IP',
+		'ainaphp_news'=>'官方动态',
+		'ainaphp_help' => '帮助中心',
+		'license'=> '授权类型',
+		'SN'=>'序列号',
+		'update'=>'程序更新',
+);
+?>

+ 27 - 0
Ainaphp/Lang/zh-cn/Admin_main.php

@@ -0,0 +1,27 @@
+<?php
+return array(
+		'Profile_info'=>'个人信息',
+		'Site_Stats'=>'网站统计',
+		'Help_News'=>'官方动态',
+		'view_new_VERSION'=>'查看最新版本',
+		'miao'=>'秒',
+		'PHP_OS'=>'操作系统',
+		'SERVER_SOFTWARE'=>'运行环境',
+		'mysql_get_server_info' => 'PHP运行方式',
+		'ainaphp_VERSION'=>'Ainatec版本',
+		'MYSQL_VERSION'=>'MYSQL版本',
+		'upload_max_filesize' => '上传附件限制',
+		'max_execution_time'=>'执行时间限制',
+		'disk_free_space' => '剩余空间',
+		'user_counts'=>'会员总数',
+		'Category_counts' => '栏目总数',
+		'username'=> '会员名',
+		'groupname'=>'所属会员组',
+		'logintime'=>'最后登陆时间',
+		'login_count'=>'登陆次数',
+		'last_ip'=>'最后登陆IP',
+		'ainaphp_news'=>'官方动态',
+		'ainaphp_help' => '帮助中心',
+		'license'=> '授权类型',
+);
+?>

+ 41 - 0
Ainaphp/Lang/zh-cn/Admin_module.php

@@ -0,0 +1,41 @@
+<?php
+return array(
+	'module_name' => '模型名称',
+	'module_dir' => '模型目录',
+	'module_developer' => '开发商',
+	'module_version' => '版本号',
+	'module_uninstall' => '卸载',
+	'module_install' => '安装',
+	'module_real_uninstall' => '您确定要卸载吗?',
+	'module_table' => '模型表名',
+	'module_description' => '模型简介',
+	'module_listfields' => '列表页调用字段',
+	'module_tip_title' => '模型名称必须为2-30个字',
+	'module_tip_table' => '表名必须为2-30个字',
+	'catid'=>'栏目',
+	'catid_error'=>'必须选择一个栏目',
+	'title_error'=>'标题必须为1-80个字符',
+	'keywords'=>'关键词',
+	'description'=>'SEO简介',
+	'content'=>'内容',
+	'createtime'=>'发布时间',
+	'recommend'=>'允许评论',
+	'norecommend'=>'不允许评论',
+	'readpoint'=>'阅读收费',
+	'hits'=>'点击次数',
+	'readgroup'=>'访问权限',
+	'posid'=>'推荐位',
+	'template'=>'模板',
+	'status'=>'状态',
+	'fabu'=>'发布',
+	'dingshi'=>'定时发布',
+	'moduleishave' =>'表已经存在',
+	'module_empty_table' => '空表字段',
+	'module_news_table' => '普通文章表字段',
+	'module_table_type' => '新建表字段',
+	'module_issearch'=> '前台搜索模型',
+	'module_ispost'=> '允许前台投稿',
+	'POSTGROUP' =>'允许投稿会员组',
+	'module_addmenu' =>'添加信息',
+);
+?>

+ 100 - 0
Ainaphp/Lang/zh-cn/Admin_order.php

@@ -0,0 +1,100 @@
+<?php
+return array(
+
+	'listorder' => '排序',
+	'order_shippinged_no_edit' => '己发货订单不能修改!',
+
+	'ORDER_SN' => '订单编号',
+	'ORDER_ADD_TIME' => '创建时间',
+	'ORDER_pay_time' => '支付时间',
+	'ORDER_shipping_time' => '发货时间',
+	'ORDER_shipping_time' => '发货时间',
+	'ORDER_accept_time' => '收货时间',
+	'ORDER_SHIPPING_SHOW' => '查看物流',
+
+	'order_status' => '订单装态',
+	'pay_status' => '支付状态',
+	'shipping_status' => '配送状态',
+
+	'ORDER_STATUS_0' => '未确认',
+	'ORDER_STATUS_1' => '已确认',
+	'ORDER_STATUS_2' => '己完成',
+	'ORDER_STATUS_3' => '作废订单',
+	'ORDER_STATUS_4' => '己退货',
+	'order_status_5'=> '取消订单',
+
+	'PAY_STATUS_0' => '未支付',
+	'PAY_STATUS_1' => '付款中',
+	'PAY_STATUS_2' => '已付款',
+	'PAY_STATUS_3' => '申请退款',
+	'PAY_STATUS_4' => '己退款',
+
+	'SHIPPING_STATUS_0' => '未发货',
+	'SHIPPING_STATUS_1' => '已发货',
+	'SHIPPING_STATUS_2' => '已收货',
+	'SHIPPING_STATUS_3' => '申请换货',
+	'SHIPPING_STATUS_4' => '己换货',
+
+
+	'DO_BUT_TEXT_0' => '确认',
+	'DO_BUT_TEXT_1' => '支付',
+	'DO_BUT_TEXT_2' => '发货',
+	'DO_BUT_TEXT_3' => '完成',
+	'DO_BUT_TEXT_4' => '退款',
+	'DO_BUT_TEXT_5' => '退货',
+	'DO_BUT_TEXT_6' => '作废',
+	'DO_BUT_TEXT_7' => '取消',
+
+
+	'Order_address_info'=>'收货人信息',
+	'Order_address_area'=>'配送区域',
+	'Order_select_province'=>'请选择省份...',
+	'Order_select_city'=>'请选择城市...',
+	'Order_select_area'=>'请选择区域...',
+	'Order_address_consignee'=>'收 货 人',
+	'Order_address_address'=>'地址',
+	'Order_address_mobile'=>'手机号码',
+	'Order_address_tel'=>'固定电话',
+	'Order_address_email'=>'邮箱',
+	'Order_address_zipcode'=>'邮编',
+
+	'Order_product_info'=>'商品信息',
+	'Order_product_count'=>'合计',
+
+	'Order_payment_info'=>'费用信息',
+	'Order_product_amount'=>'商品总价',
+	'Order_amount'=>'订单总价',
+	'Order_invoice_fee'=>'发票税金',
+	'Order_pay_fee'=>'支付费用',
+	'Order_shipping_fee'=>'配送费用',
+	'Order_insure_fee'=>'配送保价',
+	'Order_discount'=>'优惠金额',
+	'Order_count_amount'=>'应付金额',
+	'Order_payment_type'=>'支付方式',
+	'Order_payment_fee'=>'手续费',
+
+	'Order_shipping_info'=>'配送方式',
+	'Order_shipping_fee'=>'运费',
+	'Order_shipping_second_price'=>'续重',
+	'Order_shipping_is_insure'=>'保价',
+	'Order_shipping_low_price'=>'最低',
+
+	'Order_shipping_sn'=>'货单号码',
+	'Order_shipping_info_1'=>'物流信息',
+
+
+	'Order_product_thumb' => '商品图片',
+	'Order_product_name' => '商品名称',
+	'Order_product_price' => '单价',
+	'Order_product_number' => '数量',
+	'Order_product_small_count' => '小计',
+
+	'Order_no_product' => '您的购物车为空!',
+	'Order_view_product' => '浏览商品',
+	'Order_invoice_fee'=>'税金',
+	'Warning'=>'警告',
+	'ORDER_EDIT_STATUS'=>'确定要修改订单状态为',
+	'PRICE'=>'价格',
+
+);
+?>

+ 56 - 0
Ainaphp/Lang/zh-cn/Admin_payment.php

@@ -0,0 +1,56 @@
+<?php
+return array(
+	'PAY_NOW'=>'立即支付',
+	'Alipay_pay_name' =>  '支付宝',
+	'Alipay_pay_desc' => '支付宝是国内领先的独立第三方支付平台,由阿里巴巴集团创办。致力于为中国电子商务提供“简单、安全、快速”的在线支付解决方案。<a href="http://www.alipay.com" target="_blank">立即在线申请</a>',
+	'alipay_account' => '支付宝帐户',
+	'alipay_key' => '交易安全校验码(key)',
+	'alipay_partner' => '合作者身份(parterID)',
+	'alipay_pay_type'  => '选择接口类型',
+	'alipay_pay_type_option1'  => '使用担保交易接口',
+	'alipay_pay_type_option2'  => '使用标准双接口',
+	'alipay_pay_type_option3'  => '使用即时到账交易接口',
+
+	'Balance_pay_name' =>'预存款支付',
+	'Balance_pay_desc'=>'使用本站会员用户预存款支付。',
+
+	'Bank_pay_name' => '银行汇款',
+	'Bank_pay_desc'=>'您可以通过现金付款或银行转帐的方式进行收款',
+
+	'tenpay_pay_name' => '财付通',
+	'tenpay_pay_desc'=>'财付通担保交易,由财付通做担保,买家确认才付款。<a href="http://union.tenpay.com" target="_blank">申请财付通担保账户</a>',
+	'tenpay_account'  => '财付通客户号',
+	'tenpay_privateKey'  => '财付通私钥',
+	'tenpay_authtype'  => '选择接口类型',
+
+	'chinabank_pay_name' => '网银在线',
+	'chinabank_pay_desc'=>'网银在线与中国银行、中国工商银行、中国农业银行、中国建设银行、招商银行等国内各大银行,以及VISA、MasterCard、JCB等国际信用卡组织保持了长期、紧密、良好的合作关系。<a href="http://www.chinabank.com.cn" target="_blank">立即在线申请</a>',
+	'chinabank_account'  => '网银在线商户号',
+	'chinabank_key'  => '网银在线MD5私钥',
+
+	'PayPal_pay_name' => 'PayPal',
+	'PayPal_pay_desc' => 'PayPal 是全球最大的在线支付平台,同时也是目前全球贸易网上支付标准。',
+	'PayPal_account'  => '签约商家Email',
+	'PayPal_key'  => 'PayPal私钥',
+
+
+	'author'=>'插件作者',
+	'version'=>'插件版本',
+	'description'=>'描述',
+	'NAME'=>'支付名称',
+	'INSTALL'=>'安装',
+	'pay_factorage'=>'支付手续费',
+	'pay_method_rate'=>'按比例收费',
+	'pay_method_fix'=>'固定费用',
+	'pay_rate'=>'费率',
+	'pay_fix'=>'金额',
+	'pay_method_rate_desc'=>'说明:顾客将支付订单总金额乘以此费率作为手续费;',
+	'pay_method_fix_desc'=>'说明:顾客每笔订单需要支付的手续费;',
+	'parameter_config'=>'参数设置',
+	'basic_config' => '基本设置',
+	'payment_mode'=>'支付方式',
+	'online' => '在线支付',
+	'UNINSTALL'=> '卸载',
+	'config'=>'配置',
+);
+?>

+ 17 - 0
Ainaphp/Lang/zh-cn/Admin_role.php

@@ -0,0 +1,17 @@
+<?php
+return array(
+	'role_prve'=>'用户权限',
+	'role_allowpost'=>'允许投稿',
+	'role_allowpostverify'=>'投稿不需审核',
+	'role_allowupgrade'=>'允许自助升级',
+	'role_allowsendmessage'=>'允许发短消息',
+	'role_allowattachment'=>'允许上传附件',
+	'role_allowsearch'=>'搜索权限',
+	'role_update'=>'升级价格',
+	'role_price_d'=>'包日',
+	'role_price_m'=>'包月',
+	'role_price_y'=>'包年',
+	'role_maxmessagenum'=>'最大短消息数',
+	'role_maxpostnum'=>'日最大投稿数',
+);
+?>

+ 25 - 0
Ainaphp/Lang/zh-cn/Admin_slide.php

@@ -0,0 +1,25 @@
+<?php
+return array(
+		'FLASHFILE'=>'FLASH文件',
+		'XMLFILE'=>'XML文件',
+		'TPL'=>'幻灯片模板',
+		'NUM'=>'图片数量',
+		'width'=>'幻灯片宽',
+		'height'=>'幻灯片高',
+		'ADDPIC'=>'添加图片',
+		'PICMANAGE'=>'图片管理',
+		'EDIT_TPL'=>'修改模板',
+		'gobacklist'=>'返回幻灯片列表',
+'images_manage'=>'图片管理',
+'return'=>'返回',
+'add_pic'=>'添加图片',
+'SMALL'=>'小图',
+'pic'=>'大图',
+'link'=>'链接',
+'clean_thumb'=>'清除图片',
+'slide_data'=>'扩展参数输入格式',
+'upload'=>'上传',
+'view'=>'预览',
+'size'=>'图片尺寸',
+);
+?>

+ 21 - 0
Ainaphp/Lang/zh-cn/Admin_template.php

@@ -0,0 +1,21 @@
+<?php
+return array(
+	'file_no_find'=>'文件不存!',
+	'delete_ok'=>'文件删除成功!',
+	'edit_ok' => '模板修改成功!',
+	'add_ok'=> '文件创建成功!',
+	'file_name'=>'文件名称',
+	'file_size'=>'文件大小',
+	'file_time'=>'修改时间',
+	'file_name'=>'文件名称',
+	'file_type_html'=>'模板文件',
+	'file_type_css'=>'CSS文件',
+	'file_type_js'=>'js文件',
+	'filename' => '文件名称',
+	'goback'=>'返回上一级',
+	'upfile'=>'上传文件',
+	'upfile_upload_ok'=>'文件上传成功!',
+	'add_tpl_param' => '添加模板参数',
+
+);
+?>

+ 6 - 0
Ainaphp/Lang/zh-cn/Admin_type.php

@@ -0,0 +1,6 @@
+<?php
+return array(
+	'add_type' => '添加子分类',
+	'type_manage' => '管理子分类',
+);
+?>

+ 13 - 0
Ainaphp/Lang/zh-cn/Admin_urlrule.php

@@ -0,0 +1,13 @@
+<?php
+return array(
+		'URL_MAKE_HTML'=>'是否生成静态?',
+		'URL_example'=>'URL示例',
+		'URL_RULE'=>'URL规则',
+		'URL_SHOW'=>'内容页',
+		'URL_LIST'=>'列表页',
+		'URL_SHOW_VAR'=>'内容页可用变量',
+		'URL_LIST_VAR'=>'列表页可用变量',
+		'URL_SHOW_README'=>'栏目目录:{$catdir} , 栏目ID:{$catid} , 模型名称:{$module}  , 模型id:{$moduleid}  ,ID:{$id} <br>年:{$year} 月:{$month},日:{$day} , 分页:{$page}<br>生成HTML页时可用父栏目路径:{$parentdir} ',
+		'URL_LIST_README'=>'栏目目录:{$catdir}  , 栏目ID:{$catid} , 模型名称:{$module}  , 模型id:{$moduleid} <br> 分页:{$page}<br>生成HTML页时可用父栏目路径:{$parentdir}',
+);
+?>

+ 227 - 0
Ainaphp/Lang/zh-cn/common.php

@@ -0,0 +1,227 @@
+<?php
+return array(
+	'welcome'=>'欢迎使用',
+	'system_name'=>'邦聚网站系统(bangju.com)',
+	'official_site' => '官方网站',
+	'authorization' => '授权',
+	'chaxun' => '查询',
+	'save' => '保存',
+	'reset' => '重置',
+	'search' => '全站搜索',
+	'delete' => '删除',
+	'delete_error' => '删除信息出错!',
+	'delete_message' => '确定要删除信息吗?',
+	'delete_ok' => '成功删除信息!',
+	'add' => '添加',
+	'add_ok' => '添加成功!',
+	'add_error' => '添加失败!',
+	'edit' => '修改',
+	'edit_ok' => '修改成功!',
+	'edit_error' => '修改失败!',
+	'exit' => '退出',
+	'listorder' => '排序',
+	'help' => '帮助中心',
+	'remark' => '描述',
+	'catname' => '栏目名称',
+    'pinyin' => '全拼',
+	'use_module' => '所属模型',
+	'fangwen' => '访问',
+	'manage' => '管理操作',
+	'dosubmit' => '提交',
+	'cancel' => '取消',
+	'yes' => '是',
+	'no' => '否',
+	'do_success' => '操作成功!',
+	'do_ok' => '提交成功!',
+	'do_error' => '操作失败!',
+	'do_empty' => '缺少必要的参数!',
+	'admin_index' => '后台首页',
+	'edit_password' => '修改密码',
+	'edit_profile' => '修改资料',
+	'realname' => '真实姓名',
+	'notepad' => '备注',
+	'email' => '邮箱',
+	'verify' => '验证码',
+	'password_error' => '密码错误',
+	'oldpassword' => '旧密码',
+	'newpassword' => '新密码',
+	'repassword' => '确认密码',
+	'error_verify' => '验证码错误!',
+	'logined' => '已经登陆',
+	'loginouted' => '已经退出登陆',
+	'empty_userid' => '帐号不存在或已禁用!',
+	'empty_username_empty_password' => '用户名和密码不能为空!',
+	'reverify' => '点击刷新验证码',
+	'load_page' => '页面加载中...',
+	'your_nav' => '您现在的位置',
+	'system_info' => '系统信息',
+	'org_url' => '官方网站',
+	'license' => '授权查询',
+	'org_bbs' => '支持论坛',
+	'login' => '登录',
+	'logout' => '退出',
+	'login_ok' => '登录成功',
+	'login_error' => '登录失败',
+	'home_index' => '浏览站点',
+	'welcome_user' => '欢迎你!',
+	'error_oldpassword' => '旧密码错误!',
+	'password_repassword' => '两次密码不一致!',
+	'name' => '名称',
+	'username' => '用户名',
+	'sex1' => '男',
+	'sex2' => '女',
+	'sex0' => '保密',
+	'sex' => '性别',
+	'question' => '问题',
+	'answer' => '答案',
+	'telephone' => '电话',
+	'mobile' => '手机号码',
+	'fax' => '传真',
+	'web_url' => '网址',
+	'address' => '地址',
+	'message_title' => '提示信息',
+	'msg_system_1' => '系统将在',
+	'msg_system_2' => '秒后自动跳转,如果不想等待,直接',
+	'click_this' => '点击这里',
+	'close' => '关闭',
+	'jump' => '跳转',
+	'account' => '帐&nbsp;&nbsp; 号',
+	'password' => '密&nbsp;&nbsp; 码',
+	'resetVerifyCode' => '点击刷新验证码',
+	'tree_1' => '│  ',
+	'tree_2' => '├─ ',
+	'tree_3' => '└─ ',
+	'open_select' => '开启',
+	'close_select' => '关闭',
+	'disable' => '禁用',
+	'enable' => '启用',
+	'status' => '状态',
+	'display_yes' =>'显示',
+	'display_no' =>'不显示',
+	'real_delete' => '确认要删除信息吗?',
+	'log_error' => '日志写入失败',
+	'select_all' => '全选',
+	'default' => '默认',
+	'examples' => '例',
+	'menu_name' => '菜单名称',
+	'menu_add_submenu' => '添加子菜单',
+	'menu_remark' => '备注',
+	'menu_option' => '参数',
+	'menu_parent_menu' => '上级',
+	'menu_top_menu' => '一级菜单',
+	'menu_model' => '模块',
+	'menu_action' => '方法',
+	'menu_type' => '类型',
+	'menu_type1' => '后台管理',
+	'menu_type2' => '会员中心',
+	'user_reg_time' => '注册时间',
+	'user_group' => '用户组',
+	'user_select_option' => '筛选',
+	'user_is_enable' => '是否激活',
+	'user_is_empty' => '用户账号必须填写!',
+	'user_is_have' => '用户账号已经存在!',
+	'email_is_empty' => '邮箱不能为空!',
+	'email_is_not' => '邮箱格式不对!',
+	'user_password_empty' => '用户密码必须填写!',
+	'email_is_have' => '邮箱已经存在!',
+	'user_list' => '用户列表',
+	'role_ok' => '授权成功!',
+	'role_error' => '授权失败!',
+	'node_name' => '节点名称',
+	'node_title' => '节点标题',
+	'node_name_empty' => '节点名称不能为空!',
+	'node_title_empty' => '节点标题不能为空',
+	'title' => '标题',
+	'menu_user_is_empty' => '菜单名称不能为空!',
+	'menu_model_is_empty' => '菜单模块名不能为空!',
+	'keywords' => '关键词',
+	'createtime' => '发布时间',
+	'hits' => '点击',
+	'select_category' => '选择栏目',
+	'select_posids' => '选择推荐位',
+	'please_chose' => '请选择',
+	'select_typeid' => '请选择类别',
+	'news_title' => '标题',
+	'news_chose_catid' => '选择栏目',
+	'thumb' => '缩略图',
+	'news_keywords'=>'SEO关键词',
+	'news_description'=>'SEO简介',
+	'clean_thumb' => '取消缩略图',
+	'description' => '简介',
+	'copyfrom' => '来源',
+	'fromlink' => '来源网址',
+	'readgroup' => '访问权限',
+	'linkurl' => '链接地址',
+	'template' => '模板',
+	'posid' => '推荐位',
+	'content' => '内容',
+	'uploadfiles' => '文件上传',
+	'start_upload' => '开始上传',
+	'file_list' => '文件列表',
+	'upload_ok' => '上传成功!',
+	'remove' => '移除',
+	'PREVIOUS' => '上一页',
+	'PAGE_ITEM' => '条',
+	'NEXT' => '下一页',
+	'FIRST_PAGE'=> '第一页',
+	'LAST_PAGE'=> '最后一页',
+	'readpoint' => '阅读收费',
+	'publish' => '发布',
+	'date_publish' => '定时发布',
+	'style_bold' => '加粗',
+	'page_break' =>'[插入分页符]',
+	'add_description'=>'是否截取内容',
+	'description_length'=>'字符至内容摘要',
+	'auto_thumb'=>'是否获取内容第',
+	'auto_thumb_no'=>'张图片作为标题图片',
+	'posid_name'=>'推荐位名称',
+	'error_catid_is_empty'=>'请选择栏目!',
+	'error_title_is_empty'=>'标题必须为3-100个字符',
+	'error_content_is_empty'=>'内容不能为空',
+	'order_by_desc'=>'递减',
+	'order_by_asc'=>'递增',
+	'listRows'=>'条每页',
+	'module_field'=>'模型字段',
+	'mailsed_ok'=>'邮件发送成功!',
+	'mailsed_error'=>'邮件发送失败!',
+	'width'=>'宽',
+	'height'=>'高',
+	'PAGE_LISTROWS'=>'列表分页数',
+	'duihao'=>'<font color="green">√</font>',
+	'xuohao'=>'<font color="red"">×</font>',
+	'upload_files'=>'文件上传',
+	'upload_images'=>'图片上传',
+	'upload_maxfiles'=>'最多同时可以上传',
+	'zhang'=>'张',
+	'remove'=>'移除',
+	'no_login'=>'你还未登陆系统',
+	'logined_ok'=>'登陆成功!',
+	'DEFAULT_THEME'=>'默认模板',
+	'HOME_ISHTML'=>'首页生成html',
+	'ci' => '次',
+	'CREATE_TABLE_OK' => '成功导入数据表:',
+	'isshenhe' => '已审核',
+	'noshenhe' => '未审核',
+	'click_this'=>'点击这里',
+	'NO_HOME_ISHTML' => '没有开启首页生成HTML',
+	'status_ok' => '通过审核',
+	'DEFAULT_LANG' => '默认语言',
+	'LANG_NAME'=> '语言名称',
+	'LANG_MARK'=> '语言标识',
+	'LANG_FLAG'=> '语言图标',
+	'LANG_PATH'=> '语言目录',
+	'LANG_DOMAIN'=> '语言域名',
+	'LANG_module'=> '模块语言包',
+	'LANG_common'=> '公共语言包',
+	'LANG_ADD_PARAM'=> '添加语言参数',
+	'param_name'=>'参数名',
+	'param_value'=>'参数值',
+	'value_empty'=>'值不能为空!',
+	'_TOKEN_ERROR_'=>'表单验证失败',
+	'UPDATE_CACHE'=> '更新缓存',
+	'_VALID_ACCESS_'=>'你没有操作此操作的权限!',
+	'GROUP'=>'分组',
+	'ACCESS_PUBLIC'=>'全局设置',
+	'TIME'=>'时间',
+);
+?>

+ 84 - 0
Ainaphp/Lib/Action/Admin/AccessAction.class.php

@@ -0,0 +1,84 @@
+<?php
+/**
+ *
+ * Access (权限设置)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class AccessAction extends AdminbaseAction {
+
+	protected $dao;
+
+    function _initialize()
+    {
+		parent::_initialize();
+		$this->dao=M('Access');
+    }
+
+	function index(){
+
+		$rid=intval($_GET['rid']);
+		$alist = $this->dao->where('role_id = '.$rid)->getField('node_id,role_id');
+		$node=M('Node');
+
+		$r=$node->where("pid=0 and status=1")->select();
+
+		$this->assign('topnode', $r);
+
+		$groups[0]=array('id'=>0,'name'=>L('ACCESS_PUBLIC'));
+		foreach($this->menudata as $key=>$r){ if($r['parentid']==0)$groups[$r[id]]=$r;}
+		$this->assign('groups', $groups);
+
+
+		foreach($groups as $key=>$res){
+			$result=$node->where("groupid=$res[id] and status=1")->select();
+			$array=array();
+			foreach($result as $r) {
+				$r['parentid']=$r['pid'];
+				$r['selected'] = array_key_exists($r['id'],$alist)   ? 'checked' : '';
+				$array[] = $r;
+			}
+			$nodes[$res['id']]['data']  =$array;
+			$nodes[$res['id']]['groupinfo']=$res;
+		}
+
+		$node_app=$this->dao->where("pid=0 and status=1")->select();
+		$this->assign('node_app', $node_app);
+
+		$this->assign('alist', $alist);
+		$this->assign('node', $nodes);
+		$this->assign('rid', $rid);
+		$this->display();
+	}
+
+	function insert(){
+		$rid=$_POST['rid'];
+		$nid=$_POST['nid'];
+		if(!empty($rid)){
+			if($nid){
+				$node_id=implode(',',$nid);
+				$node=M('Node');
+				$list=$node->where('id in('.$node_id.')')->select();
+				$this->dao->where('role_id = '.$rid)->delete();
+				foreach($list as $key=> $node){
+					$data[$key]['role_id']=$rid;
+					$data[$key]['node_id']=$node['id'];
+					$data[$key]["level"]=$node['level'];
+					$data[$key]["pid"]=$node['pid'];
+				}
+				$r=$this->dao->addAll($data);
+			}else{
+				$r= $this->dao->where('role_id = '.$rid)->delete();
+			}
+			if(false!==$r){
+				$this->success(L('role_ok'));
+			}else{
+				$this->error(L('role_error'));
+			}
+
+		}else{
+			$this->error(L('do_empty'));
+		}
+	}
+}
+?>

+ 206 - 0
Ainaphp/Lib/Action/Admin/AttachmentAction.class.php

@@ -0,0 +1,206 @@
+<?php
+/**
+ *
+ * Attachment(附件管理)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class AttachmentAction extends  Action {
+
+	protected $lang,$dao,$Config,$sysConfig,$isadmin=0,$userid=0,$groupid=0;
+    function _initialize()
+    {
+		$this->isadmin= $_REQUEST['isadmin'] ? $_REQUEST['isadmin'] : 0;
+		$this->sysConfig = F('sys.config');
+		if(APP_LANG){
+			$this->Lang = F('Lang');
+			$this->assign('Lang',$this->Lang);
+			if($_GET['l']){
+				if(!$this->Lang[$_GET['l']]['status'])$this->error ( L ( 'NO_LANG' ) );
+				$lang=$_GET['l'];
+			}else{
+				$lang=$this->sysConfig['DEFAULT_LANG'];
+			}
+			define('LANG_NAME', $lang);
+			define('LANG_ID', $this->Lang[$lang]['id']);
+
+			$this->Config = F('Config_'.LANG_NAME);
+		}else{
+			$this->Config = F('Config');
+		}
+
+		if($_POST['PHPSESSID'] && $_POST['swf_auth_key'] && $_POST['userid']){
+			if($_POST['swf_auth_key']==sysmd5($_POST['PHPSESSID'].$_POST['userid'],$this->sysConfig['ADMIN_ACCESS'])){
+				$this->userid = $_POST['userid'];
+				if(APP_LANG) $this->Config = F('Config_'.$_POST['lang']);
+			}
+		}
+		if(!$this->userid){
+			if($this->isadmin){
+				import('@.Action.Adminbase');
+				$Adminbase=new AdminbaseAction();
+				$Adminbase->_initialize();
+				$this->userid=  $_SESSION[C('USER_AUTH_KEY')];
+				$this->groupid=  $_SESSION['groupid'];
+			}else{
+				C('ADMIN_ACCESS',$this->sysConfig['ADMIN_ACCESS']);
+				if($_COOKIE['YP_auth']){
+					if(!strstr($_SERVER['HTTP_USER_AGENT'],'Flash'))cookie('YP_cookie',$_SERVER['HTTP_USER_AGENT']);
+					$HTTP_USER_AGENT = strstr($_SERVER['HTTP_USER_AGENT'],'Flash') ? $_COOKIE['YP_cookie'] : $_SERVER['HTTP_USER_AGENT'];
+					$yourphp_auth_key = sysmd5($this->sysConfig['ADMIN_ACCESS'].$HTTP_USER_AGENT);
+					list($userid, $groupid ,$password) = explode("-", authcode($_COOKIE['YP_auth'], 'DECODE', $yourphp_auth_key));
+					$this->userid = $userid;
+					$this->groupid = $groupid;
+				}
+				if(!$this->userid){
+					$this->assign('jumpUrl',U('User/Login/index'));
+					$this->error(L('no_login'));
+				}
+			}
+		}
+		$this->assign($this->Config);
+
+		$this->dao=M('Attachment');
+    }
+	public function index(){
+
+		$auth = str_replace(' ','+',$_REQUEST['auth']) ;
+
+		$postd=array('isadmin','more','isthumb','file_limit','file_types','file_size','moduleid');
+		foreach((array)$_REQUEST as $key=>$res){
+			if(in_array($key,$postd))$postdata[$key]=$res;
+		}
+		$upsetup = implode('-',$postdata);
+		$yourphp_auth_key = sysmd5(C('ADMIN_ACCESS').$_SERVER['HTTP_USER_AGENT']);
+		$enupsetup = authcode($auth, 'DECODE', $yourphp_auth_key);
+		if(!$enupsetup || $upsetup!=$enupsetup)  $this->error (L('do_empty'));
+
+		$sessid = time();
+
+		$count = $this->dao->where('status=0 and userid ='.$this->userid)->count();
+		$this->assign('no_use_files',$count);
+		$this->assign('small_upfile_limit',$_REQUEST['file_limit'] - $count);
+
+
+		$types = '*.'.str_replace(",",";*.",$_REQUEST['file_types']); ;
+		$this->assign('moduleid',$_REQUEST['moduleid']);
+		$this->assign('file_size',$_REQUEST['file_size']);
+		$this->assign('file_limit',$_REQUEST['file_limit']);
+		$this->assign('file_types',$types);
+		$this->assign('isthumb',$_REQUEST['isthumb']);
+		$this->assign('isadmin',$this->isadmin);
+		$this->assign('sessid',$sessid);
+		$this->assign('lang',LANG_NAME);
+		$this->assign('userid',$this->userid);
+		$swf_auth_key = sysmd5($sessid.$this->userid);
+
+		$this->assign('swf_auth_key',$swf_auth_key);
+		$this->assign('more',$_GET['more']);
+		$this->display();
+	}
+
+	public function upload(){
+		//if($_POST['swf_auth_key']!= sysmd5($_POST['PHPSESSID'].$this->userid)) $this->ajaxReturn(0,'1-'.$_POST['PHPSESSID'],0);
+
+		import("@.ORG.UploadFile");
+        $upload = new UploadFile();
+		//$upload->supportMulti = false;
+        //设置上传文件大小
+        $upload->maxSize = $this->Config['attach_maxsize'];
+		$upload->autoSub = true;
+		$upload->subType = 'date';
+		$upload->dateFormat = 'Ym';
+        //设置上传文件类型
+        $upload->allowExts = explode(',', $this->Config['attach_allowext']);
+        //设置附件上传目录
+        $upload->savePath = UPLOAD_PATH;
+		 //设置上传文件规则
+        $upload->saveRule = uniqid;
+
+
+        //删除原图
+        $upload->thumbRemoveOrigin = true;
+        if (!$upload->upload()) {
+			$this->ajaxReturn(0,$upload->getErrorMsg(),0);
+        } else {
+            //取得成功上传的文件信息
+            $uploadList = $upload->getUploadFileInfo();
+
+
+			if($_REQUEST['addwater']){ //$this->Config['watermark_enable']  $_REQUEST['addwater']
+				import("@.ORG.Image");
+				Image::watermark($uploadList[0]['savepath'].$uploadList[0]['savename'],'',$this->Config);
+			}
+
+			$imagearr = explode(',', 'jpg,gif,png,jpeg,bmp,ttf,tif');
+			$data=array();
+			$model = M('Attachment');
+			//保存当前数据对象
+			$data['moduleid'] = $_REQUEST['moduleid'];
+			$data['catid'] = 0;
+			$data['userid'] = $_REQUEST['userid'];
+			$data['filename'] = $uploadList[0]['name'];
+			$data['filepath'] = __ROOT__.substr($uploadList[0]['savepath'].strtolower($uploadList[0]['savename']),1);
+			$data['filesize'] = $uploadList[0]['size'];
+			$data['fileext'] = strtolower($uploadList[0]['extension']);
+			$data['isimage'] = in_array($data['fileext'],$imagearr) ? 1 : 0;
+			$data['isthumb'] = intval($_REQUEST['isthumb']);
+			$data['createtime'] = time();
+			$data['uploadip'] = get_client_ip();
+			$aid = $model->add($data);
+			$returndata['aid']		= $aid;
+			$returndata['filepath'] = $data['filepath'];
+			$returndata['fileext']  = $data['fileext'];
+			$returndata['isimage']  = $data['isimage'];
+			$returndata['filename'] = $data['filename'];
+			$returndata['filesize'] = $data['filesize'];
+
+			$this->ajaxReturn($returndata,L('upload_ok'), '1');
+        }
+	}
+
+	public function filelist(){
+
+		$where= $_REQUEST['typeid'] ?  " status=1 " : " status=0 ";
+		$where .=" and userid = ".$this->userid ;
+		import ( '@.ORG.Page' );
+		$count = $this->dao->where($where)->count();
+		$page=new Page($count,12);
+		$imagearr = explode(',', 'jpg,gif,png,jpeg,bmp,ttf,tif');
+
+		$page->urlrule = 'javascript:ajaxload('.$_REQUEST['typeid'].',{$page},\''.$_REQUEST['inputid'].'\','.$this->isadmin.');';
+		$show = $page->show();
+		$this->assign("page",$show);
+		$list=$this->dao->order('aid desc')->where($where)
+		->limit($page->firstRow.','.$page->listRows)->select();
+		foreach((array)$list as $key=>$r){
+		$list[$key]['thumb']=in_array($r['fileext'],$imagearr) ? $r['filepath'] : __ROOT__.'/Public/Images/ext/'.$r['fileext'].'.png';
+		}
+		$this->assign('list',$list);
+		$this->display();
+	}
+
+	function delfile($aid){
+		if(empty($aid)){
+		$aid=$_REQUEST['aid'];
+		}
+		$r = delattach(array('aid'=>$aid,'userid'=>$this->userid));
+		if($r){
+			$this->success ( L ( 'delete_ok' ) );
+		}else{
+			$this->error ( L ( 'delete_error' ) );
+		}
+
+	}
+	function cleanfile(){
+
+		$r = delattach(array('status'=>0,'userid'=>$this->userid));
+		if($r){
+			$this->success ( L ( 'delete_ok' ) );
+		}else{
+			$this->error ( L ( 'delete_error' ) );
+		}
+	}
+
+}
+?>

+ 66 - 0
Ainaphp/Lib/Action/Admin/BlockAction.class.php

@@ -0,0 +1,66 @@
+<?php
+/**
+ *
+ * Posid (推荐位管理)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class BlockAction extends AdminbaseAction {
+
+	protected $dao,$Type;
+    function _initialize()
+    {
+		parent::_initialize();
+		$this->dao = M(MODULE_NAME);
+		$this->Type=F('Type');
+
+    }
+
+	public function index() {
+		if(APP_LANG)$map['lang']=array('eq',LANG_ID);
+		$this->_list(MODULE_NAME, $map);
+        $this->display();
+    }
+
+	public function _before_insert()
+    {
+		 if(APP_LANG)$_POST['lang']=LANG_ID;
+	}
+	public function edit() {
+		$pos=strip_tags($_REQUEST['pos']);
+		$name = MODULE_NAME;
+		$model = M ( $name );
+		$pk=ucfirst($model->getPk ());
+		$id = $_REQUEST [$model->getPk ()];
+		if(empty($id))   $this->error(L('do_empty'));
+		if($pos){
+			$map['pos']=array('eq',$pos);
+			if(APP_LANG)$map['lang']=array('eq',LANG_ID);
+			$vo = $model->where($map)->find();
+		}else{
+			$do='getBy'.$pk;
+			$vo = $model->$do ( $id );
+		}
+		if($vo['setup']) $vo['setup']=string2array($vo['setup']);
+		$this->assign ( 'vo', $vo );
+		$this->display ();
+	}
+
+	function delete(){
+		$name = MODULE_NAME;
+		$model = M ( $name );
+		$pk = $model->getPk ();
+		$id = $_REQUEST [$pk];
+		if (isset ( $id )) {
+			if(false!==$model->delete($id)){
+				delattach(array('moduleid'=>'231','id'=>$id));
+				$this->success(L('delete_ok'));
+			}else{
+				$this->error(L('delete_error').': '.$model->getDbError());
+			}
+		}else{
+			$this->error (L('do_empty'));
+		}
+	}
+}
+?>

+ 389 - 0
Ainaphp/Lib/Action/Admin/CategoryAction.class.php

@@ -0,0 +1,389 @@
+<?php
+/**
+ *
+ * Category(分类)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class CategoryAction extends AdminbaseAction
+{
+    protected $dao,$categorys,$module;
+    function _initialize()
+    {
+        parent::_initialize();
+        foreach ((array)$this->module as $rw){
+			if($rw['type']==1 && $rw['status']==1)  $data['module'][$rw['id']] = $rw;
+        }
+		$this->module=$data['module'];
+        $this->assign($data);
+		unset($data);
+        $this->dao = D('Admin/category');
+    }
+
+    /**
+     * 列表
+     *
+     */
+    public function index()
+    {
+        if($this->categorys){
+			foreach($this->categorys as $r) {
+				if($r['module']=='Page'){
+					$r['str_manage'] = '<a href="?g=Admin&m=Page&a=edit&id='.$r['id'].'">'.L('edit_page').'</a> | ';
+				}else{
+					$r['str_manage'] = '<a href="'.U('Category/add',array( 'parentid' => $r['id'],'type'=>$r['type'])).'">'.L('add_catname').'</a> | ';
+				}
+				$r['str_manage'] .= '<a href="'.U('Category/edit',array( 'id' => $r['id'],'type'=>$r['type'])).'">'.L('edit').'</a> | <a href="javascript:confirm_delete(\''.U('Category/delete',array( 'id' => $r['id'])).'\')">'.L('delete').'</a> ';
+				$r['modulename']=$this->module[$r['moduleid']]['title'] ? $this->module[$r['moduleid']]['title'] : L('Module_url');
+				$r['dis'] =  $r['ismenu'] ? '<font color="green">'.L('display_yes').'</font>' : '<font color="red">'.L('display_no').'</font>' ;
+				$array[] = $r;
+			}
+			$str  = "<tr>
+						<td width='40' align='center'><input name='listorders[\$id]' type='text' size='3' value='\$listorder' class='input-text-c'></td>
+						<td align='center'>\$id</td>
+						<td >\$spacer\$catname &nbsp;</td>
+						<td align='center'>\$modulename</td>
+						<td align='center'><a href='\$url' target='_blank'>".L('fangwen')."</a></td>
+						<td align='center'>\$str_manage</td>
+					</tr>";
+			import ( '@.ORG.Tree' );
+			$tree = new Tree ($array);
+			unset($array);
+			$tree->icon = array('&nbsp;&nbsp;&nbsp;<span>'.L('tree_1').'</span>','&nbsp;&nbsp;&nbsp;<span>'.L('tree_2').'</span>','&nbsp;&nbsp;&nbsp;<span>'.L('tree_3').'</span>');
+			$tree->nbsp = '&nbsp;&nbsp;&nbsp;';
+			$categorys = $tree->get_tree(0, $str);
+			$this->assign('categorys', $categorys);
+		}
+        $this->display();
+    }
+
+	public function _before_add()
+    {
+
+		foreach((array)$this->Urlrule as $key =>$r){
+			if($r['ishtml'])$Urlrule[$key]=$r;
+		}
+		$this->assign('Urlrule', $Urlrule);
+
+
+		$yourphp_auth_key = sysmd5(C('ADMIN_ACCESS').$_SERVER['HTTP_USER_AGENT']);
+		$yourphp_auth = authcode('1-1-0-1-jpeg,jpg,png,gif-3-0', 'ENCODE',$yourphp_auth_key);
+		$this->assign('yourphp_auth',$yourphp_auth);
+
+
+		$templates= template_file();
+		$this->assign ( 'templates',$templates );
+
+		$parentid =	intval($_GET['parentid']);
+		$vo['ismenu']=1;
+		$vo['moduleid'] =$this->categorys[$parentid]['moduleid'];
+		$this->assign('vo', $vo);
+		foreach($this->categorys as $r) {
+			$array[] = $r;
+		}
+		import ( '@.ORG.Tree' );
+		$str  = "<option value='\$id' \$selected>\$spacer \$catname</option>";
+		$tree = new Tree ($array);
+		$select_categorys = $tree->get_tree(0, $str,$parentid);
+		$usergroup=F('Role');
+		$this->assign('rlist',$usergroup);
+		$this->assign('select_categorys', $select_categorys);
+	}
+
+    /**
+     * 提交录入
+     *
+     */
+    public function insert()
+    {
+
+		/*
+		if($_POST['parentid']){
+			if($_POST['moduleid']!=$this->categorys[$_POST['parentid']]['moduleid']){
+				$this->success(L('chose_notop_module'));
+			}
+		}
+		*/
+		if(empty($_POST['urlruleid']) && $_POST['ishtml']) $this->error(L('do_empty'));
+		$_POST['readgroup'] = $_POST['readgroup'] ? implode(',',$_POST['readgroup']) : '';
+		$_POST['postgroup'] = $_POST['postgroup'] ? implode(',',$_POST['postgroup']) : '';
+
+
+
+		$_POST['module'] = $this->module[$_POST['moduleid']]['name'] ? $this->module[$_POST['moduleid']]['name'] : '';
+		$_POST['moduleid']= intval($_POST['moduleid']);
+		if(APP_LANG)$_POST['lang']=LANG_ID;
+        if($this->dao->create())
+        {
+			$id = $this->dao->add();
+            if($id)
+            {
+				if($_POST['module']=='Page'){
+					$_POST['id']=$id;
+					if(empty($_POST['title']))$_POST['title'] = $_POST['catname'];
+					$Page=D('Page');
+					if($Page->create()){
+						$Page->add();
+					}
+				}
+
+				if($_POST['aid']) {
+					$Attachment =M('Attachment');
+					$aids =  implode(',',$_POST['aid']);
+					$data['catid']= $_POST['catid'];
+					$data['moduleid']= $_POST['moduleid'];
+					$data['status']= '1';
+					$Attachment->where("aid in (".$aids.")")->save($data);
+				}
+
+				$this->repair();
+				savecache('Category');
+
+
+				if($_POST['ishtml']){
+					$this->categorys = F('Category');
+					$cat = $this->categorys[$id];
+					$arrparentid = array_filter(explode(',',$cat['arrparentid'].','.$cat['id']));
+					foreach($arrparentid as $catid) {
+						if($this->categorys[$catid]['ishtml'])	$this->clisthtml($catid);
+					}
+					if($this->sysConfig['HOME_ISHTML']) $this->create_index();
+				}
+				$this->assign ( 'jumpUrl', U(MODULE_NAME.'/index') );
+                $this->success(L('add_ok'));
+			}else{
+			   $this->error(L('add_error'));
+			}
+        }else{
+            $this->error($this->dao->getError());
+        }
+    }
+
+    /**
+     * 编辑
+     *
+     */
+    public function edit()
+    {
+		$id = intval($_GET['id']);
+
+		foreach((array)$this->Urlrule as $key =>$r){
+			if($r['ishtml'])$Urlrule[$key]=$r;
+		}
+		$this->assign('Urlrule', $Urlrule);
+
+		$yourphp_auth_key = sysmd5(C('ADMIN_ACCESS').$_SERVER['HTTP_USER_AGENT']);
+		$yourphp_auth = authcode('1-1-0-1-jpeg,jpg,png,gif-3-0', 'ENCODE',$yourphp_auth_key);
+		$this->assign('yourphp_auth',$yourphp_auth);
+
+		$templates= template_file();
+		$this->assign ( 'templates',$templates );
+
+        $record = $this->categorys[$id];
+		$record['readgroup'] = explode(',',$record['readgroup']);
+        if(empty($id) || empty($record)) $this->error(L('do_empty'));
+
+       	$parentid =	intval($record['parentid']);
+		import ( '@.ORG.Tree' );
+		$result = $this->categorys;
+		foreach($result as $r) {
+			//if($r['type']==1) continue;
+			$r['selected'] = $r['id'] == $parentid ? 'selected' : '';
+			$array[] = $r;
+		}
+		$str  = "<option value='\$id' \$selected>\$spacer \$catname</option>";
+		$tree = new Tree ($array);
+		$select_categorys = $tree->get_tree(0, $str,$parentid);
+		$this->assign('select_categorys', $select_categorys);
+        $this->assign('vo', $record);
+		$usergroup=F('Role');
+		$this->assign('rlist',$usergroup);
+		$this->display ();
+
+    }
+
+    /**
+     * 提交编辑
+     *
+     */
+    public function update()
+    {
+		if(empty($_POST['urlruleid']) && $_POST['ishtml']) $this->error(L('do_empty'));
+		$_POST['module'] = $this->module[$_POST['moduleid']]['name'];
+		$_POST['readgroup'] = $_POST['readgroup'] ? implode(',',$_POST['readgroup']) : '';
+		$_POST['postgroup'] = $_POST['postgroup'] ? implode(',',$_POST['postgroup']) : '';
+		$_POST['arrparentid'] = $this->get_arrparentid($_POST['id']);
+		if(empty($_POST['listtype']))$_POST['listtype']=0;
+
+
+		if($_POST['type']){
+			$_POST['moduleid']=0;
+			$_POST['module']='';
+		}
+		if (false === $this->dao->create ()) {
+			$this->error ( $this->dao->getError () );
+		}
+		if (false !== $this->dao->save ()) {
+
+			if($_POST['aid']) {
+					$Attachment =M('Attachment');
+					$aids =  implode(',',$_POST['aid']);
+					$data['moduleid']= $_POST['moduleid'];
+					$data['catid']= $_POST['id'];
+					$data['status']= '1';
+					$Attachment->where("aid in (".$aids.")")->save($data);
+				}
+
+			if($_POST['chage_all']){
+				$data=array();
+				$arrchildid = $this->get_arrchildid($_POST['id']);
+				$data['urlruleid'] = $_POST['urlruleid'] ? $_POST['urlruleid'] : '0' ;
+				$data['presentpoint'] = $_POST['presentpoint'];
+				$data['postgroup'] = $_POST['postgroup'] ? $_POST['postgroup'] : '';
+				$data['chargepoint'] = $_POST['chargepoint'];
+				$data['paytype'] = $_POST['paytype'];
+				$data['repeatchargedays'] = $_POST['repeatchargedays'];
+				$data['ismenu'] = $_POST['ismenu'];
+				$data['ishtml'] = $_POST['ishtml'];
+				$data['pagesize'] = $_POST['pagesize'];
+				$data['template_list'] = $_POST['template_list'];
+				$data['template_show'] = $_POST['template_show'];
+				$data['readgroup'] = $_POST['readgroup'] ? $_POST['readgroup'] : '';
+				$r = $this->dao->where( ' id in ('.$arrchildid.')')->data($data)->save();
+			}
+			$this->repair();
+			$this->repair();
+			savecache('Category');
+			if($_POST['ishtml']){
+				$cat=$this->categorys[$_POST['id']];
+				$arrparentid = array_filter(explode(',',$cat['arrparentid'].','.$cat['id']));
+				foreach($arrparentid as $catid) {
+					if($this->categorys[$catid]['ishtml'])	$this->clisthtml($catid);
+				}
+				if($this->sysConfig['HOME_ISHTML']) $this->create_index();
+			}
+			$this->assign ( 'jumpUrl', U(MODULE_NAME.'/index') );
+			$this->success (L('edit_ok'));
+		} else {
+			$this->success (L('edit_error').': '.$this->dao->getDbError());
+		}
+
+    }
+
+	public function repair_cache() {
+		$this->repair();
+		$this->repair();
+		savecache('Category');
+		$this->assign ( 'jumpUrl', U(MODULE_NAME.'/index') );
+		$this->success(L('do_success'));
+	}
+
+	public function repair() {
+
+		@set_time_limit(500);
+		$this->categorys = $categorys = array();
+		if(APP_LANG)$langwhere =  " and lang = ".LANG_ID;
+		$categorys = $this->dao->where("parentid=0".$langwhere)->Order('listorder ASC,id ASC')->select();
+		$this->set_categorys($categorys);
+		if(is_array($this->categorys)) {
+			foreach($this->categorys as $id => $cat) {
+				//if($id == 0 || $cat['type']==1) continue;
+				$this->categorys[$id]['arrparentid'] = $arrparentid = $this->get_arrparentid($id);
+				$this->categorys[$id]['arrchildid'] = $arrchildid = $this->get_arrchildid($id);
+				$this->categorys[$id]['parentdir'] =	$cat['parentdir'] = $parentdir = $this->get_parentdir($id);
+
+				$child = is_numeric($arrchildid) ? 0 : 1;
+				if( $cat['type']==1){
+					$url=$cat['url'];
+				}else{
+					$url =  geturl($cat,'',$this->Urlrule);
+					$url = $url[0];
+				}
+				$this->dao->save(array('url'=>$url,'parentdir'=>$parentdir,'arrparentid'=>$arrparentid,'arrchildid'=>$arrchildid,'child'=>$child,'id'=>$id));
+			}
+		}
+	}
+
+	public function set_categorys($categorys = array()) {
+		if (is_array($categorys) && !empty($categorys)) {
+			foreach ($categorys as $id => $c) {
+				$this->categorys[$c[id]] = $c;
+				if(APP_LANG)$langwhere =  " and lang = ".LANG_ID;
+				$r = $this->dao->where("parentid = $c[id]".$langwhere)->Order('listorder ASC,id ASC')->select();
+				$this->set_categorys($r);
+			}
+		}
+		return true;
+	}
+
+	public function get_parentdir($id) {
+		if($this->categorys[$id]['parentid']==0) return '';
+
+		$arrparentid = $this->categorys[$id]['arrparentid'];
+		unset($r);
+		if ($arrparentid) {
+				$arrparentid = explode(',', $arrparentid);
+				$arrcatdir = array();
+				foreach($arrparentid as $pid) {
+					if($pid==0) continue;
+					$arrcatdir[] = $this->categorys[$pid]['catdir'];
+				}
+				return implode('/', $arrcatdir).'/';
+		}
+	}
+
+
+	public function get_arrparentid($id, $arrparentid = '') {
+		if(!is_array($this->categorys) || !isset($this->categorys[$id])) return false;
+		$parentid = $this->categorys[$id]['parentid'];
+		$arrparentid = $arrparentid ? $parentid.','.$arrparentid : $parentid;
+		if($parentid) {
+			$arrparentid = $this->get_arrparentid($parentid, $arrparentid);
+		} else {
+			$this->categorys[$id]['arrparentid'] = $arrparentid;
+		}
+		return $arrparentid;
+	}
+
+	public function get_arrchildid($id) {
+		$arrchildid = $id;
+		if(is_array($this->categorys)) {
+			foreach($this->categorys as $catid => $cat) {
+				if($cat['parentid'] && $id != $catid) {
+					$arrparentids = explode(',', $cat['arrparentid']);
+					if(in_array($id, $arrparentids)) $arrchildid .= ','.$catid;
+				}
+			}
+		}
+		return $arrchildid;
+	}
+
+	public function delete() {
+		$catid = intval($_GET['id']);
+		$module = $this->categorys[$catid]['module'];
+		if($this->categorys[$catid]['type']==1){
+			if($this->categorys[$catid]['arrchildid']!=$catid)$this->error(L('category_does_not_allow_delete'));
+			$this->dao->delete($catid);
+			delattach("catid in($catid)");
+		}else{
+			$module  = M($module);
+			$arrchildid = $this->categorys[$catid]['arrchildid'];
+			$where =  "catid in(".$arrchildid.")";
+			$count = $module->where($where)->count();
+			if($count) $this->error(L('category_does_not_allow_delete'));
+			$this->dao->delete($arrchildid);
+			$moduleid = $this->mod[$module];
+			delattach("moduleid =$moduleid and catid in($arrchildid)");
+			$arr=explode(',',$arrchildid);
+			foreach((array)$arr as $r){
+				if($this->categorys[$r]['module']=='Page'){
+				$module=M('Page');
+				$module->delete($r);
+				}
+			}
+		}
+		$this->repair();
+		savecache('Category');
+		$this->success(L('do_success'));
+	}
+}

+ 150 - 0
Ainaphp/Lib/Action/Admin/ConfigAction.class.php

@@ -0,0 +1,150 @@
+<?php
+
+/**
+ *
+ * Config(系统配置文件)
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class ConfigAction extends AdminbaseAction {
+
+	protected $dao, $config,$seo_config ,$user_config, $site_config, $mail_config, $attach_config;
+    function _initialize()
+    {
+		parent::_initialize();
+		$this->dao = M('Config');
+		$this->assign($this->Config);
+
+    }
+	public function index() {
+
+		$this->config = $config = $this->dao->select();
+
+		foreach($config as $key=>$r) {
+			if($r['groupid']==1){
+				if(APP_LANG){
+					if($r['lang']==LANG_ID) $this->user_config[$r['varname']]=$r;
+				}else{
+					$this->user_config[$r['varname']]=$r;
+				}
+			}
+			if($r['groupid']==2){
+				if(APP_LANG){
+					if($r['lang']==LANG_ID) $this->site_config[$r['varname']]=$r;
+				}else{
+					$this->site_config[$r['varname']]=$r;
+				}
+			}
+		}
+		$this->assign('user_config',$this->user_config);
+		$this->assign('site_config',$this->site_config);
+		$this->display();
+	}
+
+	public function sys() {
+		$sysconfig = F("sys.config");
+		$Urlrule=array();
+		foreach((array)$this->Urlrule as $key => $r){
+			$urls=$r['showurlrule'].':::'.$r['listurlrule'];
+			if(empty($r['ishtml']))$Urlrule[$urls]=L('URL_SHOW_URLRULE').":".$r['showexample'].", ".L('URL_LIST_URLRULE').":".$r['listexample'];
+		}
+		$this->assign('Urlrule',$Urlrule);
+
+		$this->assign('Lang',F('Lang'));
+		$this->assign('yesorno',array(0 => L('no'),1  => L('yes')));
+		$this->assign('openarr',array(0 => L('close_select'),1  => L('open_select')));
+		$this->assign('enablearr',array(0 => L('disable'),1  => L('enable')));
+		$this->assign('urlmodelarr',array(0 => L('URL_MODEL0').'(m=module&a=action&id=1)',1  => L('URL_MODEL1').'(index.php/Index_index_id_1)',2 => L('URL_MODEL2').'(Index_index_id_1)'));
+		$this->assign('readtypearr', array(0=>'readfile',1=> 'redirect'));
+		$this->assign($sysconfig);
+		$this->display();
+	}
+
+
+	public function add() {
+		$this->display();
+	}
+
+	public function delete() {
+
+		$name = MODULE_NAME;
+		$model = M ( $name );
+		$id = $_REQUEST ['varname'];
+		if (isset ( $id )) {
+			if(false!==$model->where("varname='$id'")->delete()){
+				if(in_array($name,$this->cache_model)) savecache($name);
+				$this->success(L('delete_ok'));
+			}else{
+				$this->error(L('delete_error').': '.$model->getDbError());
+			}
+		}else{
+			$this->error (L('do_empty'));
+		}
+
+	}
+
+	public function insert() {
+
+		if(APP_LANG)$_POST['lang']=LANG_ID;
+
+		if (false === $this->dao->create ()) {
+			$this->error ( $this->dao->getError () );
+		}
+		$list=$this->dao->add ();
+		savecache('Config');
+		if ($list!==false) {
+			$this->success (L('add_ok'));
+		}else{
+			$this->error (L('add_error'));
+		}
+	}
+
+	public function member() {
+
+		if(APP_LANG)$where = ' and lang='.LANG_ID;
+		$config = $this->dao->where("groupid=3".$where)->select();
+		$this->assign('member_config',$config);
+		$this->display();
+	}
+
+	public function attach(){
+		$this->display();
+	}
+
+
+	public function mail() {
+		$this->display();
+	}
+
+ 	public function dosite() {
+		if(C('TOKEN_ON') && !$this->dao->autoCheckToken($_POST))$this->error (L('_TOKEN_ERROR_'));
+
+		if(APP_LANG && (isset($_POST['site_name']) || isset($_POST['member_emailchecktpl'])))$where = ' and lang='.LANG_ID;
+		foreach($_POST as $key=>$value){
+			$data['value']=$value;
+			$f = $this->dao->where("varname='".$key."'".$where)->save($data);
+		}
+		$f = savecache(MODULE_NAME);
+		if(isset($_POST['HOME_ISHTML']) && $_POST['HOME_ISHTML']=='')@unlink(__ROOT__.'index.html');
+		if($_POST['DEFAULT_LANG'])routes_cache($_POST['URL_URLRULE']);
+
+		if($f){
+			$this->success(L('do_ok'));
+		}else{
+			$this->error (L('do_error'));
+		}
+	}
+
+	public function testmail(){
+
+		$mailto = $_GET['mail_to'];
+		$message = 'Ainaphp test mail';
+		$r = sendmail($mailto,$this->Config['site_name'],$message,$_POST);
+
+		if($r==true){
+			$this->ajaxReturn($r,L('mailsed_ok'),1);
+		}else{
+			$this->ajaxReturn(0,L('mailsed_error').$r,1);
+		}
+	}
+}
+?>

+ 365 - 0
Ainaphp/Lib/Action/Admin/ContentAction.class.php

@@ -0,0 +1,365 @@
+<?php
+/**
+ *
+ * Content(内容管理模块)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class ContentAction extends AdminbaseAction
+{
+    protected  $dao,$fields;
+    public function _initialize()
+    {
+        parent::_initialize();
+		$module =$this->module[$this->moduleid]['name'];
+		$this->dao = D($module);
+
+		$fields = F($this->moduleid.'_Field');
+		foreach($fields as $key => $res){
+			$res['setup']=string2array($res['setup']);
+			$this->fields[$key]=$res;
+		}
+		unset($fields);
+		unset($res);
+		$this->assign ('fields',$this->fields);
+    }
+
+    /**
+	 * 列表
+	 *
+	 */
+    public function index()
+    {
+		$template =  file_exists(THEME_PATH.MODULE_NAME.'_index.html') ? MODULE_NAME.':index' : 'Content:index';
+	    $this->_list(MODULE_NAME);
+        $this->display ($template);
+    }
+
+	public function add()
+    {
+		$vo['catid']= intval($_GET['catid']);
+		$form=new Form($vo);
+		$form->isadmin=1;
+		$this->assign ( 'form', $form );
+		$template =  file_exists(THEME_PATH.MODULE_NAME.'_edit.html') ? MODULE_NAME.':edit' : 'Content:edit';
+		$this->display ( $template);
+	}
+
+
+	public function edit()
+    {
+
+		$id = $_REQUEST ['id'];
+		if(MODULE_NAME=='Page'){
+					$Page=D('Page');
+					$p = $Page->find($id);
+					if(empty($p)){
+					$data['id']=$id;
+					$data['title'] = $this->categorys[$id]['catname'];
+					$data['keywords'] = $this->categorys[$id]['keywords'];
+					$Page->add($data);
+					}
+		}
+		$vo = $this->dao->getById ( $id );
+		$vo['content'] = htmlspecialchars($vo['content']);
+        $data = M("Article")->where("catid = ".$vo['catid'])->order("id asc")->limit(1)->find();
+        $datas = getimagesize($this->Config['site_url'].'/'.$data['thumb']);
+ 		$form=new Form($vo);
+
+
+		$this->assign ( 'vo', $vo );
+        $this->assign ( 'datas', $datas );
+
+		$this->assign ( 'form', $form );
+		$template =  file_exists(THEME_PATH.MODULE_NAME.'_edit.html') ? MODULE_NAME.':edit' : 'Content:edit';
+		$this->display ( $template);
+	}
+
+    /**
+     * 录入
+     *
+     */
+    public function insert($module='',$fields=array(),$userid=0,$username='',$groupid=0)
+    {
+		$model = $module ?  M($module) : $this->dao;
+		$fields = $fields ? $fields : $this->fields ;
+
+		if($fields['verifyCode']['status'] && (md5($_POST['verifyCode']) != $_SESSION['verify'])){
+			$this->assign ( 'jumpUrl','javascript:history.go(-1);');
+			$this->error(L('error_verify'));
+        }
+
+		$_POST = checkfield($fields,$_POST);
+		if(empty($_POST)) $this->error (L('do_empty'));
+
+		$_POST['createtime'] = time();
+		$_POST['updatetime'] = $_POST['createtime'];
+        $_POST['userid'] = $module ? $userid : $_SESSION['userid'];
+		$_POST['username'] = $module ? $username : $_SESSION['username'];
+		if($_POST['style_color']) $_POST['style_color'] = 'color:'.$_POST['style_color'];
+		if($_POST['style_bold']) $_POST['style_bold'] =  ';font-weight:'.$_POST['style_bold'];
+		if($_POST['style_color'] || $_POST['style_bold'] ) $_POST['title_style'] = $_POST['style_color'].$_POST['style_bold'];
+
+		$module = $module? $module : MODULE_NAME ;
+		if(GROUP_NAME=='User')$_POST['status'] = $this->Role[$groupid]['allowpostverify'] ? 1 : 0;
+
+		if (false === $model->create ()) {
+			$this->error ( $model->getError () );
+		}
+		$_POST['id'] = $id= $model->add();
+
+		if ($id !==false) {
+			$catid = $module =='Page' ? $id : $_POST['catid'];
+
+
+
+			if($_POST['aid']) {
+				$Attachment =M('Attachment');
+				$aids =  implode(',',$_POST['aid']);
+				$data['id']=$id;
+				$data['catid']= $catid;
+				$data['status']= '1';
+				$Attachment->where("aid in (".$aids.")")->save($data);
+			}
+
+			$tablename=C('DB_PREFIX').strtolower($module);
+			$db=D('');
+			$db =   DB::getInstance();
+			$tables = $db->getTables();
+			$Fields=$db->getFields($tablename);
+
+			if(isset($Fields['url'])){
+				$data='';
+				$cat = $this->categorys[$catid];
+				$url = geturl($cat,$_POST,$this->Urlrule);
+				$data['id']= $id;
+				$data['url']= $url[0];
+				$model->save($data);
+			}
+
+
+			if($_POST['keywords'] && $module !='Page'){
+				$keywordsarr=explode(',',$_POST['keywords']);
+				$i=0;
+				$tagsdata =M('Tags_data');
+				$tagsdata->where("id=".$id)->delete();
+				foreach((array)$keywordsarr as $tagname){
+					if($tagname){
+						$tagidarr=$tagdatas=$where=array();
+						$where['name']=array('eq',$tagname);
+						$where['moduleid']=array('eq',$cat['moduleid']);
+						$tagid=M('Tags')->where($where)->field('id')->find();
+						$tagidarr['id']=$id;
+						if($tagid){
+							$num = $tagsdata->where("tagid=".$tagid[id])->count();
+							$tagdatas['num']=$num+1;
+							M('Tags')->where("id=".$tagid[id])->save($tagdatas);
+							$tagidarr['tagid']=$tagid['id'];
+						}else{
+							$tagdatas['moduleid']=$cat['moduleid'];
+							$tagdatas['name'] = $tagname;
+							$tagdatas['slug'] = Pinyin($tagname);
+							$tagdatas['num']=1;
+							$tagdatas['lang']=$_POST['lang'];
+							$tagdatas['module']= $cat['module'];
+							$tagidarr['tagid']=M('Tags')->add($tagdatas);
+						}
+						$i++;
+						$tagsdata->add($tagidarr);
+					}
+				}
+			}
+
+			if($cat['presentpoint']){
+				$user =M('User');
+				if($cat['presentpoint']>0) $user->where("id=".$_POST['userid'])->setInc('point',$cat['presentpoint']);
+				if($cat['presentpoint']<0) $user->where("id=".$_POST['userid'])->setDec('point',$cat['presentpoint']);
+			}
+
+			if($cat['ishtml'] && $_POST['status']){
+				if($module!='Page'   && $_POST['status'])	$this->create_show($id,$module);
+				$arrparentid = array_filter(explode(',',$cat['arrparentid'].','.$cat['id']));
+				foreach($arrparentid as $catid) {
+					if($this->categorys[$catid]['ishtml'])	$this->clisthtml($catid);
+				}
+ 			}
+			if($this->sysConfig['HOME_ISHTML']) $this->create_index();
+			if(GROUP_NAME=='Admin'){
+				$this->assign ( 'jumpUrl', U($module.'/index') );
+			}elseif(GROUP_NAME=='User'){
+				$this->assign ( 'jumpUrl',$_SERVER['HTTP_REFERER']);
+				//$this->assign ( 'jumpUrl', U(GROUP_NAME.'-'.MODULE_NAME.'/add?moduleid='.$cat['moduleid']) );
+			}
+			$this->success (L('add_ok'));
+		} else {
+			$this->error (L('add_error').': '.$model->getDbError());
+		}
+
+    }
+
+	function update($module='',$fields=array(),$userid=0,$username='')
+	{
+		$model = $module ?  M($module) : $this->dao;
+		$fields = $fields ? $fields : $this->fields ;
+		if($fields['verifyCode']['status'] && (md5($_POST['verifyCode']) != $_SESSION['verify'])){
+			$this->assign ( 'jumpUrl','javascript:history.go(-1);');
+			$this->error(L('error_verify'));
+        }
+
+		$_POST = checkfield($fields,$_POST);
+		if(empty($_POST)) $this->error (L('do_empty'));
+
+		$_POST['updatetime'] = time();
+		if($_POST['style_color']) $_POST['style_color'] = 'color:'.$_POST['style_color'];
+		if($_POST['style_bold']) $_POST['style_bold'] =  ';font-weight:'.$_POST['style_bold'];
+		if($_POST['style_color'] || $_POST['style_bold'] ) $_POST['title_style'] = $_POST['style_color'].$_POST['style_bold'];
+
+		$cat = $this->categorys[$_POST['catid']];
+		$module = $module? $module : MODULE_NAME ;
+		$_POST['url'] = geturl($cat,$_POST,$this->Urlrule);
+		$_POST['url'] =$_POST['url'][0];
+
+		$olddata = $model->find($_POST['id']);
+		if (false === $model->create ()) {
+			$this->error ( $model->getError () );
+		}
+
+
+		// 更新数据
+		$list=$model->save ();
+
+		if (false !== $list) {
+			$id= $_POST['id'];
+			$catid = $module =='Page' ? $id : $_POST['catid'];
+
+			if($olddata['keywords']!=$_POST['keywords']  && $module !='Page'){
+
+
+				$tagidarr=$tagdatas=$where=array();
+				$where['name']=array('in',$olddata['keywords']);
+				$where['moduleid']=array('eq',$cat['moduleid']);
+				$where['lang']=array('eq',$_POST['lang']);
+				M('Tags')->where($where)->setDec('num');
+
+				$tagsdata =M('Tags_data');
+				$tagsdata->where("id=".$id)->delete();
+
+				$keywordsarr=explode(',',$_POST['keywords']);
+				foreach((array)$keywordsarr as $tagname){
+					if($tagname){
+						$tagidarr=$tagdatas=$where=array();
+						$where['name']=array('eq',$tagname);
+						$where['moduleid']=array('eq',$cat['moduleid']);
+						$where['lang']=array('eq',$_POST['lang']);
+						$tagid=M('Tags')->where($where)->field('id')->find();
+						$tagidarr['id']=$id;
+						if($tagid['id']>0){
+							M('Tags')->where("id=".$tagid[id])->setInc('num'); ;
+							$tagidarr['tagid']=$tagid['id'];
+						}else{
+							$tagdatas['moduleid']=$cat['moduleid'];
+							$tagdatas['name'] = $tagname;
+							$tagdatas['slug'] = Pinyin($tagname);
+							$tagdatas['num']=1;
+							$tagdatas['lang']=$_POST['lang'];
+							$tagdatas['module']= $cat['module'];
+							$tagidarr['tagid']=M('Tags')->add($tagdatas);
+						}
+						$tagsdata->add($tagidarr);
+					}
+				}
+				M('Tags')->where('num<=0')->delete();
+			}
+
+			if($_POST['aid']) {
+				$Attachment =M('Attachment');
+				$aids =  implode(',',$_POST['aid']);
+				$data['id']= $id;
+				$data['catid']= $catid;
+				$data['status']= '1';
+				$Attachment->where("aid in (".$aids.")")->save($data);
+			}
+			$cat = $this->categorys[$catid];
+			if($cat['ishtml']){
+				if($module!='Page'  && $_POST['status'])	$this->create_show($_POST['id'],$module);
+				$arrparentid = array_filter(explode(',',$cat['arrparentid'].','.$cat['id']));
+				foreach($arrparentid as $catid) {
+					if($this->categorys[$catid]['ishtml'])	$this->clisthtml($catid);
+				}
+ 			}
+			if($this->sysConfig['HOME_ISHTML']) $this->create_index();
+			$this->assign ( 'jumpUrl', $_POST['forward'] );
+			$this->success (L('edit_ok'));
+		} else {
+			//错误提示
+			$this->success (L('edit_error').': '.$model->getDbError());
+		}
+	}
+
+
+	function statusallok(){
+
+		$module = MODULE_NAME;
+		$model = M ( $module );
+		$ids=$_POST['ids'];
+		if(!empty($ids) && is_array($ids)){
+			$id=implode(',',$ids);
+			$data = $model->select($id);
+			if($data){
+				foreach($data as $key=>$r){
+					$model->save(array(id=>$r['id'],status=>1));
+					if($this->categorys[$r['catid']]['ishtml'] && $r['status'])$this->create_show($r['id'],$module);
+				}
+				$cat =  $this->categorys[$r['catid']];
+				if($cat['ishtml']){
+					if($this->sysConfig['HOME_ISHTML']) $this->create_index();
+					$arrparentid = array_filter(explode(',',$cat['arrparentid'].','.$cat['id']));
+					foreach($arrparentid as $catid) {
+						if($this->categorys[$catid]['ishtml'])	$this->clisthtml($catid);
+					}
+				}
+				$this->success(L('do_ok'));
+			}else{
+				$this->error(L('do_error').': '.$model->getDbError());
+			}
+		}else{
+			$this->error(L('do_empty'));
+		}
+	}
+
+	/*状态*/
+
+	public function status(){
+		$module = MODULE_NAME;
+		$model = D ($module);
+		if($model->save($_GET)){
+			$_POST ='';
+			$_POST = $model->find($_GET['id']);
+			$cat =  $this->categorys[$_POST['catid']];
+			if($cat['ishtml']){
+				if($module!='Page'  && $_POST['status'])	$this->create_show($_POST['id'],$module);
+				if($this->sysConfig['HOME_ISHTML']) $this->create_index();
+				$arrparentid = array_filter(explode(',',$cat['arrparentid'].','.$cat['id']));
+				foreach($arrparentid as $catid) {
+					if($this->categorys[$catid]['ishtml'])	$this->clisthtml($catid);
+				}
+ 			}
+
+			$this->success(L('do_ok'));
+		}else{
+			$this->error(L('do_error'));
+		}
+	}
+    //获取图片大小
+    function get_img(){
+        $cid = $_POST['cid'];
+        $model = $_POST['model'];
+        $data = M($model)->where("catid = ".$cid)->order("id asc")->limit(1)->find();
+        $datas = getimagesize($this->Config['site_url'].'/'.$data['thumb']);
+        if(!$datas){$datas = array('','');}
+        echo json_encode($datas);
+        
+    }
+
+
+}?>

+ 573 - 0
Ainaphp/Lib/Action/Admin/CreatehtmlAction.class.php

@@ -0,0 +1,573 @@
+<?php
+/**
+ *
+ * Createhtml(生成静态页)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class CreatehtmlAction extends AdminbaseAction {
+
+    protected  $module;
+    public function _initialize()
+    {
+        parent::_initialize();
+        foreach ((array)$this->module as $rw){
+			if($rw['type']==1  && $rw['status']==1)  $data['module'][$rw['id']] = $rw;
+        }
+		$this->module=$data['module'];
+		$this->assign('module',$this->module);
+		$this->assign('menuid',intval($_GET['menuid']));
+    }
+
+    public function index()
+    {
+		$this->display('Createhtml:index');
+    }
+
+	public function docreateindex()
+	{
+		$this->create_index();
+		$this->assign ( 'jumpUrl', U(MODULE_NAME.'/index') );
+		$this->success(L('index_create_OK'));
+	}
+
+ 	public function createlist()
+    {
+		$moduleid = intval($_GET['moduleid']);
+			if($this->categorys){
+				foreach ($this->categorys as $r){
+					if($r['type']==1 && $r['ishtml']==0) continue;
+					if($moduleid && $r['moduleid'] !=  $moduleid) continue;
+					if(ACTION_NAME=='Updateurl' && $r['module']=='Page') continue;
+					if(ACTION_NAME=='Createlist' && $r['ishtml']!=1) continue;
+					if((ACTION_NAME=='Createshow' && $r['ishtml']!=1) || (ACTION_NAME=='Createshow' && $r['module']=='Page')) continue;
+					$array[] = $r;
+				}
+				import ( '@.ORG.Tree' );
+				$str  = "<option value='\$id'  \$disabled>\$spacer \$catname</option>";
+				$tree = new Tree ($array);
+				$tree->icon = array('&nbsp;&nbsp;&nbsp;'.L('tree_1'),'&nbsp;&nbsp;&nbsp;'.L('tree_2'),'&nbsp;&nbsp;&nbsp;'.L('tree_3'));
+				$select_categorys = $tree->get_tree(0, $str);
+				$this->assign('select_categorys', $select_categorys);
+			}
+
+			$this->display('Createhtml:show');
+
+    }
+
+
+	public function doCreatelist()
+    {
+			$this->assign ( 'waitSecond', 0);
+			extract($_GET,EXTR_SKIP);
+			$moduleid = intval($_GET['moduleid']);
+			$doid = $doid ? intval($doid) : 0;
+			$count = intval($_GET['count']);
+			if($dosubmit!=1){
+				$catids=array();
+				if($_GET['catids'][0]){
+					$catids = $_SESSION['catids'] = $_GET['catids'];
+				}else{
+					foreach($this->categorys as $id=>$cat) {
+						if($cat['type']!=0  || $cat['ishtml']!=1) continue;
+						if($moduleid){
+							if($cat['moduleid']!=$moduleid) continue;
+						}
+						$catids[] = $id;
+					}
+					$catids = $_SESSION['catids'] = $catids;
+				}
+			}else{
+				$catids =$_SESSION['catids'];
+			}
+			if(!isset($catids[$doid])){
+					unset($_SESSION['catids']);
+					$forward = U("Createhtml/createlist");
+					$this->assign ( 'jumpUrl', $forward);
+					$this->success(L('create_update_success'));
+			}else{
+					$id = $catids[$doid];
+					if(empty($count)){
+						$module = $this->categorys[$id]['module'];
+						$dao= M($module);
+						$where['status']=1;
+						if(empty($this->categorys[$id]['listtype'])){
+							if($this->categorys[$id]['child']){
+								$where['catid']=array('in',$this->categorys[$id]['arrchildid']);
+							}else{
+								$where['catid']=$id;
+							}
+							$count = $dao->where($where)->count();
+						}else{
+							$count=1;
+						}
+
+					}
+					if(empty($pages)){
+						$cat_pagesize =  !empty($this->categorys[$id]['pagesize']) ? $this->categorys[$id]['pagesize'] : C('PAGE_LISTROWS');
+						$pages = ceil($count/$cat_pagesize);
+					}
+
+					$p = max(intval($p), 1);
+					$j = 1;
+					do {
+						$this->create_list($id,$p,$count);
+						$j++;
+						$p++;
+						$pages = isset($pages) ? $pages : PAGESTOTAL;
+
+					} while ($p <= $pages && $j < $pagesize);
+
+					if($p <= $pages)  {
+						$endpage = intval($p+$pagesize);
+						$percent = round($p/$pages, 2)*100;
+						$urlarray=array(
+							'count' => $count,
+							'doid' => $doid,
+							'dosubmit' => 1,
+							'pages' => $pages,
+							'p' => $p,
+							'pagesize' => $pagesize,
+							'iscreatehtml'=>1,
+						);
+						$message = L('updating').$this->categorys[$id]['catname'].L('create_update_count').$pages.L('create_update_list_num').$p.L('items_list').$percent.L('items1');
+						$forward = U("Createhtml/".ACTION_NAME,$urlarray);
+					} else {
+						$doid++;
+						$urlarray=array(
+							'doid' => $doid,
+							'dosubmit' => 1,
+							'p' => 1,
+							'pagesize' => $pagesize,
+							'iscreatehtml'=>1,
+						);
+						$message = L('start_updating').$this->categorys[$id]['catname']." ...";
+						$forward = U("Createhtml/".ACTION_NAME,$urlarray);
+					}
+					$this->assign ( 'jumpUrl', $forward);
+					$this->success($message);
+			}
+	}
+
+
+	public function doUpdateurl()
+    {
+		$this->assign ( 'waitSecond', 0);
+		$moduleid = intval($_GET['moduleid']);
+		extract($_GET,EXTR_SKIP);
+		if($moduleid<=0 && $catids[0] <= 0){
+
+			if($this->module && !$_SESSION['moduleids']){
+					foreach($this->module as $moduleid=>$r){
+						$tablename=C('DB_PREFIX').$this->module[$moduleid]['name'];
+						$db=D('');
+						$db =   DB::getInstance();
+						$tables = $db->getTables();
+						$Fields=$db->getFields($tablename);
+						foreach ( $Fields as $key =>$r){
+							if($key=='url') $_SESSION['moduleids'][] = $moduleid;
+						}
+					}
+			}
+			$doid = $doid ? intval($doid) : 0;
+			if(!isset($_SESSION['moduleids'][$doid])){
+					unset($_SESSION['moduleids']);
+					$forward = U("Createhtml/updateurl");
+					$this->assign ( 'jumpUrl', $forward);
+					$this->success(L('create_update_success'));
+			}else{
+					$moduleid = $_SESSION['moduleids'][$doid];
+					$module=$this->module[$moduleid]['name'];
+					$dao = M($module);
+					$p = max(intval($p), 1);
+					$start = $pagesize*($p-1);
+					if(!isset($count)){
+						$count = $dao->where($where)->count();
+					}
+					$pages = ceil($count/$pagesize);
+
+					if($count){
+						$list = $dao->field('id,catid,url')->where($where)->limit($start . ',' . $pagesize)->select();
+						foreach($list as $r) {
+							if($r['islink']) continue;
+							$url = geturl($this->categorys[$r['catid']],$r,$this->Urlrule);
+							unset($r['catid']);
+							$r['url'] = $url['0'];
+							$dao->save($r);
+						}
+					}
+
+					if($pages > $p) {
+							$p++;
+							$creatednum = $start + count($list);
+							$percent = round($creatednum/$count, 2)*100;
+							$urlarray=array(
+								'doid' => $doid,
+								'dosubmit' => 1,
+								'count' => $count,
+								'pages' => $pages,
+								'p' => $p,
+								'pagesize' => $pagesize,
+							);
+
+							$message = L('updating').$this->module[$moduleid]['title'].L('create_update_count').$count.L('create_update_num').$creatednum.L('items').$percent.L('items1');
+							$forward = U("Createhtml/".ACTION_NAME,$urlarray);
+							$this->assign ( 'jumpUrl', $forward);
+							$this->success($message);
+						} else {
+							$doid++;
+							$urlarray=array(
+								'doid' => $doid,
+								'dosubmit' => 1,
+								'p' => 1,
+								'pagesize' => $pagesize,
+							);
+							$message = L('start_updating').$this->module[$moduleid]['title']." ...";
+							$forward = U("Createhtml/".ACTION_NAME,$urlarray);
+							$this->assign ( 'jumpUrl', $forward);
+							$this->success($message);
+						}
+				}
+			}elseif($moduleid){
+				$module=$this->module[$moduleid]['name'];
+				$dao = M($module);
+
+				$p = max(intval($p), 1);
+				$start = $pagesize*($p-1);
+
+				if(is_array($catids) && $catids[0] > 0){
+					$cids = implode(',',$catids);
+					$where = " catid IN($cids) ";
+					$_SESSION['catids'] = $catids;
+				}
+				if(!$catids && $_SESSION['catids'] && $_SESSION['catids'][0] > 0){
+					$catids = implode(',',$_SESSION['catids']);;
+					$where = " catid IN($catids) ";
+				}
+				if(!isset($count)){
+					$count = $dao->where($where)->count();
+				}
+				$pages = ceil($count/$pagesize);
+
+				if($count){
+					$list = $dao->field('id,catid,url')->where($where)->limit($start . ',' . $pagesize)->select();
+					foreach($list as $r) {
+						if($r['islink']) continue;
+						$url = geturl($this->categorys[$r['catid']],$r,$this->Urlrule);
+						unset($r['catid']);
+						$r['url'] = $url['0'];
+						$dao->save($r);
+					}
+				}
+
+				if($pages > $p) {
+					$p++;
+					$creatednum = $start + count($list);
+					$percent = round($creatednum/$count, 2)*100;
+					$urlarray=array(
+						'moduleid' => $moduleid,
+						'dosubmit' => 1,
+						'count' => $count,
+						'pages' => $pages,
+						'p' => $p,
+						'pagesize' => $pagesize,
+					);
+
+					$message = L('create_update_count').$count.L('create_update_num').$creatednum.L('items').$percent.L('items1');
+					$forward = U("Createhtml/updateurl",$urlarray);
+					$this->assign ( 'jumpUrl', $forward);
+					$this->success($message);
+				} else {
+					unset($_SESSION['catids']);
+					$forward = U("Createhtml/updateurl");
+					$this->assign ( 'jumpUrl', $forward);
+					$this->success(L('create_update_success'));
+				}
+			}else{
+				//按照栏目更新url
+				extract($_GET,EXTR_SKIP);
+				$doid = $doid ? intval($doid) : 0;
+				if(empty($_SESSION['catids']) && $catids){
+					if($catids[0] == 0) {
+							foreach($this->categorys as $id=>$cat) {
+								if($cat['child'] || $cat['type']!=0 || $cat['module']=='Page') continue;
+								$catids[] = $id;
+							}
+					}
+					$_SESSION['catids'] = $catids;
+				}else{
+					$catids =$_SESSION['catids'];
+				}
+				if(!isset($catids[$doid])){
+					unset($_SESSION['catids']);
+					$forward = U("Createhtml/updateurl");
+					$this->assign ( 'jumpUrl', $forward);
+					$this->success(L('create_update_success'));
+				}elseif($catids[$doid]<=0){
+					$forward = U("Createhtml/updateurl");
+					$this->assign ( 'jumpUrl', $forward);
+					$this->success(L('create_update_success'));
+
+				}else{
+					$id = $catids[$doid];
+					$module=$this->categorys[$id]['module'];
+					$dao = M($module);
+					$where = "catid=$id";
+					$p = max(intval($p), 1);
+					$start = $pagesize*($p-1);
+					if(!isset($count)){
+						$count = $dao->where($where)->count();
+					}
+					$pages = ceil($count/$pagesize);
+
+					if($count){
+						$list = $dao->field('id,catid,url')->where($where)->limit($start . ',' . $pagesize)->select();
+						foreach($list as $r) {
+							if($r['islink']) continue;
+							$url = geturl($this->categorys[$r['catid']],$r,$this->Urlrule);
+							unset($r['catid']);
+							$r['url'] = $url['0'];
+							$dao->save($r);
+						}
+					}
+
+					if($pages > $p) {
+						$p++;
+						$creatednum = $start + count($list);
+						$percent = round($creatednum/$count, 2)*100;
+						$urlarray=array(
+							'doid' => $doid,
+							'dosubmit' => 1,
+							'count' => $count,
+							'pages' => $pages,
+							'p' => $p,
+							'pagesize' => $pagesize,
+						);
+
+						$message = L('updating').$this->categorys[$id]['catname'].L('create_update_count').$count.L('create_update_num').$creatednum.L('items').$percent.L('items1');
+						$forward = U("Createhtml/".ACTION_NAME,$urlarray);
+						$this->assign ( 'jumpUrl', $forward);
+						$this->success($message);
+					} else {
+						$doid++;
+						$urlarray=array(
+							'doid' => $doid,
+							'dosubmit' => 1,
+							'p' => 1,
+							'pagesize' => $pagesize,
+						);
+						$message = L('start_updating').$this->categorys[$id]['catname']." ...";
+						$forward = U("Createhtml/".ACTION_NAME,$urlarray);
+						$this->assign ( 'jumpUrl', $forward);
+						$this->success($message);
+					}
+				}
+			}
+	}
+
+	public function updateurl()
+    {
+			$moduleid = intval($_GET['moduleid']);
+			$this->assign('moduleid',$moduleid);
+			if($this->categorys){
+				foreach ($this->categorys as $r){
+					if($r['type']==1 && $r['ishtml']==0) continue;
+					if($_GET['moduleid'] && $r['moduleid'] !=  $_GET['moduleid']) continue;
+					if(ACTION_NAME=='Updateurl' && $r['module']=='Page') continue;
+					if(ACTION_NAME=='Createlist' && $r['ishtml']!=1) continue;
+					if((ACTION_NAME=='Createshow' && $r['ishtml']!=1) || (ACTION_NAME=='Createshow' && $r['module']=='Page')) continue;
+					if($r['child'] && ACTION_NAME!='Createlist'){
+						$r['disabled'] = 'disabled';
+					}else{
+						$r['disabled'] = '';
+					}
+					$array[] = $r;
+				}
+				import ( '@.ORG.Tree' );
+				$str  = "<option value='\$id'  \$disabled>\$spacer \$catname</option>";
+				$tree = new Tree ($array);
+				$tree->icon = array('&nbsp;&nbsp;&nbsp;'.L('tree_1'),'&nbsp;&nbsp;&nbsp;'.L('tree_2'),'&nbsp;&nbsp;&nbsp;'.L('tree_3'));
+				$select_categorys = $tree->get_tree(0, $str);
+				$this->assign('select_categorys', $select_categorys);
+			}
+			$this->display('Createhtml:show');
+
+    }
+
+	public function createshow()
+    {
+		$moduleid = intval($_GET['moduleid']);
+			if($this->categorys){
+				foreach ($this->categorys as $r){
+					if($r['type']==1 && $r['ishtml']==0) continue;
+					if($moduleid && $r['moduleid'] !=  $moduleid) continue;
+					if(ACTION_NAME=='Updateurl' && $r['module']=='Page') continue;
+					if(ACTION_NAME=='Createlist' && $r['ishtml']!=1) continue;
+					if((ACTION_NAME=='Createshow' && $r['ishtml']!=1) || (ACTION_NAME=='Createshow' && $r['module']=='Page')) continue;
+					if($r['child'] && ACTION_NAME!='Createlist'){
+						$r['disabled'] = 'disabled';
+					}else{
+						$r['disabled'] = '';
+					}
+					$array[] = $r;
+				}
+				import ( '@.ORG.Tree' );
+				$str  = "<option value='\$id'  \$disabled>\$spacer \$catname</option>";
+				$tree = new Tree ($array);
+				$tree->icon = array('&nbsp;&nbsp;&nbsp;'.L('tree_1'),'&nbsp;&nbsp;&nbsp;'.L('tree_2'),'&nbsp;&nbsp;&nbsp;'.L('tree_3'));
+				$select_categorys = $tree->get_tree(0, $str);
+				$this->assign('select_categorys', $select_categorys);
+			}
+			$this->display('Createhtml:show');
+	}
+
+
+	public function doCreateshow()
+    {
+
+			$this->assign ( 'waitSecond', 0);
+			extract($_GET,EXTR_SKIP);
+			$moduleid = intval($_GET['moduleid']);
+			$doid = $doid ? intval($doid) : 0;
+
+			if($dosubmit!=1){
+					if($catids[0] == 0) {
+						$catids=array();
+						foreach($this->categorys as $id=>$cat) {
+							if($cat['child'] || $cat['type']!=0 || $cat['module']=='Page' || $cat['ishtml']!=1) continue;
+							if($moduleid){
+								if($cat['moduleid']!=$moduleid) continue;
+							}
+							$catids[] = $id;
+						}
+					}
+					$_SESSION['catids'] = $catids;
+			}else{
+					$catids =$_SESSION['catids'];
+			}
+			if(!isset($catids[$doid])){
+					unset($_SESSION['catids']);
+					$forward = U("Createhtml/Createshow");
+					$this->assign ( 'jumpUrl', $forward);
+					$this->success(L('create_update_success'));
+			}else{
+					$id = $catids[$doid];
+					$module=$this->categorys[$id]['module'];
+					$dao = M($module);
+					$where = "catid=$id";
+					$p = max(intval($p), 1);
+					$start = $pagesize*($p-1);
+
+					if(!isset($count)){
+						$count = $dao->where($where)->count();
+					}
+					$pages = ceil($count/$pagesize);
+
+					if($count){
+						$list = $dao->field('id,catid,url')->where($where)->limit($start . ',' . $pagesize)->select();
+						foreach($list as $r) {
+							if($r['islink']) continue;
+							$module = $this->categorys[$r['catid']]['module'];
+							$this->create_show($r['id'],$module);
+						}
+					}
+
+					if($pages > $p) {
+						$p++;
+						$creatednum = $start + count($list);
+						$percent = round($creatednum/$count, 2)*100;
+						$urlarray=array(
+							'doid' => $doid,
+							'dosubmit' => 1,
+							'count' => $count,
+							'pages' => $pages,
+							'p' => $p,
+							'pagesize' => $pagesize,
+							'iscreatehtml'=>1,
+						);
+
+						$message = L('updating').$this->categorys[$id]['catname'].L('create_update_count').$count.L('create_update_num').$creatednum.L('items').$percent.L('items1');
+						$forward = U("Createhtml/".ACTION_NAME,$urlarray);
+						$this->assign ( 'jumpUrl', $forward);
+						$this->success($message);
+					} else {
+						$doid++;
+						$urlarray=array(
+							'doid' => $doid,
+							'dosubmit' => 1,
+							'p' => 1,
+							'pagesize' => $pagesize,
+							'iscreatehtml'=>1,
+						);
+						$message = L('start_updating').$this->categorys[$id]['catname']." ...";
+						$forward = U("Createhtml/".ACTION_NAME,$urlarray);
+						$this->assign ( 'jumpUrl', $forward);
+						$this->success($message);
+					}
+			}
+
+		}
+
+		public function createsitemap()
+		{
+
+			foreach((array)$this->module as $r){
+					if($r['issearch'])$search_module[$r['name']] =  $r;
+			}
+			$this->assign('module',$search_module);
+
+			$xmlmap=file_exists('./sitemap.xml');
+			$htmlmap=file_exists('./sitemap.html');
+			$this->assign('siteurl',$this->Config['site_url']);
+			$this->assign('xmlmap',$xmlmap);
+			$this->assign('htmlmap',$htmlmap);
+			$this->assign('yesorno',array(0 => L('no'),1  => L('yes')));
+			$this->display('Createhtml:sitemap');
+
+		}
+
+		public function docreatesitemap()
+		{
+			if($_GET['htmlmap']){
+				$r = $this->create_index(1);
+			}
+
+			if($_GET['xmlmap']){
+				import("@.ORG.Cxml");
+				$array=array();
+
+
+				$array[0]['NodeName']['value'] ='url';
+				$array[0]['loc']['value']=$this->Config['site_url'];
+				$array[0]['lastmod']['value']= date('Y-m-d',time());
+				$array[0]['changefreq']['value'] ='weekly';
+				$array[0]['priority']['value'] =1;
+
+				foreach((array)$this->module as $r){
+					if($r['issearch']){
+						$num = intval($_GET[$r['name']]);
+						if(!$num) continue;
+						$data = M($r['name'])->field('id,title,url,createtime')->where("status=1")->order('id desc')->limit('0,'.$num)->select();
+						foreach($data as $key=> $res){
+							$arraya[$key]['NodeName']['value'] ='url';
+							$arraya[$key]['loc']['value'] = $this->Config['site_url'].$res['url'];
+							$arraya[$key]['lastmod']['value'] = date('Y-m-d',$res['createtime']);
+							$arraya[$key]['changefreq']['value'] ='weekly';
+							$arraya[$key]['priority']['value'] =0.7;
+						}
+						$array =array_merge($array,$arraya);
+					}
+				}
+
+				$Cxml = new Cxml();
+				$Cxml->root='urlset';
+				$Cxml->root_attributes=array('xmlns'=>'http://www.sitemaps.org/schemas/sitemap/0.9');
+				$xmldata = $Cxml->Cxml($array,'./sitemap.xml');
+				$d=file_exists('./sitemap.xml');;
+			}
+			if(($_GET['htmlmap'] && $r) || ($_GET['xmlmap']&& $d)){$this->success(L('DO_OK'));}else{$this->error(L('Create error.'));}
+
+		}
+
+}
+?>

+ 253 - 0
Ainaphp/Lib/Action/Admin/DatabaseAction.class.php

@@ -0,0 +1,253 @@
+<?php
+/**
+ *
+ * Database(数据库)
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+
+class DatabaseAction extends AdminbaseAction{
+
+    protected $db = '', $datadir = '' , $startrow=0,$startfrom=0, $complete=true;
+    function _initialize()
+    {
+		parent::_initialize();
+		$this->datadir = RUNTIME_PATH.'Backup/';
+		if(!is_dir($this->datadir))mkdir($this->datadir,0755,true);
+		$db=D('');
+		$this->db =   DB::getInstance();
+    }
+
+    public function index()
+    {
+        $dataList = $this->db->query("SHOW TABLE STATUS LIKE '".C('DB_PREFIX')."%'");
+        foreach ($dataList as $row){
+            $total += $row['Data_length'];
+        }
+        $this->assign('totalSize', $total);
+        $this->assign("dataList", $dataList);
+        $this->display();
+    }
+
+    public function excuteQuery($sql='')
+    {
+        if(empty($sql)) {$this->error(L('do_empty'));}
+        $queryType = 'INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|LOAD DATA|SELECT .* INTO|COPY|ALTER|GRANT|TRUNCATE|REVOKE|LOCK|UNLOCK';
+        if (preg_match('/^\s*"?(' . $queryType . ')\s+/i', $sql)) {
+            $data['result'] = $this->db->execute($sql);
+            $data['type'] = 'execute';
+        }else {
+
+            $data['result'] = $this->db->query($sql);
+            $data['type'] = 'query';
+
+        }
+        return $data;
+    }
+
+    public function query(){
+        $this->display();
+    }
+
+    public function doquery(){
+		$sqls=explode("\n",stripcslashes($_POST['sql']));
+		foreach ((array)$sqls as $sql){
+			if($sql)$r =$this->excuteQuery($sql);
+		}
+		if($r['result']!=''){
+			$this->success(L('do_ok'));
+		}else{
+			if($r['dberror']) $this->error(L($r['dberror']));
+		}
+    }
+
+	public function recover(){
+		if($_GET['do']=='delete'){
+
+			foreach ((array)$_POST['files'] as $r){
+				unlink($r);
+			}
+			$this->success(L('do_ok'));
+		}elseif($_GET['do']=='import'){
+			header('Content-Type: text/html; charset=UTF-8');
+			$filename = $_GET['filename'];
+			$filelist = dir_list($this->datadir);
+			foreach ((array)$filelist as $r){
+				$file = explode('-',basename($r));
+				if($file[0] ==$filename){
+					$files[]  = $r;
+				}
+			}
+			foreach((array)$files as $file){
+				//读取数据文件
+				$sqldata = file_get_contents($file);
+				$sqlFormat = sql_split($sqldata, C('DB_PREFIX'));
+				foreach ((array)$sqlFormat as $sql){
+						$sql = trim($sql);
+						if (strstr($sql, 'CREATE TABLE')){
+							preg_match('/CREATE TABLE `([^ ]*)`/', $sql, $matches);
+							$ret =$this->excuteQuery($sql);
+							//if($ret){echo   L('CREATE_TABLE_OK').$matches[0].' <br />';}else{echo 'Error sql:'.$sql;}exit;
+						}else{
+							$ret = $this->excuteQuery($sql);
+						}
+				}
+				echo L('CREATE_TABLE_OK').basename($file).'<br>';
+			}
+
+		}else{
+			$filelist = dir_list($this->datadir);
+			foreach ((array)$filelist as $r){
+				$filename = explode('-',basename($r));
+				$files[] = array('path'=> $r,'file'=>basename($r),'name' => $filename[0], 'size' => filesize($r), 'time' => filemtime($r));
+			}
+			$this->assign('files',$files);
+			$this->display();
+		}
+	}
+
+	public function docommand()
+    {
+        $tables = $_POST['tables'];
+        $do= trim($_GET['do']);
+		if(empty($do) || empty($tables)) $this->error(L('do_empty'));
+		if($do=='show'){
+			 foreach ((array)$tables as $t){
+				$this->db->execute("SHOW COLUMNS FROM {$t}");
+			}
+		}else{
+			$tables = implode(',',$tables);
+			$r=$this->db->execute($do.' TABLE '.$tables);
+			if(false != $r){ $this->success(L('do_ok'));}else{ $this->error($r['dbError']);}
+		}
+    }
+
+	public function backup(){
+		$tableid = intval($_GET['tableid']);
+		$this->startfrom = intval($_GET['startfrom']);
+		$sizelimit = intval($_REQUEST['sizelimit']);
+		$volume = intval($_GET['volume']) + 1;
+
+		$dataList = $this->db->query("SHOW TABLE STATUS LIKE '".C('DB_PREFIX')."%'");
+		foreach ($dataList as $row){
+				$table_info[$row['Name']]=$row;
+		}
+		$tables = S('backuptables');
+		if(empty( $_POST['tables']) && empty($tables)) {
+			foreach ($dataList as $row){
+				$tables[]= $row['Name'];
+			}
+		}else{
+			$tables = array();
+			if(!$tableid) {
+				$tables=$_POST['tables'];
+				S('backuptables',$tables);
+			} else {
+				$tables = S('backuptables');
+			}
+			if( !is_array($tables) || empty($tables)) {
+				$this->success(L('do_empty'));
+			}
+		}
+		unset($dataList);
+		$sql='';
+		if(!$tableid) {
+				$sql .= "-- Ainatec SQL Backup\n-- Time:".toDate(time())."\n-- http://www.ainatec.com \n\n";
+				foreach($tables as $key=>$table) {
+					$sql .= "--\n-- Ainaphp Table `$table`\n-- \n";
+					$sql .= "DROP TABLE IF EXISTS `$table`;\n";
+					$info = $this->db->query("SHOW CREATE TABLE  $table");
+					$sql .= str_replace(array('USING BTREE','ROW_FORMAT=DYNAMIC'),'',$info[0]['Create Table']).";\n";
+				}
+		}
+
+		for(; $this->complete && $tableid < count($tables) && strlen($sql) + 500 < $sizelimit * 1000; $tableid++) {
+			if($table_info[$tables[$tableid]]['Rows']>0){
+				$sql .=  $this->dumptablesql($tables[$tableid], $this->startfrom, strlen($sql),$table_info[$tables[$tableid]]['Auto_increment']);
+				if($this->complete) {
+					$this->startfrom = 0;
+				}
+
+			}
+		}
+		!$this->complete && $tableid--;
+		$filename = htmlspecialchars(strip_tags($_GET['filename']));
+		$filename = !$filename ? 'Yp_'.rand_string(10).'_'.date('YmdH') : $filename;
+		$filename_valume = sprintf($filename."-%s".'.sql', $volume);
+
+		if(trim($sql)){
+			$putfile=$this->datadir . $filename_valume;
+			$r= file_put_contents($putfile , trim($sql));
+		}
+
+
+		if($tableid < count($tables) || $r){
+
+			$this->assign ( 'waitSecond', 0);
+			$urlarray=array(
+						'tableid'   => $tableid,
+						'startfrom' => $this->startfrom,
+						'sizelimit' => $sizelimit,
+						'volume'	=> $volume,
+						'filename'  => $filename,
+					);
+			$message = $filename_valume.' File Create Ok!';
+			$forward = U("Database/backup",$urlarray);
+			$this->assign ( 'jumpUrl', $forward);
+			$this->success($message);
+
+		}else{
+			S('backuptables',null);
+			$this->assign ( 'jumpUrl', U(MODULE_NAME.'/recover') );
+			$this->success(L('do_ok'));
+		}
+
+	}
+
+	public function dumptablesql($table, $startfrom = 0, $currsize = 0,$auto_increment=0) {
+		$offset = 300;
+		$insertsql = '';
+		$sizelimit = intval($_REQUEST['sizelimit']);
+		if(C('DB_PREFIX').'online'==$tbale)return '';
+
+		$modelname=str_replace(C('DB_PREFIX'),'',$table);
+		$model = M($modelname);
+		$keyfield=$model->getPk ();
+		$rows = $offset;
+		while($currsize + strlen($insertsql) + 500 < $sizelimit * 1000 && $rows == $offset) {
+				if($auto_increment) {
+					$selectsql = "SELECT * FROM $table WHERE $keyfield > $startfrom ORDER BY $keyfield LIMIT $offset";
+				} else {
+					$selectsql = "SELECT * FROM $table LIMIT $startfrom, $offset";
+				}
+				$tabledumped = 1;
+				$row = $this->db->query($selectsql);
+				$rows = count($row);
+				foreach($row as $key=>$val) {
+					foreach ($val as $k=>$field){
+						if(is_string($field)) {
+							$val[$k] = '\''. $this->db->escapeString($field).'\'';
+						}elseif(empty($field)){
+							$val[$k] = 'NULL';
+						}
+					}
+					if($currsize + strlen($insertsql) + 500 < $sizelimit * 1000) {
+						if($auto_increment) {
+							$startfrom = $row[$key][$keyfield];
+						} else {
+							$startfrom++;
+						}
+						$insertsql .= "INSERT INTO `$table` VALUES (".implode(',', $val).");\n";
+					} else {
+						$this->complete=false;
+						break 2;
+					}
+				}
+
+		}
+		$this->startfrom= $startfrom;
+		return $insertsql;
+	}
+
+}
+
+?>

+ 18 - 0
Ainaphp/Lib/Action/Admin/DbsourceAction.class.php

@@ -0,0 +1,18 @@
+<?php
+/**
+ *
+ * Posid (推荐位管理)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class DbsourceAction extends AdminbaseAction {
+
+	protected $dao;
+    function _initialize()
+    {
+		parent::_initialize();
+    }
+
+
+}
+?>

+ 15 - 0
Ainaphp/Lib/Action/Admin/EmptyAction.class.php

@@ -0,0 +1,15 @@
+<?php
+/**
+ *
+ * Empty (空模块)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class EmptyAction extends Action
+{
+	public function _empty()
+	{
+		R('Admin/Content/'.ACTION_NAME);
+	}
+}
+?>

+ 271 - 0
Ainaphp/Lib/Action/Admin/FieldAction.class.php

@@ -0,0 +1,271 @@
+<?php
+/**
+ *
+ * Module(模型管理)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class FieldAction extends AdminbaseAction {
+
+	protected $dao,$moduleid;
+    function _initialize()
+    {
+		parent::_initialize();
+		$this->moduleid = $moduleid=intval($_REQUEST ['moduleid']);
+		$this->assign('moduleid', $moduleid);
+		$this->dao=D('Admin/field');
+		$field_pattern = array(
+			'0'=> L(please_chose),
+			'email' => L(pattern_email),
+			'url' => L(pattern_url),
+			'date' => L(pattern_date),
+			'number'=> L(pattern_number),
+			'digits'=>  L(pattern_digits),
+			'creditcard'=> L(pattern_creditcard),
+			'equalTo'=> L(pattern_equalTo),
+			'ip4'=>  L(pattern_ip4),
+			'mobile'=> L(pattern_mobile),
+			'zipcode'=> L(pattern_zipcode),
+			'qq'=> L(pattern_qq),
+			'idcard'=> L(pattern_idcard),
+			'chinese'=> L(pattern_chinese),
+			'cn_username'=> L(pattern_cn_username),
+			'tel'=> L(pattern_tel),
+			'english'=> L(pattern_english),
+			'en_num'=> L(pattern_en_num),
+		);
+		$this->assign('field_pattern', $field_pattern);
+		$this->assign ( 'options', array(1=>L('yes'),0=>L('no')));
+		$role =F('Role');
+		foreach((array)$role as $key=>$c){
+		$usergroup[$key]=$c['name'];
+		}
+		$this->assign ( 'usergroup', $usergroup);
+    }
+
+	public function index(){
+		$this->assign('sysfield',array('catid','userid','username','title','thumb','keywords','description','posid','status','createtime','url'));
+		$this->assign('nodostatus',array('catid','title','status','createtime'));
+		$list = $this->dao->where("moduleid=".$this->moduleid)->order('listorder ASC')->select();
+		$this->assign('list', $list);
+		$this->display();
+	}
+
+
+	public function _before_add(){
+		if(empty($this->moduleid))$this->error(L('do_empty'));
+		if($_GET['isajax']){
+			$this->assign($_GET);
+			$this->assign($_POST);
+			$this->display('type');
+			exit;
+		}
+	}
+
+	function delete() {
+		$id=intval($_GET['id']);
+		$r = $this->dao->find($id);
+		if(empty($r)) $this->error  (L('do_empty'));
+		$this->dao->delete($id);
+		$moduleid = $r['moduleid'];
+		$field = $r['field'];
+		$tablename=C('DB_PREFIX').$this->module[$moduleid]['name'];;
+		$this->dao->execute("ALTER TABLE `$tablename` DROP `$field`");
+		savecache(MODULE_NAME,$moduleid);
+		$this->success (L('delete_ok'));
+	}
+
+ 	public function status(){
+		$id =intval($_GET['id']);
+		if($this->dao->save($_GET)){
+			$r = $this->dao->find($id);
+			savecache(MODULE_NAME,$r['moduleid']);
+			$this->success(L('do_ok'));
+		}else{
+			$this->error(L('do_error'));
+		}
+	}
+
+	function insert() {
+		if($_GET['isajax']){//检测字段是否已经存在
+			$name=$_GET['field'];
+			$moduleid=intval($_GET['moduleid']);
+			$tablename=C('DB_PREFIX').$this->module[$moduleid]['name'];
+			$db=D('');
+			$db =   DB::getInstance();
+			$tables = $db->getTables();
+			$Fields=$db->getFields($tablename);
+			foreach ( $Fields as $key =>$r){
+				if($key==$name) $ishave=1;
+			}
+			if($ishave) { echo 'false';}else{echo 'true';}
+			exit;
+		}
+		$addfieldsql =$this->get_tablesql($_POST,'add');
+		if($_POST['setup']) $_POST['setup']=array2string($_POST['setup']);
+		$_POST['unpostgroup'] = $_POST['unpostgroup'] ?  implode(',',$_POST['unpostgroup']) : '';
+		$_POST['status'] =1;
+		$name = MODULE_NAME;
+		$model = D ($name);
+		if (false === $model->create ()) {
+			$this->error ( $model->getError () );
+		}
+		if ($model->add() !==false) {
+			savecache(MODULE_NAME,$_POST['moduleid']);
+
+			if(is_array($addfieldsql)){
+				foreach($addfieldsql as $sql){
+				$model->execute($sql);
+				}
+			}else{
+				if($addfieldsql)$model->execute($addfieldsql);
+			}
+			$this->assign ( 'jumpUrl', U(MODULE_NAME.'/index',array('moduleid' => $this->moduleid))) ;
+			$this->success (L('add_ok'));
+		} else {
+			$this->error (L('add_error').': '.$model->getDbError());
+		}
+	}
+
+	function update() {
+		$editfieldsql =$this->get_tablesql($_POST,'edit');
+		if($_POST['setup']) $_POST['setup']=array2string($_POST['setup']);
+		$_POST['unpostgroup'] = $_POST['unpostgroup'] ?  implode(',',$_POST['unpostgroup']) : '';
+		$name = MODULE_NAME;
+		$model = D ( $name );
+		if (false === $model->create ()) {
+			$this->error ( $model->getError () );
+		}
+		if (false !== $model->save ()) {
+			savecache(MODULE_NAME,$_POST['moduleid']);
+			if(is_array($editfieldsql)){
+				foreach($editfieldsql as $sql){
+				$model->execute($sql);
+				}
+			}else{
+				$r=$model->execute($editfieldsql);
+			}
+			$this->success (L('edit_ok'));
+		} else {
+			$this->success (L('edit_error').': '.$model->getDbError());
+		}
+	}
+
+	public function _before_edit(){
+		if(empty($this->moduleid))$this->error(L('do_empty'));
+	}
+
+
+	public function get_tablesql($info,$do){
+
+		$fieldtype = $info['type'];
+		if($info['setup']['fieldtype']){
+			$fieldtype=$info['setup']['fieldtype'];
+		}
+		$moduleid = $info['moduleid'];
+		$default=$info['setup']['default'];
+		$field = $info['field'];
+		$tablename=C('DB_PREFIX').strtolower($this->module[$moduleid]['name']);
+		$maxlength = intval($info['maxlength']);
+		$minlength = intval($info['minlength']);
+		$numbertype = $info['setup']['numbertype'];
+		$oldfield = $info['oldfield'];
+		if($do=='add'){ $do = ' ADD ';}else{$do =  " CHANGE `$oldfield` ";}
+
+
+		switch($fieldtype) {
+			case 'varchar':
+				if(!$maxlength) $maxlength = 255;
+				$maxlength = min($maxlength, 255);
+				$sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( $maxlength ) NOT NULL DEFAULT '$default'";
+			break;
+
+			case 'title':
+				if(!$maxlength) $maxlength = 255;
+				$maxlength = min($maxlength, 255);
+				$sql[] = "ALTER TABLE `$tablename` $do `title` VARCHAR( $maxlength ) NOT NULL DEFAULT '$default'";
+				$sql[] = "ALTER TABLE `$tablename` $do `title_style` VARCHAR( 40 ) NOT NULL DEFAULT ''";
+				$sql[] = "ALTER TABLE `$tablename` $do `thumb` VARCHAR( 100 ) NOT NULL DEFAULT ''";
+			break;
+
+			case 'catid':
+				$sql = "ALTER TABLE `$tablename` $do `$field` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0'";
+			break;
+
+			case 'number':
+				$decimaldigits = $info['setup']['decimaldigits'];
+				$default = $decimaldigits == 0 ? intval($default) : floatval($default);
+				$sql = "ALTER TABLE `$tablename` $do `$field` ".($decimaldigits == 0 ? 'INT' : 'decimal( 10,'.$decimaldigits.' )')." ".($numbertype ==1 ? 'UNSIGNED' : '')."  NOT NULL DEFAULT '$default'";
+			break;
+
+			case 'tinyint':
+				if(!$maxlength) $maxlength = 3;
+				$maxlength = min($maxlength,3);
+				$default = intval($default);
+				$sql = "ALTER TABLE `$tablename` $do `$field` TINYINT( $maxlength ) ".($numbertype ==1 ? 'UNSIGNED' : '')." NOT NULL DEFAULT '$default'";
+			break;
+
+
+			case 'smallint':
+				$default = intval($default);
+				if(!$maxlength) $maxlength = 8;
+				$maxlength = min($maxlength,8);
+				$sql = "ALTER TABLE `$tablename` $do `$field` SMALLINT( $maxlength ) ".($numbertype ==1 ? 'UNSIGNED' : '')." NOT NULL DEFAULT '$default'";
+			break;
+
+			case 'int':
+				$default = intval($default);
+				$sql = "ALTER TABLE `$tablename` $do `$field` INT ".($numbertype ==1 ? 'UNSIGNED' : '')." NOT NULL DEFAULT '$default'";
+			break;
+
+			case 'mediumint':
+				$default = intval($default);
+				$sql = "ALTER TABLE `$tablename` $do `$field` INT ".($numbertype ==1 ? 'UNSIGNED' : '')." NOT NULL DEFAULT '$default'";
+			break;
+
+			case 'mediumtext':
+				$sql = "ALTER TABLE `$tablename` $do `$field` MEDIUMTEXT NOT NULL";
+			break;
+
+			case 'text':
+				$sql = "ALTER TABLE `$tablename` $do `$field` TEXT NOT NULL";
+			break;
+
+			case 'posid':
+				$sql = "ALTER TABLE `$tablename` $do `$field` TINYINT(2) UNSIGNED NOT NULL DEFAULT '0'";
+			break;
+
+			//case 'typeid':
+				//$sql = "ALTER TABLE `$tablename` $do `$field` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0'";
+			//break;
+
+			case 'datetime':
+				$sql = "ALTER TABLE `$tablename` $do `$field` INT(11) UNSIGNED NOT NULL DEFAULT '0'";
+			break;
+
+			case 'editor':
+				$sql = "ALTER TABLE `$tablename` $do `$field` TEXT NOT NULL";
+			break;
+
+			case 'image':
+				$sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( 80 ) NOT NULL DEFAULT ''";
+			break;
+
+			case 'images':
+				$sql = "ALTER TABLE `$tablename` $do `$field` MEDIUMTEXT NOT NULL";
+			break;
+
+			case 'file':
+				$sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( 80 ) NOT NULL DEFAULT ''";
+			break;
+
+			case 'files':
+				$sql = "ALTER TABLE `$tablename` $do `$field` MEDIUMTEXT NOT NULL";
+			break;
+		}
+		return $sql;
+	}
+
+
+}
+?>

+ 185 - 0
Ainaphp/Lib/Action/Admin/IndexAction.class.php

@@ -0,0 +1,185 @@
+<?php
+
+/**
+ *
+ * IndexAction.class.php(后台首页)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class IndexAction extends AdminbaseAction
+{
+	protected   $cache_model;
+	function _initialize()
+    {
+		parent::_initialize();
+		unset($_POST['status']);
+		unset($_POST['groupid']);
+		unset($_POST['amount']);
+		unset($_POST['point']);
+    }
+
+    public function index()
+    {
+		$role	=	F("Role");
+		$this->assign('usergroup',$role[$_SESSION['groupid']]['name']);
+
+
+		foreach((array)$_SESSION['_ACCESS_LIST']['ADMIN'] as $key=>$r){$modules[]=ucwords(strtolower($key));}
+		$modules=implode("','",$modules);
+		$alltopnode= M('Node')->field('groupid')->where("name in('$modules') and level=2")->group('groupid')->select();
+		foreach((array)$alltopnode as $key=>$r){$GroupAccessids[]=$r['groupid'];}
+
+		foreach($this->menudata as $key=>$module) {
+			if($module['parentid'] != 0 || $module['status']==0) continue;
+			if(in_array($key,$GroupAccessids) || $_SESSION[C('ADMIN_AUTH_KEY')]) {
+				if(empty($module['action'])) $module['action']='index';
+					$nav[$key]  = $module;
+					if($isnav){
+						$array=array('menuid'=> $nav[$key]['parentid']);
+						cookie('menuid',$nav[$key]['parentid']);
+						//$_SESSION['menuid'] = $nav[$key]['parentid'];
+					}else{
+						 $array=array('menuid'=> $nav[$key]['id']);
+					}
+					if(empty($menuid) && empty($isnav)) $array=array();
+					$c=array();
+					parse_str($nav[$key]['data'],$c);
+					$nav[$key]['data'] = $c + $array;
+			}
+		}
+		$this->assign('menuGroupList',$nav);
+		$this->assign($this->Config);
+		foreach($nav as $key=>$r){
+			$menu[$r['id']]  = $this->getnav($r['id']);
+		}
+		$this->assign('menu',$menu);
+		$this->display();
+    }
+
+	public function cache() {
+		dir_delete(RUNTIME_PATH.'Html/');
+		dir_delete(RUNTIME_PATH.'Cache/');
+		if(is_file(RUNTIME_PATH.'~runtime.php'))@unlink(RUNTIME_PATH.'~runtime.php');
+		if(is_file(RUNTIME_PATH.'~allinone.php'))@unlink(RUNTIME_PATH.'~allinone.php');
+		R('Admin/Category/repair');
+		R('Admin/Category/repair');
+
+		foreach($this->cache_model as $r){
+			savecache($r);
+		}
+		$forward = $_GET['forward'] ?   $_GET['forward']  : U('Index/main');
+		$this->assign ( 'jumpUrl', $forward );
+		$this->success(L('do_success'));
+	}
+
+	public function main() {
+
+		$db=D('');
+		$db =   DB::getInstance();
+		$tables = $db->getTables();
+
+		$info = array(
+
+            'SERVER_SOFTWARE'=>PHP_OS.' '.$_SERVER["SERVER_SOFTWARE"],
+            'mysql_get_server_info'=>php_sapi_name(),
+			'MYSQL_VERSION' => mysql_get_server_info(),
+            'upload_max_filesize'=> ini_get('upload_max_filesize'),
+            'max_execution_time'=>ini_get('max_execution_time').L('miao'),
+			'disk_free_space'=>round((@disk_free_space(".")/(1024*1024)),2).'M',
+            );
+		$yourphp_info=array(
+			'ainaphp_VERSION'=> VERSION.' '.UPDATETIME.'',
+			'license'=> '<b></b>',
+			'SN'=> '<b></b>',
+			'update'=>  ' <b></b>',
+
+		);
+		$this->assign('ainaphp_info',$ainaphp_info);
+        $this->assign('server_info',$info);
+		foreach ((array)$this->module as $rw){
+			if($rw['type']==1){
+				$molule= M($rw['name']);
+				$rw['counts'] = $molule->count();;
+				$mdata['moduledata'][] = $rw;
+			}
+        }
+
+		$molule= M('User');
+		$counts = $molule->count();
+		$userinfos = $molule->find($_SESSION['adminid']);
+		$mdata['moduledata'][]=array('title'=>L('user_counts'),'counts'=>$counts);
+
+		$molule= M('Category');$counts = $molule->count();
+		$mdata['moduledata'][]=array('title'=>L('Category_counts'),'counts'=>$counts);
+		$this->assign($mdata);
+		$role =F('Role');
+
+		$userinfo=array(
+			'username'=>$userinfos['username'],
+			'groupname'=>$role[$userinfos['groupid']]['name'],
+			'logintime'=>toDate($userinfos['last_logintime']),
+			'last_ip'=>$userinfos['last_ip'],
+			'login_count'=>$userinfos['login_count'].L('ci'),
+		);
+		$this->assign('userinfo',$userinfo);
+
+        $this->display();
+    }
+
+
+    // 更换密码
+    public function password(){
+		if($_POST['dosubmit']){
+			if(md5($_POST['verify'])	!= $_SESSION['verify']) {
+				$this->error(L('error_verify'));
+			}
+			if($_POST['password'] != $_POST['repassword']){
+				$this->error(L('password_repassword'));
+			}
+			$map	=	array();
+			$map['password']= sysmd5($_POST['oldpassword']);
+			if(isset($_POST['username'])) {
+				$map['username']	 =	 $_POST['username'];
+			}elseif(isset($_SESSION['adminid'])) {
+				$map['id']		=	$_SESSION['adminid'];
+			}
+			//检查用户
+			$User    =   M("user");
+			if(!$User->where($map)->field('id')->find()) {
+				$this->error(L('error_oldpassword'));
+			}else {
+				$User->updatetime = time();
+				$User->password	=	sysmd5($_POST['password']);
+				$User->save();
+				$this->success(L('do_success'));
+			 }
+		}else{
+			 $this->display();
+		}
+    }
+
+	// 修改资料
+	public function profile() {
+		if($_REQUEST['dosubmit']){
+			$User	 =	M("User");
+			if(!$User->create()) {
+				$this->error($User->getError());
+			}
+			$User->update_time = time();
+			$User->last_ip = get_client_ip();
+			$result	=	$User->save();
+			if(false !== $result) {
+				$this->success(L('do_success'));
+			}else{
+				$this->error(L('do_error'));
+			}
+		}else{
+			$User	 =	 M("user");
+			$vo	=	$User->getById($_SESSION['adminid']);
+			$this->assign('vo',$vo);
+			$this->display();
+		}
+	}
+
+}
+?>

+ 102 - 0
Ainaphp/Lib/Action/Admin/LangAction.class.php

@@ -0,0 +1,102 @@
+<?php
+/**
+ *
+ * Urlrule(URL规则)
+ *
+ */
+if(defined('APP_NAME')!='Ainaphp' && !defined("Ainaphp"))  exit("Access Denied");
+class LangAction extends AdminbaseAction {
+
+	protected  $langpath,$lang;
+    function _initialize()
+    {
+		parent::_initialize();
+		$this->langpath = LANG_PATH.LANG_NAME.'/';
+    }
+
+
+	function insert() {
+
+
+		$lang_path =LANG_PATH.$_POST['mark'].'/';
+		$r =dir_copy(LANG_PATH.'cn/',$lang_path);
+
+		$name = MODULE_NAME;
+		$model = D ($name);
+		if (false === $model->create ()) {
+			$this->error ( $model->getError () );
+		}
+		$id = $model->add();
+		if ($id !==false) {
+			$db=D('');
+			$db =   DB::getInstance();
+			$db->execute("INSERT INTO `aina_config`  (`varname`,`info`,`groupid`,`value`,`lang`) VALUES ('site_name','网站名称','2','','".$id."'),
+			('site_url','网站网址','2','','".$id."'),
+			('logo','网站LOGO','2','./Public/Images/logo.gif','".$id."'),
+			('site_email','站点邮箱','2',admin@bangju.com','".$id."'),
+			('seo_title','网站标题','2','','".$id."'),
+			('seo_keywords','关键词','2','','".$id."'),
+			('seo_description','网站简介','2','','".$id."'),
+			('member_register','允许新会员注册','3','1','".$id."'),
+			('member_emailcheck','新会员注册需要邮件验证','3','0','".$id."'),
+			('member_registecheck','新会员注册需要审核','3','1','".$id."'),
+			('member_login_verify','注册登陆开启验证码','3','1','".$id."'),
+			('member_emailchecktpl','邮件认证模板','3','','".$id."'),
+			('member_getpwdemaitpl','密码找回邮件内容','3','','".$id."')
+			;");
+			if(in_array($name,$this->cache_model)) savecache($name);
+			$jumpUrl = $_POST['forward'] ? $_POST['forward'] : U(MODULE_NAME.'/index');
+			$this->assign ( 'jumpUrl',$jumpUrl );
+			$this->success (L('add_ok'));
+		} else {
+			$this->error (L('add_error').': '.$model->getDbError());
+		}
+	}
+
+
+	function param()
+	{
+		$files = glob($this->langpath.'*');
+		$lang_files=array();
+		foreach($files as $key => $file) {
+			//$filename = basename($file);
+			$filename = pathinfo($file);
+	 		$lang_files[$key]['filename'] = $filename['filename'];
+			$lang_files[$key]['filepath'] = $file;
+			$temp = explode('_',$lang_files[$key]['filename']);
+			$lang_files[$key]['name'] = count($temp)>1 ? $temp[0].L('LANG_module') : L('LANG_common') ;
+		}
+		$this->assign ( 'id', $id );
+		$this->assign ( 'lang', LANG_NAME );
+		$this->assign ( 'files', $lang_files );
+		$this->display();
+
+	}
+	function editparam()
+	{
+		$file=  $_REQUEST['file'];
+		$value = F($file, $value='', $this->langpath);
+		$this->assign ( 'id', $id );
+		$this->assign ( 'file', $file );
+		$this->assign ( 'lang', LANG_NAME );
+		$this->assign ( 'list', $value );
+		$this->display();
+	}
+
+	function updateparam()
+	{
+		$file=  $_REQUEST['file'];
+		unset($_POST[C('TOKEN_NAME')]);
+
+		foreach($_POST as $key=>$r){
+			if($r)$data[strtoupper($key)]=$r;
+		}
+		$r = F($file,$data, $this->langpath);
+		if($r){
+			$this->success(L('do_ok'));
+		}else{
+			$this->error(L('add_error'));
+		 }
+	}
+}
+?>

+ 26 - 0
Ainaphp/Lib/Action/Admin/LogAction.class.php

@@ -0,0 +1,26 @@
+<?php
+
+if(!defined("Ainaphp")) exit("Access Denied");
+class LogAction extends  AdminbaseAction {
+    function _initialize()
+    {
+		parent::_initialize();
+    }
+	function delete(){
+		$day=intval($_GET['day']);
+		if($day==1){
+			$time = time()-60*60*24*30;
+		}elseif($day==2){
+			$time =  time()-60*60*24*90;
+		}elseif($day==3){
+			$time = time();
+		}else{
+			$this->error (L('do_empty'));
+		}
+
+		M(MODULE_NAME)->where("time < $time")->delete();
+		$this->success(L('delete_ok'));
+
+	}
+
+}

+ 181 - 0
Ainaphp/Lib/Action/Admin/LoginAction.class.php

@@ -0,0 +1,181 @@
+<?php
+/**
+ *
+ * Login(后台登陆页面)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class LoginAction extends Action{
+    private $adminid ,$groupid ,$sysConfig ,$cache_model,$Config,$menudata ;
+    function _initialize()
+    {
+		$this->sysConfig = F('sys.config');
+		C('ADMIN_ACCESS',$this->sysConfig['ADMIN_ACCESS']);
+
+		import('@.TagLib.TagLibYP');
+        $this->adminid = $_SESSION['adminid'];
+        $this->groupid = $_SESSION['groupid'];
+    }
+    /**
+     * 登录页
+     *
+     */
+    public function index()
+    {
+		if(is_file(RUNTIME_FILE))@unlink(RUNTIME_FILE);
+		$this->menudata = F('Menu');
+		$this->cache_model=array('Lang','Menu','Config','Module','Role','Category','Posid','Field','Type','Urlrule','Dbsource');
+		if(empty($this->sysConfig['ADMIN_ACCESS']) || empty($this->menudata)){
+			foreach($this->cache_model as $r){
+				savecache($r);
+			}
+			$this->sysConfig = F('sys.config');
+			C('ADMIN_ACCESS',$this->sysConfig['ADMIN_ACCESS']);
+		}
+		if($this->_adminid){
+			$this->assign('jumpUrl',U('Index/index'));
+			$this->success(L('logined'));
+		}
+		$this->assign ( 'admin_verify', $this->sysConfig['ADMIN_VERIFY'] );
+        $this->display();
+    }
+
+    /**
+     * 提交登录
+     *
+     */
+    public function doLogin()
+    {
+
+		$dao = M('User');
+		$ip =get_client_ip();
+
+		if(empty($this->sysConfig['ADMIN_ACCESS'])) $this->error(L('NO SYSTEM CONFIG FILE'));
+		$username = get_safe_replace(trim($_POST['username']));
+        $password = get_safe_replace(trim($_POST['password']));
+        $verifyCode = trim($_POST['verifyCode']);
+
+        if(empty($username) || empty($password)){
+           $this->error(L('empty_username_empty_password'));
+        }elseif($_SESSION['verify'] && $this->sysConfig['ADMIN_VERIFY'] &&  md5($verifyCode) != $_SESSION['verify']){
+           $this->error(L('error_verify'));
+        }
+
+		$time =time();
+		$logwhere=array();
+		$logwhere['time']=array('EGT',$time-1800);
+		$logwhere['ip']=array('eq',$ip);
+		$logwhere['error'] =1;
+		$lognum= M('Log')->where($logwhere)->count();
+		if($lognum>=5)$this->error("错误次数过多,请联系管理人员!");
+
+        $condition = array();
+        $condition['username'] =array('eq',$username);
+
+		import ( '@.ORG.RBAC' );
+        $authInfo = RBAC::authenticate($condition);
+        //使用用户名、密码和状态的方式进行认证
+        if(false === $authInfo) {
+			$data=array();
+			$data['username']=$username;
+			$data['ip']=$ip;
+			$data['time']=$time;
+			$data['note']=L('empty_userid');
+			$data['error'] =1;
+			M('Log')->add($data);
+            $this->error(L('empty_userid'));
+        }else {
+            if($authInfo['password'] != sysmd5($password)) {
+				$data=array();
+				$data['username']=$username;
+				$data['ip']=$ip;
+				$data['time']=$time;
+				$data['note']=L('password_error').':'.$password;
+				$data['error'] =1;
+				M('Log')->add($data);
+            	$this->error(L('password_error'));
+            }
+
+			$_SESSION['username'] = $authInfo['username'];
+			$_SESSION['adminid'] = $_SESSION['userid'] = $authInfo['id'];
+			$_SESSION['groupid'] = $authInfo['groupid'];
+			$_SESSION['adminaccess'] = C('ADMIN_ACCESS');
+            $_SESSION[C('USER_AUTH_KEY')]	=	$authInfo['id'];
+            $_SESSION['email']	=	$authInfo['email'];
+            $_SESSION['lastLoginTime']		=	$authInfo['last_logintime'];
+			$_SESSION['login_count']	=	$authInfo['login_count']+1;
+
+            if($authInfo['groupid']==1) {
+				$_SESSION[C('ADMIN_AUTH_KEY')]=true;
+            }
+
+            //保存登录信息
+
+			$data = array();
+			$data['id']	=	$authInfo['id'];
+			$data['last_logintime']	=	$time;
+			$data['last_ip']	=	 get_client_ip();
+			$data['login_count']	=	array('exp','login_count+1');
+			$dao->save($data);
+
+           // 缓存访问权限
+            RBAC::saveAccessList();
+
+				$data=array();
+				$data['username']=$username;
+				$data['ip']=$ip;
+				$data['time']=$time;
+				$data['note']=L('login_ok');
+				M('Log')->add($data);
+
+			if($_POST['ajax']){
+				$this->ajaxReturn($authInfo,L('login_ok'),1);
+			}else{
+				$this->assign('jumpUrl',U('Index/index'));
+				$this->success(L('login_ok'));
+			}
+		}
+
+    }
+
+
+    /**
+     * 退出登录
+     *
+     */
+    public function logout()
+    {
+		if(isset($_SESSION[C('USER_AUTH_KEY')])) {
+			unset($_SESSION[C('USER_AUTH_KEY')]);
+			unset($_SESSION);
+			session_destroy();
+            $this->assign('jumpUrl',U('Login/index'));
+			$this->success(L('loginouted'));
+        }else {
+			$this->assign('jumpUrl',U('Login/index'));
+            $this->error(L('logined'));
+        }
+    }
+
+    function checkEmail(){
+		$user=M('User');
+
+        $email=$_GET['email'];
+		$userid=intval($_GET['userid']);
+		if(empty($userid)){
+			if($user->getByEmail($email)){
+				 echo 'false';
+			}else{
+				echo 'true';
+			}
+		}else{
+			//判断邮箱是否已经使用
+			if($user->where("id!={$userid} and email='{$email}'")->find()){
+				 echo 'false';
+			}else{
+				echo 'true';
+			}
+		}
+        exit;
+	}
+}

+ 169 - 0
Ainaphp/Lib/Action/Admin/MainAction.class.php

@@ -0,0 +1,169 @@
+<?php
+/**
+ *
+ * Main(后台登陆页面)
+ *
+ */
+class MainAction extends AdminbaseAction {
+	protected   $cache_model;
+	function _initialize()
+    {
+		parent::_initialize();
+		if(empty($_SESSION['username']) || empty($_SESSION['adminid']) || $_SESSION['adminaccess'] != C('ADMIN_ACCESS') ){
+			$this->assign ( 'jumpUrl', U('Login/index') );
+			$this->error(L('no_login'));
+		}
+    }
+	public function index()
+	{
+		  $this->display();
+	}
+	public function right()
+	{
+		  $this->display();
+	}
+	public function footer() {
+		$this->display();
+	}
+
+	public function cache() {
+		dir_delete(RUNTIME_PATH.'Html/');
+		dir_delete(RUNTIME_PATH.'Cache/');
+		if(is_file(RUNTIME_PATH.'~runtime.php'))@unlink(RUNTIME_PATH.'~runtime.php');
+		if(is_file(RUNTIME_PATH.'~allinone.php'))@unlink(RUNTIME_PATH.'~allinone.php');
+		R('Admin/Category/repair');
+		R('Admin/Category/repair');
+
+		foreach($this->cache_model as $r){
+			savecache($r);
+		}
+		$this->assign ( 'jumpUrl', U('Main/main') );
+		$this->success(L('do_success'));
+	}
+
+	public function top() {
+		$role	=	F("Role");
+		$this->assign('usergroup',$role[$_SESSION['groupid']]['name']);
+		$menu = $this->getnav(0);
+		$this->assign('menuGroupList',$menu['nav']);
+		$this->assign($this->Config);
+		$this->display();
+	}
+
+
+	public function menu() {
+
+		$parentid =	intval($_GET['parentid']);
+		if($parentid){
+			$menu = $this->getnav($parentid);
+			$this->assign('pname',$menu['bnav']);
+            $this->assign('menu',$menu['nav']);
+		}
+		$this->display();
+	}
+
+    public function main() {
+
+		$db=D('');
+		$db =   DB::getInstance();
+		$tables = $db->getTables();
+
+		$info = array(
+            'license'=> '<b></b><b></b>',
+			'ainaphp_VERSION'=> VERSION.' '.UPDATETIME.'',
+            'SERVER_SOFTWARE'=>PHP_OS.' '.$_SERVER["SERVER_SOFTWARE"],
+            'mysql_get_server_info'=>php_sapi_name(),
+			'MYSQL_VERSION' => mysql_get_server_info(),
+            'upload_max_filesize'=> ini_get('upload_max_filesize'),
+            'max_execution_time'=>ini_get('max_execution_time').L('miao'),
+			'disk_free_space'=>round((@disk_free_space(".")/(1024*1024)),2).'M',
+            );
+        $this->assign('server_info',$info);
+		foreach ((array)$this->module as $rw){
+			if($rw['type']==1){
+				$molule= M($rw['name']);
+				$rw['counts'] = $molule->count();;
+				$mdata['moduledata'][] = $rw;
+			}
+        }
+
+
+
+		$molule= M('User');
+		$counts = $molule->count();
+		$userinfos = $molule->find($_SESSION['adminid']);
+		$mdata['moduledata'][]=array('title'=>L('user_counts'),'counts'=>$counts);
+
+		$molule= M('Category');$counts = $molule->count();
+		$mdata['moduledata'][]=array('title'=>L('Category_counts'),'counts'=>$counts);
+		$this->assign($mdata);
+		$role =F('Role');
+
+		$userinfo=array(
+			'username'=>$userinfos['username'],
+			'groupname'=>$role[$userinfos['groupid']]['name'],
+			'logintime'=>toDate($userinfos['last_logintime']),
+			'last_ip'=>$userinfos['last_ip'],
+			'login_count'=>$userinfos['login_count'].L('ci'),
+		);
+		$this->assign('userinfo',$userinfo);
+
+        $this->display();
+    }
+
+
+    // 更换密码
+    public function password(){
+		if($_POST['dosubmit']){
+			if(md5($_POST['verify'])	!= $_SESSION['verify']) {
+				$this->error(L('error_verify'));
+			}
+			if($_POST['password'] != $_POST['repassword']){
+				$this->error(L('password_repassword'));
+			}
+			$map	=	array();
+			$map['password']= sysmd5($_POST['oldpassword']);
+			if(isset($_POST['username'])) {
+				$map['username']	 =	 $_POST['username'];
+			}elseif(isset($_SESSION['adminid'])) {
+				$map['id']		=	$_SESSION['adminid'];
+			}
+			//检查用户
+			$User    =   M("user");
+			if(!$User->where($map)->field('id')->find()) {
+				$this->error(L('error_oldpassword'));
+			}else {
+				$User->updatetime = time();
+				$User->password	=	sysmd5($_POST['password']);
+				$User->save();
+				$this->success(L('do_success'));
+			 }
+		}else{
+			 $this->display();
+		}
+    }
+
+	// 修改资料
+	public function profile() {
+		if($_REQUEST['dosubmit']){
+			$User	 =	M("User");
+			if(!$User->create()) {
+				$this->error($User->getError());
+			}
+			$User->update_time = time();
+			$User->last_ip = get_client_ip();
+			$result	=	$User->save();
+			if(false !== $result) {
+				$this->success(L('do_success'));
+			}else{
+				$this->error(L('do_error'));
+			}
+		}else{
+			$User	 =	 M("user");
+			$vo	=	$User->getById($_SESSION['adminid']);
+			$this->assign('vo',$vo);
+			$this->display();
+		}
+	}
+}
+?>

+ 97 - 0
Ainaphp/Lib/Action/Admin/MenuAction.class.php

@@ -0,0 +1,97 @@
+<?php
+/**
+ *
+ * Menu(菜单管理)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class MenuAction extends AdminbaseAction
+{
+    public $dao;
+	function _initialize()
+	{
+		parent::_initialize();
+		$this->dao = D('Admin/menu');
+		$this->assign('actionname',$this->getActionName());
+
+	}
+
+	/**
+     * 列表
+     *
+     */
+	public function index()
+	{
+		$result = $this->menudata;
+		foreach($result as $r) {
+			if($r['type']!=1) continue;
+			$r['str_manage'] = '<a href="'.U('Menu/add',array( 'parentid' => $r['id'])).'">'.L('menu_add_submenu').'</a> | <a href="'.U('Menu/edit',array( 'id' => $r['id'])).'">'.L('edit').'</a> | <a href="javascript:confirm_delete(\''.U('Menu/delete',array( 'id' => $r['id'])).'\')">'.L('delete').'</a> ';
+			$r['status'] ? $r['status']='<font color="green">'.L('enable').'</font>' : $r['status']='<font color="red">'.L(' disable').'</font>' ;
+			$array[] = $r;
+		}
+
+		$str  = "<tr>
+					<td width='40' align='center'><input name='listorders[\$id]' type='text' size='3' value='\$listorder' class='input-text-c'></td>
+					<td align='center'>\$id</td>
+					<td >\$spacer\$name</td>
+					<td align='center'>\$status</td>
+					<td align='center'>\$str_manage</td>
+				</tr>";
+		import ( '@.ORG.Tree' );
+		$tree = new Tree ($array);
+		$tree->icon = array('&nbsp;&nbsp;&nbsp;<span>'.L('tree_1').'</span>','&nbsp;&nbsp;&nbsp;<span>'.L('tree_2').'</span>','&nbsp;&nbsp;&nbsp;<span>'.L('tree_3').'</span>');
+		$tree->nbsp = '&nbsp;&nbsp;&nbsp;';
+		$select_categorys = $tree->get_tree(0, $str);
+		$this->assign('select_categorys', $select_categorys);
+		$this->display();
+	}
+
+	/**
+     * 提交
+     *
+     */
+	public function _before_add()
+	{
+		$parentid =	intval($_GET['parentid']);
+		import ( '@.ORG.Tree' );
+		$result = $this->menudata;
+		foreach($result as $r) {
+			if($r['type']!=1) continue;
+			$r['selected'] = $r['id'] == $parentid ? 'selected' : '';
+			$array[] = $r;
+		}
+
+		$str  = "<option value='\$id' \$selected>\$spacer \$name</option>";
+
+		$tree = new Tree ($array);
+		$tree->icon = array(L('tree_1'),L('tree_2'),L('tree_3'));
+		$select_categorys = $tree->get_tree(0, $str,$parentid);
+		$this->assign('select_categorys', $select_categorys);
+	}
+
+
+
+	function edit() {
+
+		$id =	intval($_GET['id']);;
+		$vo = $this->menudata[$id];
+		$parentid =	intval($vo['parentid']);
+		import ( '@.ORG.Tree' );
+		$result = $this->menudata;
+		foreach($result as $r) {
+			if($r['type']!=1) continue;
+			$r['selected'] = $r['id'] == $parentid ? 'selected' : '';
+			$array[] = $r;
+		}
+		$str  = "<option value='\$id' \$selected>\$spacer \$name</option>";
+		$tree = new Tree ($array);
+		$tree->icon = array(L('tree_1'),L('tree_2'),L('tree_3'));
+		$select_categorys = $tree->get_tree(0, $str,$parentid);
+		$this->assign('select_categorys', $select_categorys);
+		$this->assign ( 'vo', $vo );
+		$this->display ();
+	}
+
+
+}
+?>

+ 174 - 0
Ainaphp/Lib/Action/Admin/ModuleAction.class.php

@@ -0,0 +1,174 @@
+<?php
+/**
+ *
+ * Module(模型管理)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class ModuleAction extends AdminbaseAction {
+
+	protected $dao;
+    function _initialize()
+    {
+		parent::_initialize();
+		$this->dao=D('Admin/module');
+
+		$this->Role = F('Role');
+		$this->assign('Role',$this->Role);
+    }
+
+
+ 	function _before_index(){
+		if($_REQUEST ['type']){
+			$_REQUEST['where'] = 'type='.intval($_REQUEST ['type']);
+		}else{
+			$_REQUEST['where'] = 'type=1';
+		}
+
+	}
+
+	function _before_add(){
+		if(empty($_GET['type'])) $_GET['type']=1;
+
+	}
+
+	function _before_update(){
+		$_POST['postgroup'] = implode(',',$_POST['postgroup']);
+	}
+
+
+
+	function insert(){
+
+		if($_GET['isajax']){
+			$name=$_GET['name'];
+			$tablename = C('DB_PREFIX').$name;
+			$db=D('');
+			$db =   DB::getInstance();
+			$tables = $db->getTables();
+			if(in_array($tablename,$tables)){
+				echo 'false';
+			}else{
+				echo 'true';
+			}
+			exit;
+		}
+		$db=D('');
+		$db =   DB::getInstance();
+
+		$tablename = C('DB_PREFIX').$_POST['name'];
+		$_POST['name'] = ucfirst($_POST['name']);
+		$model = $this->dao;
+		if (false === $model->create ()) {
+			$this->error ( $model->getError () );
+		}
+		$moduleid = $model->add();
+		if(empty($moduleid)) $this->error (L('add_error').': '.$model->getDbError());
+
+		if(empty($_POST['emptytable'])){
+			$db->execute("CREATE TABLE `".$tablename."` (
+			  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
+			  `catid` smallint(5) unsigned NOT NULL DEFAULT '0',
+			  `userid` int(8) unsigned NOT NULL DEFAULT '0',
+			  `username` varchar(40) NOT NULL DEFAULT '',
+			  `title` varchar(120) NOT NULL DEFAULT '',
+			  `title_style` varchar(40) NOT NULL DEFAULT '',
+			  `thumb` varchar(100) NOT NULL DEFAULT '',
+			  `keywords` varchar(120) NOT NULL DEFAULT '',
+			  `description` mediumtext NOT NULL,
+			  `content` mediumtext NOT NULL,
+			  `url` varchar(60) NOT NULL DEFAULT '',
+			  `template` varchar(40) NOT NULL DEFAULT '',
+			  `posid` tinyint(2) unsigned NOT NULL DEFAULT '0',
+			  `status` tinyint(1) unsigned NOT NULL DEFAULT '0',
+			  `listorder` int(10) unsigned NOT NULL DEFAULT '0',
+			  `hits` int(11) unsigned NOT NULL DEFAULT '0',
+			  `createtime` int(11) unsigned NOT NULL DEFAULT '0',
+			  `updatetime` int(11) unsigned NOT NULL DEFAULT '0',
+			  `lang` tinyint(1) unsigned NOT NULL DEFAULT '0',
+			  PRIMARY KEY (`id`),
+			  KEY `status` (`id`,`status`,`listorder`),
+			  KEY `catid` (`id`,`catid`,`status`),
+			  KEY `listorder` (`id`,`catid`,`status`,`listorder`)
+			) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8");
+
+			$db->execute("INSERT INTO `".C('DB_PREFIX')."field` VALUES ('', '".$moduleid."', 'catid', '".L('catid')."', '', '1', '1', '6', '', '".L('catid_error')."', '', 'catid', '','1','', '0', '1', '1')");
+			$db->execute("INSERT INTO `".C('DB_PREFIX')."field` VALUES ('', '".$moduleid."', 'title', '".L('title')."', '', '1', '1', '80', '', '".L('title_error')."', '', 'title', 'array (\n  \'thumb\' => \'1\',\n  \'style\' => \'1\',\n  \'size\' => \'55\',\n)','1','',  '0', '1', '1')");
+			$db->execute("INSERT INTO `".C('DB_PREFIX')."field` VALUES ('', '".$moduleid."', 'keywords', '".L('keywords')."', '', '0', '0', '80', '', '', '', 'text', 'array (\n  \'size\' => \'55\',\n  \'default\' => \'\',\n  \'ispassword\' => \'0\',\n  \'fieldtype\' => \'varchar\',\n)','1','',  '2', '1', '1')");
+			$db->execute("INSERT INTO `".C('DB_PREFIX')."field` VALUES ('', '".$moduleid."', 'description', '".L('description')."', '', '0', '0', '0', '', '', '', 'textarea', 'array (\n  \'fieldtype\' => \'mediumtext\',\n  \'rows\' => \'4\',\n  \'cols\' => \'55\',\n  \'default\' => \'\',\n)','1','',  '3', '1', '1')");
+			$db->execute("INSERT INTO `".C('DB_PREFIX')."field` VALUES ('', '".$moduleid."', 'content', '".L('content')."', '', '0', '0', '0', '', '', '', 'editor', 'array (\n  \'toolbar\' => \'full\',\n  \'default\' => \'\',\n  \'height\' => \'\',\n  \'showpage\' => \'1\',\n  \'enablekeylink\' => \'0\',\n  \'replacenum\' => \'\',\n  \'enablesaveimage\' => \'0\',\n  \'flashupload\' => \'1\',\n  \'alowuploadexts\' => \'\',\n)','1','',  '10', '1', '1')");
+			$db->execute("INSERT INTO `".C('DB_PREFIX')."field` VALUES ('', '".$moduleid."', 'createtime', '".L('createtime')."', '', '0', '0', '0', '', '', '', 'datetime', '','1','3,4',  '93', '1', '1')");
+			//$db->execute("INSERT INTO `".C('DB_PREFIX')."field` VALUES ('', '".$moduleid."', 'recommend', '".L('recommend')."', '', '0', '0', '1', '', '', '', 'radio', 'array (\n  \'options\' => \'".L('recommend')."|1\r\n".L('norecommend')."|0\',\n  \'fieldtype\' => \'tinyint\',\n  \'numbertype\' => \'1\',\n  \'labelwidth\' => \'\',\n  \'default\' => \'\',\n)','1','3,4', '93', '0', '0')");
+			//$db->execute("INSERT INTO `".C('DB_PREFIX')."field` VALUES ('', '".$moduleid."', 'readpoint', '".L('readpoint')."', '', '0', '0', '5', '', '', '', 'number', 'array (\n  \'size\' => \'5\',\n  \'numbertype\' => \'1\',\n  \'decimaldigits\' => \'0\',\n  \'default\' => \'0\',\n)','1','3,4', '93', '0', '0')");
+			$db->execute("INSERT INTO `".C('DB_PREFIX')."field` VALUES ('', '".$moduleid."', 'hits', '".L('hits')."', '', '0', '0', '8', '', '', '', 'number', 'array (\n  \'size\' => \'10\',\n  \'numbertype\' => \'1\',\n  \'decimaldigits\' => \'0\',\n  \'default\' => \'0\',\n)','1','3,4',  '93', '0', '0')");
+			//$db->execute("INSERT INTO `".C('DB_PREFIX')."field` VALUES ('', '".$moduleid."', 'readgroup', '".L('readgroup')."', '', '0', '0', '0', '', '', '', 'groupid', 'array (\n  \'inputtype\' => \'checkbox\',\n  \'fieldtype\' => \'tinyint\',\n  \'labelwidth\' => \'85\',\n  \'default\' => \'\',\n)','1','3,4', '96', '0', '1')");
+			$db->execute("INSERT INTO `".C('DB_PREFIX')."field` VALUES ('', '".$moduleid."', 'posid', '".L('posid')."', '', '0', '0', '0', '', '', '', 'posid', '','1','', '97', '1', '1')");
+			$db->execute("INSERT INTO `".C('DB_PREFIX')."field` VALUES ('', '".$moduleid."', 'template', '".L('template')."', '', '0', '0', '0', '', '', '', 'template', '','1','3,4', '98', '1', '1')");
+			$db->execute("INSERT INTO `".C('DB_PREFIX')."field` VALUES ('', '".$moduleid."', 'status', '".L('status')."', '', '0', '0', '0', '', '', '', 'radio', 'array (\n  \'options\' => \'".L('fabu')."|1\r\n".L('dingshi')."|0\',\n  \'fieldtype\' => \'tinyint\',\n  \'numbertype\' => \'1\',\n  \'labelwidth\' => \'75\',\n  \'default\' => \'1\',\n)','1','3,4','99', '1', '1')");
+		}else{
+			$db->execute("CREATE TABLE `".$tablename."` (
+			  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
+			  `status` tinyint(1) unsigned NOT NULL DEFAULT '0',
+			  `userid` int(8) unsigned NOT NULL DEFAULT '0',
+			  `username` varchar(40) NOT NULL DEFAULT '',
+			  `url` varchar(60) NOT NULL DEFAULT '',
+			  `listorder` int(10) unsigned NOT NULL DEFAULT '0',
+			  `createtime` int(11) unsigned NOT NULL DEFAULT '0',
+			  `updatetime` int(11) unsigned NOT NULL DEFAULT '0',
+			  `lang` tinyint(1) unsigned NOT NULL DEFAULT '0',
+			  PRIMARY KEY (`id`)
+			) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8");
+			$db->execute("INSERT INTO `".C('DB_PREFIX')."field` VALUES ('', '".$moduleid."', 'createtime', '".L('createtime')."', '', '1', '0', '0', '', '', '', 'datetime', '','0','3,4',  '93', '1', '1')");
+			$db->execute("INSERT INTO `".C('DB_PREFIX')."field` VALUES ('', '".$moduleid."', 'status', '".L('status')."', '', '0', '0', '0', '', '', '', 'radio', 'array (\n  \'options\' => \'".L('isshenhe')."|1\r\n".L('noshenhe')."|0\',\n  \'fieldtype\' => \'tinyint\',\n  \'numbertype\' => \'1\',\n  \'labelwidth\' => \'75\',\n  \'default\' => \'1\',\n)','0','3,4', '99', '1', '1')");
+		}
+
+		if ($moduleid  !==false) {
+
+			$menu=M('Menu');
+			$data=array();
+			$data['parentid'] =  $_POST['type']==2 ? 4 : 3;
+			$data['model'] = $_POST['name'];
+			$data['action'] = 'index';
+			$data['type'] = 1;
+			$data['status'] = 1;
+			$data['name'] =  $_POST['title'];
+			$data['listorder']=9;
+			$pmenuid = $menu->data($data)->add();
+			$data['parentid'] = $pmenuid;
+			$data['action'] ='add';
+			$data['name'] = L('module_addmenu');
+			$menu->data($data)->add();
+			savecache('Module');
+			savecache('Menu');
+			savecache('Field',$moduleid);
+			$this->assign ( 'jumpUrl', U(MODULE_NAME.'/index') );
+			$this->success (L('add_ok'));
+		} else {
+			$this->error (L('add_error').': '.$model->getDbError());
+		}
+	}
+
+	function delete() {
+		$id =intval($_GET['id']);
+		$r = $this->dao->find($id);
+		if(empty($r)) $this->error (L('do_empty'));
+
+		$tablename = C('DB_PREFIX').$this->module[$id]['name'];
+		$m = $this->dao->delete($id);
+		if($m){
+			$t =$this->dao->execute("DROP TABLE IF EXISTS `".$tablename."`");
+			$module = ucfirst($this->module[$id]['name']);
+			$menu = M('Menu');
+			$menu->where("model='".$module."'")->delete();
+			$module = M('Field');
+			$f = $module->where('moduleid='.$id)->delete();
+
+			savecache('Module');
+			savecache('Menu');
+			@unlink(RUNTIME_PATH.'Data/'.$id.'_Field.php');
+			$this->success (L('do_ok'));
+		}
+	}
+
+}
+?>

+ 135 - 0
Ainaphp/Lib/Action/Admin/NodeAction.class.php

@@ -0,0 +1,135 @@
+<?php
+/**
+ *
+ * Node (权限管理)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class NodeAction extends AdminbaseAction {
+
+	protected $dao,$groups;
+    function _initialize()
+    {
+		parent::_initialize();
+		$this->dao=D('node');
+
+		$this->groups[0]=array('id'=>0,'name'=>L('ACCESS_PUBLIC'));
+		foreach($this->menudata as $key=>$r){ if($r['parentid']==0)$this->groups[$r[id]]=$r;}
+		$this->assign('groups', $this->groups);
+    }
+
+
+	function index(){
+
+		$data[]=array('name'=>'index','title'=>'列表','pid'=>90,'status'=>1,'listorder'=>0,'level'=>3,'groupid'=>3);
+		$data[]=array('name'=>'add','title'=>'添加','pid'=>90,'status'=>1,'listorder'=>0,'level'=>3,'groupid'=>3);
+		$data[]=array('name'=>'edit','title'=>'修改','pid'=>90,'status'=>1,'listorder'=>0,'level'=>3,'groupid'=>3);
+		$data[]=array('name'=>'insert','title'=>'插入','pid'=>90,'status'=>1,'listorder'=>0,'level'=>3,'groupid'=>3);
+		$data[]=array('name'=>'update','title'=>'更新','pid'=>90,'status'=>1,'listorder'=>0,'level'=>3,'groupid'=>3);
+		$data[]=array('name'=>'delete','title'=>'删除','pid'=>90,'status'=>1,'listorder'=>0,'level'=>3,'groupid'=>3);
+		$data[]=array('name'=>'status','title'=>'状态','pid'=>90,'status'=>1,'listorder'=>0,'level'=>3,'groupid'=>3);
+		$data[]=array('name'=>'listorder','title'=>'排序','pid'=>90,'status'=>1,'listorder'=>0,'level'=>3,'groupid'=>3);
+		//$data[]=array('name'=>'deleteall','title'=>'批量删除','pid'=>90,'status'=>1,'listorder'=>0,'level'=>3,'groupid'=>3);
+		//$data[]=array('name'=>'statusallok','title'=>'批量审核','pid'=>90,'status'=>1,'listorder'=>0,'level'=>3,'groupid'=>3);
+
+		foreach($data as $sql){
+			//$this->dao->add($sql);
+		}
+
+
+
+		$str  = "<tr>
+					<td align='center'><input name='listorders[\$id]' type='text' size='2' value='\$listorder' class='input-text-c'></td>
+					<td >\$spacer\$title</td>
+					<td >\$name</td>
+					<td align='center'>\$status</td>
+					<td align='center'>\$str_manage</td>
+				</tr>";
+		import ( '@.ORG.Tree' );
+
+
+
+		foreach($this->groups as $key=>$res){
+
+			$result=$this->dao->where("groupid=$res[id]")->select();
+			$array=array();
+			foreach($result as $r) {
+				$r['str_manage'] = '<a href="'.U('Node/add',array( 'pid' => $r['id'],'groupid'=>$r['groupid'])).'">'.L('add').'</a> | <a href="'.U('Node/edit',array( 'id' => $r['id'])).'">'.L('edit').'</a> | <a href="javascript:confirm_delete(\''.U('Node/delete',array( 'id' => $r['id'])).'\',\''.L('confirm',array('message'=>$r['cname'])).'\')">'.L('delete').'</a> ';
+				$r['parentid']=$r['pid'];
+				$r['status']==1 ? $r['status']=L('enable') : $r['status']=L('disable') ;
+				$array[] = $r;
+			}
+
+			$tree = new Tree ($array);
+			$tree->icon = array('&nbsp;&nbsp;&nbsp;'.L('tree_1'),'&nbsp;&nbsp;&nbsp;'.L('tree_2'),'&nbsp;&nbsp;&nbsp;'.L('tree_3'));
+			$tree->nbsp = '&nbsp;&nbsp;&nbsp;';
+			$data = $tree->get_tree(1, $str);
+
+			$nodes[$res['id']]['data']  = $data;
+			$nodes[$res['id']]['groupinfo']=$res;
+		}
+
+		$this->assign('nodes', $nodes);
+		$this->display();
+	}
+
+	function _before_insert(){
+		if($_POST['pid']){
+			$level =$this->dao->getById($_POST['pid']);
+			$_POST['level']=$level['level']+1;
+		}else{
+			$_POST['level']=1;
+		}
+	}
+
+	function _before_update(){
+		if($_POST['pid']){
+			$level =$this->dao->getById($_POST['pid']);
+			$_POST['level']=$level['level']+1;
+		}else{
+			$_POST['level']=1;
+		}
+
+	}
+	function _before_add(){
+		$groupid=	intval($_GET['groupid']);
+		$pid =	intval($_GET['pid']);
+		import ( '@.ORG.Tree' );
+		$result = $this->dao->select();
+		foreach($result as $r) {
+			if($r['status']!=1 || $r['level']==3) continue;
+			$r['selected'] = $r['id'] == $pid ? 'selected' : '';
+			$r['parentid']=$r['pid'];
+			$array[] = $r;
+		}
+		$str  = "<option value='\$id' \$selected>\$spacer \$title</option>";
+		$tree = new Tree ($array);
+		$nodes  = $tree->get_tree(0, $str,$pid);
+		$this->assign('nodes', $nodes);
+		$this->assign('groupid', $groupid);
+	}
+	function edit(){
+
+		$id =	intval($_GET['id']);;
+		$vo = $this->dao->getById($id);
+		$this->assign('groupid', $vo['groupid']);
+		$pid =	intval($vo['pid']);
+		import ( '@.ORG.Tree' );
+		$result = $this->dao->select();
+		foreach($result as $r) {
+			if($r['status']!=1) continue;
+			$r['selected'] = $r['id'] == $pid ? 'selected' : '';
+			$r['parentid']=$r['pid'];
+			$array[] = $r;
+		}
+		$str  = "<option value='\$id' \$selected>\$spacer \$title</option>";
+		$tree = new Tree ($array);
+		$nodes = $tree->get_tree(0, $str,$pid);
+		$this->assign('nodes', $nodes);
+		$this->assign ( 'udate', $vo );
+		$this->display ();
+
+	}
+
+}
+?>

+ 18 - 0
Ainaphp/Lib/Action/Admin/PosidAction.class.php

@@ -0,0 +1,18 @@
+<?php
+/**
+ *
+ * Posid (推荐位管理)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class PosidAction extends AdminbaseAction {
+
+	protected $dao;
+    function _initialize()
+    {
+		parent::_initialize();
+    }
+
+
+}
+?>

+ 39 - 0
Ainaphp/Lib/Action/Admin/RoleAction.class.php

@@ -0,0 +1,39 @@
+<?php
+/**
+ *
+ * Role(会员组管理)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class RoleAction extends AdminbaseAction {
+
+	protected $dao;
+    function _initialize()
+    {
+		parent::_initialize();
+
+    }
+
+	public function _before_insert()
+    {
+		$_POST['allowpost'] = $_POST['allowpost'] ? 1 : 0 ;
+		$_POST['allowpostverify'] = $_POST['allowpostverify'] ? 1 : 0 ;
+		$_POST['allowupgrade'] = $_POST['allowupgrade'] ? 1 : 0 ;
+		$_POST['allowsendmessage'] = $_POST['allowsendmessage'] ? 1 : 0 ;
+		$_POST['allowattachment'] = $_POST['allowattachment'] ? 1 : 0 ;
+		$_POST['allowsearch'] = $_POST['allowsearch'] ? 1 : 0 ;
+	}
+
+
+	public function _before_update()
+    {
+		$_POST['allowpost'] = $_POST['allowpost'] ? 1 : 0 ;
+		$_POST['allowpostverify'] = $_POST['allowpostverify'] ? 1 : 0 ;
+		$_POST['allowupgrade'] = $_POST['allowupgrade'] ? 1 : 0 ;
+		$_POST['allowsendmessage'] = $_POST['allowsendmessage'] ? 1 : 0 ;
+		$_POST['allowattachment'] = $_POST['allowattachment'] ? 1 : 0 ;
+		$_POST['allowsearch'] = $_POST['allowsearch'] ? 1 : 0 ;
+	}
+
+}
+?>

+ 231 - 0
Ainaphp/Lib/Action/Admin/SlideAction.class.php

@@ -0,0 +1,231 @@
+<?php
+/**
+ *
+ * Slide(幻灯片管理)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class SlideAction extends AdminbaseAction {
+
+	protected  $Tplpath,$Flashpath,$Xmlpath;
+    function _initialize()
+    {
+		parent::_initialize();
+		$this->Tplpath = TMPL_PATH.'/Home/'.$this->sysConfig['DEFAULT_THEME'].'/';
+		//$this->Flashpath = TMPL_PATH.$this->sysConfig['DEFAULT_THEME'].'/Public/flash/';
+		$this->Xmlpath = TMPL_PATH.'/Home/'.$this->sysConfig['DEFAULT_THEME'].'/Public/xml/';
+
+    }
+
+
+	function _before_add(){
+		$Tpl = template_file('Slide');
+		$this->assign ( 'Tpl', $Tpl );
+
+
+	}
+
+	function _before_edit(){
+
+		$Tpl = template_file('Slide');
+		$this->assign ( 'Tpl', $Tpl );
+		//$Flash= template_file('',$this->Flashpath,'swf');
+		//$this->assign ( 'Flash', $Flash);
+	}
+	function edittpl(){
+		$file = $this->Tplpath.'Slide_'.$_REQUEST['tpl'].'.html';
+		if($_POST['content']){
+			file_put_contents($file,htmlspecialchars_decode(stripslashes($_POST['content'])));
+			$this->success (L('do_ok'));
+		}else{
+			$content = htmlspecialchars(file_get_contents($file));
+			echo ' <form method="post" id="myform"  action="'.U('Slide/edittpl').'">Slide_'.$_GET['tpl'].'.html<input type="hidden" name="tpl" value="'.$_GET['tpl'].'"/><textarea  name="content" id="content" style="width:100%;height:500px;"  >'.$content.'</textarea>  <input type="hidden" name="isajax" value="1" />
+			 <input name="dosubmit" type="submit" value="1" style="display:none;"class="hidden" id="dosubmit"> </form>';
+		}
+	}
+
+	function picmanage(){
+		$fid=intval($_REQUEST['fid']);
+		if(!$fid) $this->error(L('do_empty'));
+		$map = array();
+		if(APP_LANG)$map['lang']=array('eq',LANG_ID);
+
+		$slide = D('Slide')->find($fid);
+
+		$map['fid']=array('eq',$fid);
+		$list = D('Slide_data')->where($map)->order(" listorder ASC ,id DESC ")->select();
+		$this->assign ( 'list', $list );
+		$this->assign ( 'fid', $fid );
+		$this->assign ( 'slide', $slide );
+		$this->display();
+
+	}
+
+	function addpic(){
+		$fid=intval($_REQUEST['fid']);
+		if(!$fid) $this->error(L('do_empty'));
+		$map = array();
+		if(APP_LANG)$map['lang']=array('eq',LANG_ID);
+
+		$slide = D('Slide')->find($fid);
+		$map['fid']=array('eq',$id);
+		$list = D('Slide_data')->where($map)->order(" listorder ASC ,id DESC ")->select();
+
+
+		$yourphp_auth_key = sysmd5(C('ADMIN_ACCESS').$_SERVER['HTTP_USER_AGENT']);
+		$yourphp_auth = authcode('1-1-0-10-jpeg,jpg,png,gif-5-230', 'ENCODE',$yourphp_auth_key);
+		$this->assign('yourphp_auth',$yourphp_auth);
+
+		$vo['status'] = 1;
+		$this->assign ( 'vo', $vo);
+		$this->assign ( 'list', $list );
+		$this->assign ( 'fid', $fid );
+		$this->assign ( 'slide', $slide );
+
+		$this->display ('Slide:editpic');
+
+	}
+
+	function editpic(){
+		$id=intval($_REQUEST['id']);
+		$fid=intval($_REQUEST['fid']);
+		if(!$id) $this->error(L('do_empty'));
+		$slide = D('Slide')->find($fid);
+
+		//isadmin,more,isthumb,file_limit,file_types,file_size,moduleid,
+		$yourphp_auth_key = sysmd5(C('ADMIN_ACCESS').$_SERVER['HTTP_USER_AGENT']);
+		$yourphp_auth = authcode('1-1-0-10-jpeg,jpg,png,gif-5-230', 'ENCODE',$yourphp_auth_key);
+		$this->assign('yourphp_auth',$yourphp_auth);
+
+		$vo = D('Slide_data')->find($id);
+		$this->assign ( 'fid', $fid );
+		$this->assign ( 'vo', $vo );
+		$this->assign ( 'slide', $slide );
+		$this->display ();
+
+	}
+
+	function insertpic(){
+
+		if(APP_LANG)$_POST['lang']=LANG_ID;
+		//if($_POST['setup']) $_POST['setup']=array2string($_POST['setup']);
+		$name = 'Slide_data';
+		$model = D ($name);
+		if (false === $model->create ()) {
+			$this->error ( $model->getError () );
+		}
+		$_POST['id'] = $id= $model->add();
+		if ($id !==false) {
+
+			if($_POST['aid']){
+				$Attachment =M('Attachment');
+				$aids =  implode(',',$_POST['aid']);
+				$data['id']= $_POST['id'];
+				$data['catid']= $_POST['fid'];
+				$data['status']= '1';
+				$Attachment->where("aid in (".$aids.")")->save($data);
+			}
+
+			$this->assign ( 'jumpUrl', U('Slide/picmanage?fid='.$_POST['fid']) );
+			$this->success (L('add_ok'));
+		} else {
+			$this->error (L('add_error').': '.$model->getDbError());
+		}
+	}
+
+	function updatepic(){
+
+		$name = 'Slide_data';
+		$model = D ( $name );
+		if (false === $model->create ()) {
+			$this->error ( $model->getError () );
+		}
+		if (false !== $model->save ()) {
+
+			if($_POST['aid']){
+				$Attachment =M('Attachment');
+				$aids =  implode(',',$_POST['aid']);
+				$data['id']= $_POST['id'];
+				$data['catid']= $_POST['fid'];
+				$data['status']= '1';
+				$Attachment->where("aid in (".$aids.")")->save($data);
+			}
+
+			$this->success (L('edit_ok'));
+		} else {
+			$this->success (L('edit_error').': '.$model->getDbError());
+		}
+	}
+
+	function param()
+	{
+		$files = glob(LANG_NAMEpath.'*');
+		$lang_files=array();
+		foreach($files as $key => $file) {
+			//$filename = basename($file);
+			$filename = pathinfo($file);
+	 		$lang_files[$key]['filename'] = $filename['filename'];
+			$lang_files[$key]['filepath'] = $file;
+			$temp = explode('_',$filename);
+			$lang_files[$key]['name'] = count($temp)>1 ? $temp[0].L('LANG_module') : L('LANG_common') ;
+		}
+		$this->assign ( 'id', $id );
+		$this->assign ( 'lang', LANG_NAME );
+		$this->assign ( 'files', $lang_files );
+		$this->display();
+
+	}
+
+
+	function listorder(){
+		$name ='Slide_data';
+		$model = M ( $name );
+		$pk = $model->getPk ();
+		$ids = $_POST['listorders'];
+		foreach($ids as $key=>$r) {
+			$data['listorder']=$r;
+			$model->where($pk .'='.$key)->save($data);
+		}
+		$this->success (L('do_ok'));
+
+	}
+
+
+	function delete(){
+		$name = MODULE_NAME;
+		$model = M ( $name );
+		$pk = $model->getPk ();
+		$id = $_REQUEST [$pk];
+		if (isset ( $id )) {
+			if(false!==$model->delete($id)){
+				$name ='Slide_data';
+				$model = M ( $name );
+				$model->where("fid=".$id)->delete();
+				delattach(array('moduleid'=>'230','catid'=>$id));
+				$this->success(L('delete_ok'));
+			}else{
+				$this->error(L('delete_error').': '.$model->getDbError());
+			}
+		}else{
+			$this->error (L('do_empty'));
+		}
+	}
+
+	function deletepic(){
+		$name ='Slide_data';
+		$model = M ( $name );
+		$pk = $model->getPk ();
+		$id = $_REQUEST [$pk];
+		if (isset ( $id )) {
+			if(false!==$model->delete($id)){
+				delattach(array('moduleid'=>'230','id'=>$id));
+				$this->success(L('delete_ok'));
+			}else{
+				$this->error(L('delete_error').': '.$model->getDbError());
+			}
+		}else{
+			$this->error (L('do_empty'));
+		}
+	}
+}
+?>

+ 194 - 0
Ainaphp/Lib/Action/Admin/TemplateAction.class.php

@@ -0,0 +1,194 @@
+<?php
+/**
+ *
+ * Template(模板管理)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class TemplateAction extends AdminbaseAction
+{
+	protected $filepath,$publicpath;
+    function _initialize()
+    {
+		parent::_initialize();
+		$this->filepath = TMPL_PATH.'Home/'.$this->sysConfig['DEFAULT_THEME'].'/';
+		$this->publicpath = TMPL_PATH.'Home/'.$this->sysConfig['DEFAULT_THEME'].'/Public/';
+		$this->allpath = '';
+    }
+
+    public function index()
+    {
+		$exts = array('html','css','js');
+		$type=  $_GET['type'] ? $_GET['type'] : 'html';
+		if($type=='html'){
+			$path=$this->filepath;
+		}else{
+			$path=$this->allpath.$type.'/';
+		}
+
+		$files = dir_list($path,$type);
+
+		foreach ($files as $key=>$file){
+			$filename = basename($file);
+			$templates[$key]['value'] =  substr($filename,0,strrpos($filename, '.'));
+			$templates[$key]['filename'] = $filename;
+			$templates[$key]['filepath'] = $file;
+			$templates[$key]['filesize']=byte_format(filesize($file));
+			$templates[$key]['filemtime']=filemtime($file);
+			$templates[$key]['ext'] = strtolower(substr($filename,strrpos($filename, '.')-strlen($filename)));
+		}
+
+		$this->assign ( 'templates',$templates );
+        $this->display ();
+    }
+
+	public function images(){
+		$path = $this->publicpath.'images/'.$_GET['folder'];
+
+
+		$this->assign ( 'Public',$this->publicpath);
+
+		$uppath = explode('/',$_GET['folder']);
+		$leve = count($uppath)-1;;unset($uppath[$leve]);
+		if($leve>1){
+			unset($uppath[$leve-1]);
+			$uppath = implode('/',$uppath).'/';
+		}else{
+			$uppath = '';
+		}
+
+		$this->assign ( 'leve',$leve);
+		$this->assign ( 'uppath',$uppath);
+
+		if($_GET['delete']){
+			$file=$path.$_GET['filename'];
+			if(file_exists($file)){
+				is_dir($file) ? dir_delete($file) : unlink($file);
+				$this->success(L('delete_ok'));
+			}else{
+				$this->error(L('file_no_find'));
+			}
+		}
+
+		$files = glob($path.'*');
+		$folders=array();
+		foreach($files as $key => $file) {
+			$filename = basename($file);
+			if(is_dir($file)){
+				$folders[$key]['filename'] = $filename;
+				$folders[$key]['filepath'] = $file;
+				$folders[$key]['ext'] = 'folder';
+			}else{
+				$templates[$key]['filename'] = $filename;
+				$templates[$key]['filepath'] = $file;
+				$templates[$key]['ext'] = strtolower(substr($filename,strrpos($filename, '.')-strlen($filename)+1));
+				if(!in_array($templates[$key]['ext'],array('gif','jpg','png','bmp'))) $templates[$key]['ico'] =1;
+			}
+		}
+		$this->assign ( 'path',$path);
+		$this->assign ( 'folders',$folders );
+		$this->assign ( 'files',$templates );
+		$this->display ();
+
+	}
+	public function _before_add()
+    {
+		if (!is_writable($this->filepath)) $this->error(L('file_no_find'));
+	}
+
+ 	public function edit(){
+		$exts = array('html','css','js');
+
+		$filename = $_REQUEST['file'];
+		if($_POST['type']){
+			$type = $_POST['type'];
+		}else{
+			$type = strtolower(substr($filename,strrpos($filename, '.')-strlen($filename)+1));
+		}
+		$path = $type=='html' ?  $this->filepath : $this->allpath.$type.'/';
+ 		$file = $path.$filename;
+		if($_REQUEST['dosubmit']){
+
+			if(C('TOKEN_ON') && !M()->autoCheckToken($_POST))$this->error (L('_TOKEN_ERROR_'));
+
+			if($_POST['type']){
+ 				$file = $path.$filename.'.'.$type;
+				file_put_contents($file,htmlspecialchars_decode(stripslashes($_POST['content'])));
+				$this->assign('jumpUrl',U($module_name.'/index?type='.$type));
+				$this->success(L('add_ok'));
+			}else{
+				if(file_exists($file)){
+					file_put_contents($file,htmlspecialchars_decode(stripslashes($_POST['content'])));
+					$this->success(L('edit_ok'));
+				}else{
+					$this->error(L('file_no_find'));
+				}
+			}
+		}else{
+			if(file_exists($file)){
+				$content = htmlspecialchars(file_get_contents($file));
+				$this->assign ( 'filename',$filename );
+				$this->assign ( 'file',$file );
+				$this->display ();
+				echo '<textarea id="contentbox" style="display:none;" >'.$content.'</textarea><script>$("#content").val($("#contentbox").val());</script>';
+			}else{
+				$this->error(L('file_no_find'));
+			}
+		}
+	}
+
+	public function delete(){
+
+		$exts = array('html','css','js');
+		$filename = $_REQUEST['file'];
+		$type = strtolower(substr($filename,strrpos($filename, '.')-strlen($filename)+1));
+		$path = $type=='html' ? $path=$this->filepath : $this->publicpath.$type.'/';
+ 		$file = $path.$filename;
+
+		if(file_exists($file)){
+			unlink($file);
+            $this->assign('jumpUrl',U($module_name.'/index?type='.$type));
+			$this->success(L('delete_ok'));
+		}else{
+            $this->assign('jumpUrl',U($module_name.'/index?type='.$type));
+			$this->error(L('file_no_find'));
+		}
+	}
+	public function config(){
+
+		$lang= APP_LANG ? LANG_NAME : $this->sysConfig['DEFAULT_LANG'];
+		if($_GET['isajax']){
+			if(empty($_POST['value'])){ echo '0';exit;}
+
+			$data = F('config_'.$lang, $value='', $this->filepath);
+			$data[$_POST['key']]=$_POST['value'];
+			$r = F('config_'.$lang, $data, $this->filepath);
+			echo $r ? 1 : 0;
+			exit;
+		}
+		if($_POST['dosubmit']){
+			$file=  $_REQUEST['file'];
+			unset($_POST[C('TOKEN_NAME')]);
+			unset($_POST['dosubmit']);
+				// strtoupper
+			foreach($_POST as $key=>$r){
+				if($r)$data[strtolower($key)]=$r;
+			}
+			$r = F('config_'.$lang, $data, $this->filepath);
+			if($r){
+				$this->success(L('do_ok'));
+			}else{
+				$this->error(L('add_error'));
+			 }
+
+		}else{
+			$data = F('config_'.$lang, $value='', $this->filepath);
+			$this->assign ( 'list', $data );
+		}
+
+
+
+		$this->display ();
+	}
+}
+?>

+ 52 - 0
Ainaphp/Lib/Action/Admin/ThemeAction.class.php

@@ -0,0 +1,52 @@
+<?php
+/**
+ *
+ * Theme(风格选择)
+ *
+ */
+ if(!defined("Ainaphp")) exit("Access Denied");
+class ThemeAction extends AdminbaseAction
+{
+	 protected $filepath,$publicpath;
+    function _initialize()
+    {
+		parent::_initialize();
+		$this->filepath = TMPL_PATH.'Home/'.$this->sysConfig['DEFAULT_THEME'].'/';
+		$this->publicpath = TMPL_PATH.'Home/'.$this->sysConfig['DEFAULT_THEME'].'/Public/';
+		$this->tplpath = TMPL_PATH.'Home/';
+    }
+
+    public function index()
+    {
+		$filed = glob($this->tplpath.'*');
+		foreach ($filed as $key=>$v) {
+			$arr[$key]['name'] =  basename($v);
+			if(is_file($this->tplpath.$arr[$key]['name'].'/preview.jpg')){
+				$arr[$key]['preview']=$this->tplpath.$arr[$key]['name'].'/preview.jpg';
+			}else{
+				$arr[$key]['preview']=__ROOT__.'/Public/Images/nopic.jpg';
+			}
+			if($this->sysConfig['DEFAULT_THEME']==$arr[$key]['name']) $arr[$key]['use']=1;
+		}
+
+		$this->assign ( 'themes',$arr );
+        $this->display ();
+    }
+	public function chose()
+	{
+		$theme = $_GET['theme'];
+		if($theme){
+			$Model = M('Config');
+			$r = $Model->where("varname='DEFAULT_THEME'")->setField('value',$theme);
+			savecache('Config');
+			$this->success(L('do_ok'));
+		}else{
+			$this->error(L('do_empty'));
+		}
+	}
+	public function upload()
+	{
+		$this->display ();
+	}
+}
+?>

+ 133 - 0
Ainaphp/Lib/Action/Admin/TypeAction.class.php

@@ -0,0 +1,133 @@
+<?php
+/**
+ *
+ * Type (类别管理)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class TypeAction extends AdminbaseAction {
+
+	protected $dao,$Type;
+    function _initialize()
+    {
+		parent::_initialize();
+		$this->dao = M(MODULE_NAME);
+		$this->Type=F('Type');
+
+    }
+
+	public function _before_index()
+    {
+		if($_REQUEST ['parentid']){
+			$_REQUEST['where'] = "parentid=".intval($_REQUEST ['parentid']);
+		}else{
+			$_REQUEST['where'] = "parentid=0";
+		}
+	}
+
+	public function _before_add()
+    {
+
+		$parentid =	intval($_GET['parentid']);
+		$keyid = intval($_GET['keyid']);
+		$this->assign('keyid', $keyid);
+		$array=array();
+		if($parentid){
+			foreach((array)$this->Type as $key => $r) {
+				if($r['keyid']!=$keyid || empty($r['status'])) continue;
+				$r['id']=$r['typeid'];
+				$array[] = $r;
+			}
+			import ( '@.ORG.Tree' );
+			$str  = "<option value='\$typeid' \$selected>\$spacer \$name</option>";
+			$tree = new Tree ($array);
+			$select_type = $tree->get_tree(0, $str,$parentid);
+			$this->assign('select_type', $select_type);
+		}
+	}
+
+	public function _before_edit()
+    {
+		$typeid = intval($_GET['typeid']);
+		$parentid =	$this->Type[$typeid]['parentid'];
+		$keyid = intval($_GET['keyid']);
+		$this->assign('keyid', $keyid);
+		$array=array();
+		if($parentid){
+			foreach((array)$this->Type as $key => $r) {
+				if($r['keyid']!=$keyid) continue;
+				$r['id']=$r['typeid'];
+				$array[] = $r;
+			}
+			import ( '@.ORG.Tree' );
+			$str  = "<option value='\$typeid' \$selected>\$spacer \$name</option>";
+			$tree = new Tree ($array);
+			$tree->nbsp='&nbsp;&nbsp;';
+			$select_type = $tree->get_tree(0, $str,$parentid);
+			$this->assign('select_type', $select_type);
+		}
+	}
+
+	public function insert()
+    {
+		$_POST['status']=1;
+		$name = MODULE_NAME;
+		$model = D ($name);
+		if (false === $model->create ()) {
+			$this->error ( $model->getError () );
+		}
+
+		$typeid = $model->add() ;
+		if ($typeid) {
+			if(empty($_POST['keyid'])){
+				$data['typeid'] = $data['keyid'] = $typeid;
+				$model->save($data);
+			}
+			savecache($name);
+			$this->assign ( 'jumpUrl', U(MODULE_NAME.'/index') );
+			$this->success (L('add_ok'));
+		} else {
+			$this->error (L('add_error').': '.$model->getDbError());
+		}
+	}
+
+	public function get_child($linkageid) {
+		$where = array('parentid'=>$linkageid);
+		$this->childnode[] = intval($linkageid);
+		$result = $this->db->select($where);
+		if($result) {
+			foreach($result as $r) {
+				$this->_get_childnode($r['linkageid']);
+			}
+		}
+	}
+
+
+
+	public function get_arrparentids($pid, $array=array(),$arrparentid='') {
+		if(!is_array($array) || !isset($array[$pid])) return $pid;
+		$parentid = $array[$pid]['parentid'];
+		$arrparentid = $arrparentid ? $parentid.','.$arrparentid : $parentid;
+		if($parentid) {
+			$arrparentid = $this->get_arrparentids($parentid,$array, $arrparentid);
+		}else{
+			$data = array();
+			$data['bid'] = $pid;
+			$data['arrparentid'] = $arrparentid;
+		}
+		return $data;
+	}
+
+	public function get_arrchildid($id, $array=array()) {
+		$arrchildid = $id;
+
+		foreach($array as $catid => $cat) {
+			if($cat['parentid'] && $id != $catid) {
+				$arrparentids = explode(',', $cat['arrparentid']);
+				if(in_array($id, $arrparentids)) $arrchildid .= ','.$catid;
+			}
+		}
+		return $arrchildid;
+	}
+}
+?>

+ 17 - 0
Ainaphp/Lib/Action/Admin/UrlruleAction.class.php

@@ -0,0 +1,17 @@
+<?php
+/**
+ *
+ * Urlrule(URL规则)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class UrlruleAction extends AdminbaseAction {
+
+	protected $dao;
+    function _initialize()
+    {
+		parent::_initialize();
+		$this->dao = D('Admin/urlrule');
+    }
+}
+?>

+ 126 - 0
Ainaphp/Lib/Action/Admin/UserAction.class.php

@@ -0,0 +1,126 @@
+<?php
+/**
+ *
+ * User(会员管理文件)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class UserAction extends AdminbaseAction {
+
+    public $dao,$usergroup;
+	function _initialize()
+	{
+		parent::_initialize();
+		$this->dao = D('User');
+		$this->usergroup=F('Role');
+		$this->assign('usergroup',$this->usergroup);
+	}
+
+
+	function index(){
+		import ( '@.ORG.Page' );
+
+		$keyword=$_GET['keyword'];
+		$searchtype=$_GET['searchtype'];
+		$groupid =intval($_GET['groupid']);
+
+		$this->assign($_GET);
+
+		if(!empty($keyword) && !empty($searchtype)){
+			$where[$searchtype]=array('like','%'.$keyword.'%');
+		}
+		if($groupid)$where['groupid']=$groupid;
+
+		$user=$this->dao;
+		$count=$user->where($where)->count();
+		$page=new Page($count,20);
+		$show=$page->show();
+		$this->assign("page",$show);
+		$list=$user->order('id')->where($where)
+		->limit($page->firstRow.','.$page->listRows)->select();
+
+		$this->assign('ulist',$list);
+		$this->display();
+	}
+
+	function insert(){
+		$user=$this->dao;
+		$_POST['password'] = sysmd5($_POST['pwd']);
+		if($data=$user->create()){
+			if(false!==$user->add()){
+				$uid=$user->getLastInsID();
+				$ru['role_id']=$_POST['groupid'];
+				$ru['user_id']=$uid;
+				$roleuser=M('RoleUser');
+				$roleuser->add($ru);
+				$this->success(L('add_ok'));
+			}else{
+				$this->error(L('add_error'));
+			}
+		}else{
+			$this->error($user->getError());
+		}
+	}
+
+	function update(){
+		$user=$this->dao;
+		$_POST['password'] = $_POST['pwd'] ? sysmd5($_POST['pwd']) : $_POST['opwd'];
+		if(!empty($_POST['id'])){
+				if(false!==$user->save($_POST)){
+					$ru['user_id']=$_POST['id'];
+					$ru['role_id']=$_POST['groupid'];
+					$roleuser=M('RoleUser');
+					$roleuser->where('user_id='.$_POST['id'])->delete();
+					$roleuser->where('user_id='.$_POST['id'])->add($ru);
+					$this->success(L('edit_ok'));
+				}else{
+					$this->error(L('edit_error').$user->getDbError());
+				}
+		}else{
+				$this->error(L('do_error'));
+		}
+
+	}
+
+
+	function _before_add(){
+		$this->assign('rlist',$this->usergroup);
+	}
+
+	function _before_edit(){
+		$this->assign('rlist',$this->usergroup);
+	}
+
+
+	function delete(){
+		$id=$_GET['id'];
+		$user=$this->dao;
+		if(false!==$user->delete($id)){
+			$roleuser=M('RoleUser');
+			$roleuser->where('user_id ='.$id)->delete();
+			delattach(array('moduleid'=>0,'catid'=>0,'id'=>0,'userid'=>$id));
+			$this->success(L('delete_ok'));
+		}else{
+			$this->error(L('delete_error').$user->getDbError());
+		}
+	}
+
+	function deleteall(){
+		$ids=$_POST['ids'];
+		if(!empty($ids) && is_array($ids)){
+			$user=$this->dao;
+			$id=implode(',',$ids);
+			if(false!==$user->delete($id)){
+				$roleuser=M('RoleUser');
+				$roleuser->where('user_id in('.$id.')')->delete();
+				delattach("moduleid=0 and catid=0 and id=0 and userid in($id)");
+				$this->success(L('delete_ok'));
+			}else{
+				$this->error(L('delete_error'));
+			}
+		}else{
+			$this->error(L('do_empty'));
+		}
+	}
+}
+?>

+ 803 - 0
Ainaphp/Lib/Action/AdminbaseAction.class.php

@@ -0,0 +1,803 @@
+<?php
+/**
+ *
+ * Adminbase (后台公共模块)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class AdminbaseAction extends Action
+{
+	protected   $mod,$Config,$sysConfig,$nav,$menudata,$cache_model,$categorys,$module,$moduleid,$Type,$Urlrule,$Lang;
+	function _initialize()
+	{
+
+		$this->sysConfig = F('sys.config');
+		$this->menudata = F('Menu');
+		$this->module = F('Module');
+		$this->Type =F('Type');
+		$this->Urlrule =F('Urlrule');
+		$this->mod = F('Mod');
+
+
+		if(APP_LANG){
+			$this->Lang = F('Lang');
+			if($_GET['l']){
+				if($this->Lang[$_GET['l']]['id']){
+					$_SESSION['YP_lang'] = $_GET['l'];
+					$_SESSION['YP_langid'] = $this->Lang[$_GET['l']]['id'];
+				}else{
+					$this->error ( L ( 'NO_LANG' ) );
+				}
+			}elseif(!$_SESSION['YP_lang'] || !$_SESSION['YP_langid']){
+				$_SESSION['YP_lang'] = $this->sysConfig['DEFAULT_LANG'];
+				$_SESSION['YP_langid'] = $this->Lang[$this->sysConfig['DEFAULT_LANG']]['id'];
+			}
+			define('LANG_NAME',$_SESSION['YP_lang']);
+			define('LANG_ID',$_SESSION['YP_langid']);
+
+			$this->assign('l',LANG_NAME);
+			$this->assign('langid',LANG_ID);
+			$this->categorys = F('Category_'.LANG_NAME);
+			$this->Config = F('Config_'.LANG_NAME);
+			$this->assign('Lang',$this->Lang);
+		}else{
+			$this->Config = F('Config');
+			$this->categorys = F('Category');
+		}
+
+		$this->assign('module_name',MODULE_NAME);
+		$this->assign('action_name',ACTION_NAME);
+		$this->cache_model=array('Lang','Menu','Config','Module','Role','Category','Posid','Field','Type','Urlrule','Dbsource');
+
+		C('HOME_ISHTML',$this->sysConfig['HOME_ISHTML']);
+		C('PAGE_LISTROWS',$this->sysConfig['PAGE_LISTROWS']);
+		C('URL_LANG',$this->sysConfig['DEFAULT_LANG']);
+		C('URL_M',$this->sysConfig['URL_MODEL']);
+		C('URL_M_PATHINFO_DEPR',$this->sysConfig['URL_PATHINFO_DEPR']);
+		C('URL_M_HTML_SUFFIX',$this->sysConfig['URL_HTML_SUFFIX']);
+		C('URL_URLRULE',$this->sysConfig['URL_URLRULE']);
+
+
+		C('ADMIN_ACCESS',$this->sysConfig['ADMIN_ACCESS']);
+		// 用户权限检查
+		if (C ( 'USER_AUTH_ON' ) && !in_array(MODULE_NAME,explode(',',C('NOT_AUTH_MODULE')))) {
+			import ( '@.ORG.RBAC' );
+			if (! RBAC::AccessDecision ('Admin')) {
+				//检查认证识别号
+
+				if (! $_SESSION [C ( 'USER_AUTH_KEY' )]) {
+					//跳转到认证网关
+					redirect ( PHP_FILE . C ( 'USER_AUTH_GATEWAY' ) );
+				}
+				// 没有权限 抛出错误
+				if (C ( 'RBAC_ERROR_PAGE' )) {
+					// 定义权限错误页面
+					redirect ( C ( 'RBAC_ERROR_PAGE' ) );
+				} else {
+					if (C ( 'GUEST_AUTH_ON' )) {
+						$this->assign ( 'jumpUrl', PHP_FILE . C ( 'USER_AUTH_GATEWAY' ) );
+					}
+					// 提示错误信息
+					$this->error ( L ( '_VALID_ACCESS_' ) );
+				}
+			}
+		}
+
+	 	$menuid = intval($_GET['menuid']);
+		if(empty($menuid)) $menuid = cookie('menuid');
+		if(!empty($menuid)){
+			$this->nav = $this->getnav($menuid,1);
+			if($this->nav)$this->assign('nav', $this->nav);
+		}
+
+		if($this->mod[MODULE_NAME]){
+			$this->moduleid = $this->mod[MODULE_NAME];
+			$this->m = $this->module[$this->moduleid];
+			$this->assign('moduleid',$this->moduleid);
+			$this->Type = F('Type');
+			$this->assign('Type',$this->Type);
+
+			if($this->module[$this->moduleid]['type']==1 && ACTION_NAME=='index'){
+
+				if($this->categorys){
+					foreach ($this->categorys as $r){
+
+						if($_SESSION['groupid']!=1 && !in_array($_SESSION['groupid'],explode(',',$r['postgroup']))) continue;
+						if($r['moduleid'] != $this->moduleid || $r['child']){
+							$arr= explode(",",$r['arrchildid']);
+							$show=0;
+							foreach((array)$arr as $rr){
+								if($this->categorys[$rr]['moduleid'] ==$this->moduleid) $show=1;
+							}
+							if(empty($show))continue;
+							$r['disabled'] =  $r['child'] ? ' disabled' : '';
+						}else{
+							$r['disabled'] = '';
+						}
+						$array[] = $r;
+					}
+					import ( '@.ORG.Tree' );
+					$str  = "<option value='\$id' \$disabled \$selected>\$spacer \$catname</option>";
+					$tree = new Tree ($array);
+					$select_categorys = $tree->get_tree(0, $str);
+					$this->assign('select_categorys', $select_categorys);
+					$this->assign('categorys', $this->categorys);
+				}
+
+
+				$this->assign('posids', F('Posid'));
+			}
+		}
+		import("@.ORG.Form");
+		$this->assign('Form', new Form());
+	}
+
+	function getnav($menuid,$isnav=0){
+
+			if($menuid){
+				$bnav = $this->menudata[$menuid];
+				if(empty($bnav['action']))$bnav['action'] ='index';
+				$array = array('menuid'=> $bnav['id']);
+				parse_str($bnav['data'],$c);
+				$bnav['data'] = $c + $array;
+			}
+
+			if($this->menudata){
+				$accessList = $_SESSION['_ACCESS_LIST'];
+				foreach($this->menudata as $key=>$module) {
+					if($module['parentid'] != $menuid || $module['status']==0) continue;
+					if(isset($accessList[strtoupper('Admin')][strtoupper($module['model'])]) || $_SESSION[C('ADMIN_AUTH_KEY')]) {
+						//设置模块访问权限$module['access'] =   1;
+						if(empty($module['action'])) $module['action']='index';
+						//检测动作权限
+						if(isset($accessList[strtoupper('Admin')][strtoupper($module['model'])][strtoupper($module['action'])]) || $_SESSION[C('ADMIN_AUTH_KEY')]){
+							$nav[$key]  = $module;
+							if($isnav){
+								$array=array('menuid'=> $nav[$key]['parentid']);
+								cookie('menuid',$nav[$key]['parentid']);
+								//$_SESSION['menuid'] = $nav[$key]['parentid'];
+							}else{
+								 $array=array('menuid'=> $nav[$key]['id']);
+							}
+							if(empty($menuid) && empty($isnav)) $array=array();
+							$c=array();
+							parse_str($nav[$key]['data'],$c);
+							$nav[$key]['data'] = $c + $array;
+						}
+					}
+				}
+			}
+			$navdata['bnav']=$bnav;
+			$navdata['nav']=$nav;
+			return $navdata;
+	}
+
+	function _list($modelname, $map = '', $sortBy = '', $asc = false ,$listRows = 15) {
+		$model = M($modelname);
+		$id=$model->getPk ();
+		$this->assign ( 'pkid', $id );
+
+		if (isset ( $_REQUEST ['order'] )) {
+			$order = $_REQUEST ['order'];
+		} else {
+			$order = ! empty ( $sortBy ) ? $sortBy : $id;
+		}
+		if (isset ( $_REQUEST ['sort'])) {
+			$_REQUEST ['sort']=='asc' ? $sort = 'asc' : $sort = 'desc';
+		} else {
+			$sort = $asc ? 'asc' : 'desc';
+		}
+
+
+		$_REQUEST ['sort'] = $sort;
+		$_REQUEST ['order'] = $order;
+
+		$keyword=$_REQUEST['keyword'];
+		$searchtype=$_REQUEST['searchtype'];
+		$groupid =intval($_REQUEST['groupid']);
+		$catid =intval($_REQUEST['catid']);
+		$posid =intval($_REQUEST['posid']);
+		$typeid =intval($_REQUEST['typeid']);
+
+		if(APP_LANG)if($this->moduleid)$map['lang']=array('eq',LANG_ID);
+
+
+		if(!empty($keyword) && !empty($searchtype)){
+			$map[$searchtype]=array('like','%'.$keyword.'%');
+		}
+		if($groupid)$map['groupid']=$groupid;
+		if($catid)$map['catid']=$catid;
+		if($posid)$map['posid']=$posid;
+		if($typeid) $map['typeid']=$typeid;
+
+		$tables = $model->getDbFields();
+
+
+		foreach($_REQUEST['map'] as $key=>$res){
+				if(  ($res==='0' || $res>0) || !empty($res) ){
+					if($_REQUEST['maptype'][$key]){
+						$map[$key]=array($_REQUEST['maptype'][$key],$res);
+					}else{
+						$map[$key]=intval($res);
+					}
+					$_REQUEST[$key]=$res;
+				}else{
+					unset($_REQUEST[$key]);
+				}
+		}
+
+
+		$this->assign($_REQUEST);
+
+		//取得满足条件的记录总数
+		$count = $model->where ( $map )->count ( $id );//echo $model->getLastsql();
+
+		if ($count > 0) {
+			import ( "@.ORG.Page" );
+			//创建分页对象
+			if (! empty ( $_REQUEST ['listRows'] )) {
+				$listRows = $_REQUEST ['listRows'];
+			}
+			$page = new Page ( $count, $listRows );
+			//分页查询数据
+
+			$field=$this->module[$this->moduleid]['listfields'];
+			$field= (empty($field) || $field=='*') ? '*' : 'id,catid,url,posid,title,thumb,title_style,userid,username,hits,createtime,updatetime,status,listorder' ;
+			$voList = $model->field($field)->where($map)->order( "`" . $order . "` " . $sort)->limit($page->firstRow . ',' . $page->listRows)->select ( );
+			//分页跳转的时候保证查询条件
+			foreach ( $map as $key => $val ) {
+				if (! is_array ( $val )) {
+					$page->parameter .= "$key=" . urlencode ( $val ) . "&";
+				}
+			}
+
+			$map[C('VAR_PAGE')]='{$page}';
+			unset($map['lang']);
+			$map['lang']=LANG_ID;
+			$map['listRows']=$listRows;
+			$page->urlrule = U($modelname.'/index', $map);
+			//分页显示
+			$page = $page->show ();
+			//列表排序显示
+			$sortImg = $sort; //排序图标
+			$sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
+			$sort = $sort == 'desc' ? 1 : 0; //排序方式
+			//模板赋值显示
+			$this->assign ( 'list', $voList );
+			$this->assign ( 'page', $page );
+		}
+		return;
+	}
+
+
+	/**
+     * 添加
+     *
+     */
+
+	function add() {
+		$name = MODULE_NAME;
+		$this->display ('edit');
+	}
+
+
+	function insert() {
+
+		if($_POST['setup']) $_POST['setup']=array2string($_POST['setup']);
+		$name = MODULE_NAME;
+		$model = D ($name);
+		if (false === $model->create ()) {
+			$this->error ( $model->getError () );
+		}
+		$id = $model->add();
+		if ($id !==false) {
+			if(in_array($name,$this->cache_model)) savecache($name);
+			if($_POST['aid']){
+				$Attachment =M('Attachment');
+				$aids =  implode(',',$_POST['aid']);
+				$data['id']= $id;
+				$data['catid']= intval($_POST['catid']);
+				$data['status']= '1';
+				$Attachment->where("aid in (".$aids.")")->save($data);
+			}
+			if($_POST['isajax'])$this->assign('dialog','1');
+			$jumpUrl = $_POST['forward'] ? $_POST['forward'] : U(MODULE_NAME.'/index');
+			$this->assign ( 'jumpUrl',$jumpUrl );
+			$this->success (L('add_ok'));
+		} else {
+			$this->error (L('add_error').': '.$model->getDbError());
+		}
+	}
+
+	/**
+     * 更新
+     *
+     */
+
+	function edit() {
+		$name = MODULE_NAME;
+		$model = M ( $name );
+		$pk=ucfirst($model->getPk ());
+		$id = intval($_REQUEST [$model->getPk ()]);
+		if(empty($id))   $this->error(L('do_empty'));
+		$do='getBy'.$pk;
+		$vo = $model->$do ( $id );
+		if($vo['setup']) $vo['setup']=string2array($vo['setup']);
+		$this->assign ( 'vo', $vo );
+		$this->display ();
+	}
+
+	function update() {
+		if($_POST['setup']) $_POST['setup']=array2string($_POST['setup']);
+		$name = MODULE_NAME;
+		$model = D ( $name );
+		if (false === $model->create ()) {
+			$this->error ( $model->getError () );
+		}
+		if (false !== $model->save ()) {
+			if(in_array($name,$this->cache_model)) savecache($name);
+			if($_POST['aid']){
+				$Attachment =M('Attachment');
+				$aids =  implode(',',$_POST['aid']);
+				$data['id']= $_POST['id'];
+				$data['catid']= intval($_POST['catid']);
+				$data['status']= '1';
+				$Attachment->where("aid in (".$aids.")")->save($data);
+			}
+			if($_POST['isajax'])$this->assign('dialog','1');
+			$jumpUrl = $_POST['forward'] ? $_POST['forward'] : U(MODULE_NAME.'/index');
+			$this->assign ( 'jumpUrl', $jumpUrl);
+			$this->success (L('edit_ok'));
+		} else {
+			$this->success (L('edit_error').': '.$model->getDbError());
+		}
+	}
+
+	/**
+     * 删除
+     *
+     */
+	function delete(){
+		$name = MODULE_NAME;
+		$model = M ( $name );
+		$pk = $model->getPk ();
+		$id = $_REQUEST [$pk];
+		if (isset ( $id )) {
+			if(false!==$model->delete($id)){
+				if(in_array($name,$this->cache_model)) savecache($name);
+				if($this->moduleid){
+					$fields =  $model->getDbFields();
+					delattach(array('moduleid'=>$this->moduleid,'id'=>$id));
+					if($fields['keywords']){
+						$olddata  = $model->field('keywords')->find($id);
+						$where['name']=array('in',$olddata['keywords']);
+						$where['moduleid']=array('eq',$this->moduleid);
+						if(APP_LANG)$where['lang']=array('eq',LANG_ID);
+						M('Tags')->where($where)->setDec('num');
+						M('Tags_data')->where("id=".$id)->delete();
+					}
+				}
+				if($name=='Order')M('Order_data')->where('order_id='.$id)->delete();
+				$this->success(L('delete_ok'));
+			}else{
+				$this->error(L('delete_error').': '.$model->getDbError());
+			}
+		}else{
+			$this->error (L('do_empty'));
+		}
+	}
+
+	/**
+     * 批量删除
+     *
+     */
+
+	function deleteall(){
+
+		$name = MODULE_NAME;
+		$model = M ( $name );
+		$ids=$_POST['ids'];
+		if(!empty($ids) && is_array($ids)){
+			$id=implode(',',$ids);
+			if(false!==$model->delete($id)){
+				if(in_array($name,$this->cache_model)) savecache($name);
+				if($this->moduleid){
+					$fields =  $model->getDbFields();
+					delattach("moduleid=$this->moduleid and id in($id)");
+					if($fields['keywords']){
+						$olddata  = $model->field('keywords')->where("id in($id)")->select();
+						foreach((array)$olddata as $r){
+								$where['name']=array('in',$r['keywords']);
+								$where['moduleid']=array('eq',$this->moduleid);
+								if(APP_LANG)$where['lang']=array('eq',LANG_ID);
+								M('Tags')->where($where)->setDec('num');
+						}
+						M('Tags_data')->where("id in($id)")->delete();
+						M('Tags')->where('num<=0')->delete();
+					}
+				}
+				if($name=='Order')M('Order_data')->where('order_id in('.$id.')')->delete();
+				$this->success(L('delete_ok'));
+			}else{
+				$this->error(L('delete_error').': '.$model->getDbError());
+			}
+		}else{
+			$this->error(L('do_empty'));
+		}
+	}
+
+	/**
+     * 批量操作
+     *
+     */
+	public function listorder()
+	{
+		$name = MODULE_NAME;
+		$model = M ( $name );
+		$pk = $model->getPk ();
+		$ids = $_POST['listorders'];
+		foreach($ids as $key=>$r) {
+			$data['listorder']=$r;
+			$model->where($pk .'='.$key)->save($data);
+		}
+		if(in_array($name,$this->cache_model)) savecache($name);
+		$this->success (L('do_ok'));
+
+	}
+
+	/*状态*/
+
+	public function status(){
+		$name = MODULE_NAME;
+		$model = D ($name);
+		$_GET = get_safe_replace($_GET);
+		if($model->save($_GET)){
+			savecache(MODULE_NAME);
+			$this->success(L('do_ok'));
+		}else{
+			$this->error(L('do_error'));
+		}
+	}
+
+	/**
+     * 默认操作
+     *
+     */
+	public function index() {
+        $name = MODULE_NAME;
+		$model = M ($name);
+		$id=$model->getPk ();
+		$count = $model->where($_REQUEST['where'])->count();
+		import ( "@.ORG.Page" );
+		$p = new Page ( $count, 15 );
+		unset($_GET[C('VAR_PAGE')]);
+		$map=$_GET;
+		$map[C('VAR_PAGE')]='{$page}';
+		$p->urlrule = U($name.'/index',$map);
+		$page = $p->show ();
+
+        $list = $model->where($_REQUEST['where'])->order("$id desc")->limit($p->firstRow . ',' . $p->listRows)->select();
+        $this->assign('list', $list);
+		$this->assign ( 'page', $page );
+        $this->display();
+    }
+
+
+	public function create_show($id,$module)
+    {
+		C('DEFAULT_THEME_NAME',$this->sysConfig['DEFAULT_THEME']);
+		C('HTML_FILE_SUFFIX',$this->sysConfig['HTML_FILE_SUFFIX']);
+		C('TMPL_FILE_NAME',str_replace('Admin/Default','Home/'.$this->sysConfig['DEFAULT_THEME'],C('TMPL_FILE_NAME')));
+
+
+		if(APP_LANG){
+			C('TMPL_CACHFILE_SUFFIX','_'.LANG_NAME.'.php');
+			$lang =  C('URL_LANG')!=LANG_NAME ? $lang = LANG_NAME.'/' : '';
+			L(include LANG_PATH.LANG_NAME.'/common.php');
+			$T = F('config_'.LANG_NAME,'', './Ainaphp/Tpl/Home/'.$this->sysConfig['DEFAULT_THEME'].'/');
+		}else{
+			L(include LANG_PATH.$this->sysConfig['DEFAULT_LANG'].'/common.php');
+			$T = F('config_'.$this->sysConfig['DEFAULT_LANG'],'', './Ainaphp/Tpl/Home/'.$this->sysConfig['DEFAULT_THEME'].'/');
+		}
+		$this->assign('T',$T);
+		foreach((array)$this->module as $r){
+			if($r['issearch'])$search_module[$r['name']] = L($r['name']);
+		}
+		$this->assign('search_module',$search_module);
+		$this->assign ( 'form',new Form());
+		$p =1;
+		$id=intval($id);
+		if(empty($id)) $this->success (L('do_empty'));;
+		$this->assign($this->Config);
+		$this->assign('Categorys',$this->categorys);
+		$this->assign('Module',$this->module);
+		$this->assign('Type',$this->Type);
+		$this->assign('module_name',$module);
+		$dao= M($module);
+		$data = $dao->find($id);
+
+		$catid = $data['catid'];
+		$this->assign('catid',$catid);
+		$cat = $this->categorys[$data['catid']];
+		$this->assign ($cat);
+		$bcid = explode(",",$cat['arrparentid']);
+		$bcid = $bcid[1];
+		if($bcid == '') $bcid=intval($catid);
+		$this->assign('bcid',$bcid);
+
+		$seo_title = $data['title'].'-'.$cat['catname'];
+		$this->assign ('seo_title',$seo_title);
+		$this->assign ('seo_keywords',$data['keywords']);
+		$this->assign ('seo_description',$data['description']);
+
+		$fields = F($this->mod[$module].'_Field');
+		foreach($data as $key=>$c_d){
+			$setup='';
+			$fields[$key]['setup'] =$setup=string2array($fields[$key]['setup']);
+			if($setup['fieldtype']=='varchar' && $fields[$key]['type']!='text'){
+				$data[$key.'_old_val'] =$data[$key];
+				$data[$key]=fieldoption($fields[$key],$data[$key]);
+			}elseif($fields[$key]['type']=='images' || $fields[$key]['type']=='files'){
+				$p_data=explode(':::',$data[$key]);
+				$data[$key]=array();
+				foreach($p_data as $k=>$res){
+					$p_data_arr=explode('|',$res);
+					$data[$key][$k]['filepath'] = $p_data_arr[0];
+					$data[$key][$k]['filename'] = $p_data_arr[1];
+				}
+				unset($p_data);
+				unset($p_data_arr);
+			}
+			unset($setup);
+		}
+		$this->assign('fields',$fields);
+		$this->assign ('form',new Form());
+
+		$urlrule = geturl($cat,$data,$this->Urlrule);
+
+		if(!empty($data['template'])){
+			$template = $cat['module'].'_'.$data['template'];
+		}elseif(!empty($cat['template_show'])){
+			$template = $cat['module'].'_'.$cat['template_show'];
+		}else{
+			$template = $cat['module'].'_show';
+		}
+		//手动分页
+		$CONTENT_POS = strpos($data['content'], '[page]');
+		if($CONTENT_POS !== false){
+
+				$pageurls=array();
+				$contents = array_filter(explode('[page]',$data['content']));
+				$pagenumber = count($contents);
+				for($i=1; $i<=$pagenumber; $i++) {
+					$pageurls[$i] = str_replace('{$page}',$i,$urlrule);
+				}
+				//生成分页
+				foreach ($pageurls as $p=>$urls) {
+					$pages = content_pages($pagenumber,$p, $pageurls);
+					$this->assign ('pages',$pages);
+					$data['content'] = $contents[$p-1];
+					$this->assign ($data);
+					$url= ($p > 1 ) ? $urls[1] :  $urls[0];
+					if(strstr($url,C('HTML_FILE_SUFFIX'))){
+						$filename = basename($url,C('HTML_FILE_SUFFIX'));
+						$dir = dirname($url).'/';
+					}else{
+						$filename = 'index';
+						$dir= $url;
+					}
+					$dir = substr($dir,strlen(__ROOT__.'/'));
+					$this->buildHtml($filename,$dir,'./Ainaphp/Tpl/Home/'.$this->sysConfig['DEFAULT_THEME'].'/'.$template.C('TMPL_TEMPLATE_SUFFIX'));
+				}
+		}else{
+				$url = str_replace('{$page}', $p, $urlrule[0]);
+				if(strstr($url,C('HTML_FILE_SUFFIX'))){
+					$filename = basename($url,C('HTML_FILE_SUFFIX'));
+					$dir = dirname($url).'/';
+				}else{
+					$filename = 'index';
+					$dir= $url;
+				}
+				$this->assign ('pages','');
+				$this->assign ($data);
+				$dir = substr($dir,strlen(__ROOT__.'/'));
+				$this->buildHtml($filename,$dir,'./Ainaphp/Tpl/Home/'.$this->sysConfig['DEFAULT_THEME'].'/'.$template.C('TMPL_TEMPLATE_SUFFIX'));
+		}
+
+		return true;
+    }
+
+	public function create_list($catid,$p=1,$count=0)
+    {
+		C('DEFAULT_THEME_NAME',$this->sysConfig['DEFAULT_THEME']);
+		C('HTML_FILE_SUFFIX',$this->sysConfig['HTML_FILE_SUFFIX']);
+		C('TMPL_FILE_NAME',str_replace('Admin/Default','Home/'.$this->sysConfig['DEFAULT_THEME'],C('TMPL_FILE_NAME')));
+
+		if(APP_LANG){
+			C('TMPL_CACHFILE_SUFFIX','_'.LANG_NAME.'.php');
+			$lang =  C('URL_LANG')!=LANG_NAME ? $lang = LANG_NAME.'/' : '';
+			L(include LANG_PATH.LANG_NAME.'/common.php');
+			$T = F('config_'.LANG_NAME,'', './Ainaphp/Tpl/Home/'.$this->sysConfig['DEFAULT_THEME'].'/');
+		}else{
+			L(include LANG_PATH.$this->sysConfig['DEFAULT_LANG'].'/common.php');
+			$T = F('config_'.$this->sysConfig['DEFAULT_LANG'],'', './Ainaphp/Tpl/Home/'.$this->sysConfig['DEFAULT_THEME'].'/');
+		}
+		$this->assign('T',$T);
+		foreach((array)$this->module as $r){
+			if($r['issearch'])$search_module[$r['name']] = L($r['name']);
+		}
+		$this->assign('search_module',$search_module);
+		$this->assign ( 'form',new Form());
+
+		$this->assign($this->Config);
+		$this->assign('Categorys',$this->categorys);
+		$this->assign('Module',$this->module);
+		$this->assign('Type',$this->Type);
+		$catid =intval($catid);
+		if(empty($catid)) $this->success (L('do_empty'));
+
+		$cat = $this->categorys[$catid];
+		$this->assign('catid',$catid);
+		if($cat['type']) return;
+		if(empty($cat['ishtml'])) return;
+		unset($cat['id']);
+		$this->assign($cat);
+		$cat['id']=$catid;
+		$bcid = explode(",",$cat['arrparentid']);
+		$bcid = $bcid[1];
+		if($bcid == '') $bcid=intval($catid);
+		$this->assign('bcid',$bcid);
+
+		$urlrule = geturl($cat,'',$this->Urlrule);
+		$url= ($p > 1 ) ? $urlrule[1] :  $urlrule[0];
+		$url = str_replace('{$page}', $p, $url);
+		if(strstr($url,C('HTML_FILE_SUFFIX'))){
+			$filename = basename($url,C('HTML_FILE_SUFFIX'));
+			$dir = dirname($url).'/';
+		}else{
+			$filename = 'index';
+			$dir= $url;
+		}
+		$dir = substr($dir,strlen(__ROOT__.'/'));
+		if(empty($module))$module=$cat['module'];
+		$this->assign('module_name',$module);
+
+
+		$this->assign ( 'fields', F($cat['moduleid'].'_Field') );
+		$this->assign ( 'form',new Form());
+
+
+		if($cat['moduleid']==1){
+			$cat['listtype']=2;
+			$module = $cat['module'];
+			$dao= M($module);
+			$data = $dao->find($catid);
+			$seo_title = $cat['title'] ? $cat['title'] : $data['title'];
+			$this->assign ('seo_title',$seo_title);
+			$this->assign ('seo_keywords',$data['keywords']);
+			$this->assign ('seo_description',$data['description']);
+
+			$template = $cat['template_list']? $cat['template_list'] : 'index';
+			//手动分页
+			$CONTENT_POS = strpos($data['content'], '[page]');
+
+			if($CONTENT_POS !== false){
+
+					$contents = array_filter(explode('[page]',$data['content']));
+					$pagenumber = count($contents);
+					for($i=1; $i<=$pagenumber; $i++) {
+						$pageurls[$i] = str_replace('{$page}',$i,$urlrule);
+					}
+					//生成分页
+					foreach ($pageurls as $p=>$urls) {
+						$pages = content_pages($pagenumber,$p, $pageurls);
+						$this->assign ('pages',$pages);
+						$data['content'] = $contents[$p-1];
+						$this->assign ($data);
+						if($p > 1)$filename = basename($pageurls[$p]['1'],C('HTML_FILE_SUFFIX'));
+						//$this->buildHtml($filename,$dir,'Home/'.$template);
+						$r=$this->buildHtml($filename,$dir,'./Ainaphp/Tpl/Home/'.$this->sysConfig['DEFAULT_THEME'].'/Page_'.$template.C('TMPL_TEMPLATE_SUFFIX'));
+					}
+			}else{
+					$this->assign($data);
+					//$r=$this->buildHtml($filename,$dir,'Home/'.$template);
+					$r=$this->buildHtml($filename,$dir,'./Ainaphp/Tpl/Home/'.$this->sysConfig['DEFAULT_THEME'].'/Page_'.$template.C('TMPL_TEMPLATE_SUFFIX'));
+			}
+
+		}else{
+
+			$seo_title = $cat['title'] ? $cat['title'] : $cat['catname'];
+			$this->assign ('seo_title',$seo_title);
+			$this->assign ('seo_keywords',$cat['keywords']);
+			$this->assign ('seo_description',$cat['description']);
+
+			if($cat['listtype']==1){
+				$template_r = 'index';
+			}else{
+				$where = " status=1 ";
+				if($cat['child']){
+					$where .= " and catid in(".$cat['arrchildid'].")";
+				}else{
+					$where .=  " and catid=".$catid;
+				}
+
+				$module = $cat['module'];
+				$dao= M($module);
+				if(empty($count))$count = $dao->where($where)->count();
+				if($count){
+					import ( "@.ORG.Page" );
+					$listRows =  !empty($cat['pagesize']) ? $cat['pagesize'] : C('PAGE_LISTROWS');
+					$page = new Page ( $count, $listRows ,$p );
+					$page->urlrule = $urlrule;
+					$pages = $page->show();
+					$field =  $this->module[$this->mod[$module]]['listfields'];
+					$field =  $field ? $field : 'id,catid,userid,url,username,title,title_style,keywords,description,thumb,createtime,hits';
+
+					$list = $dao->field($field)->where($where)->order('id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
+					$this->assign('pages',$pages);
+					$this->assign('list',$list);
+				}
+				$template_r = 'list';
+			}
+
+			$template = $cat['template_list']? $cat['template_list'] : $template_r;
+			$r=$this->buildHtml($filename,$dir,'./Ainaphp/Tpl/Home/'.$this->sysConfig['DEFAULT_THEME'].'/'.$cat['module'].'_'.$template.C('TMPL_TEMPLATE_SUFFIX'));
+
+		}
+		if($r) return true;
+	}
+
+	public function create_index($sitemap)
+    {
+		C('HTML_FILE_SUFFIX',$this->sysConfig['HTML_FILE_SUFFIX']);
+		C('DEFAULT_THEME_NAME',$this->sysConfig['DEFAULT_THEME']);
+		C('TMPL_FILE_NAME',str_replace('Admin/Default','Home/'.$this->sysConfig['DEFAULT_THEME'],C('TMPL_FILE_NAME')));
+
+
+		if(APP_LANG){
+			C('TMPL_CACHFILE_SUFFIX','_'.LANG_NAME.'.php');
+			$lang =  C('URL_LANG')!=LANG_NAME ? $lang = LANG_NAME.'/' : '';
+			L(include LANG_PATH.LANG_NAME.'/common.php');
+			$T = F('config_'.LANG_NAME,'', './Ainaphp/Tpl/Home/'.$this->sysConfig['DEFAULT_THEME'].'/');
+		}else{
+			L(include LANG_PATH.$this->sysConfig['DEFAULT_LANG'].'/common.php');
+			$T = F('config_'.$this->sysConfig['DEFAULT_LANG'],'', './Ainaphp/Tpl/Home/'.$this->sysConfig['DEFAULT_THEME'].'/');
+		}
+		$this->assign('T',$T);
+		foreach((array)$this->module as $r){
+			if($r['issearch'])$search_module[$r['name']] = L($r['name']);
+		}
+		$this->assign('search_module',$search_module);
+
+
+		$this->assign ( 'form',new Form());
+		$this->assign('Module',$this->module);
+		$this->assign('Type',$this->Type);
+		$this->assign($this->Config);
+		$this->assign('Categorys',$this->categorys);
+ 		//$r=$this->buildHtml('index','./','Home/Index_index');
+		if(empty($sitemap)){
+			$this->assign('ishome','home');
+			if(!$this->sysConfig['HOME_ISHTML']) $this->error(L('NO_HOME_ISHTML'));
+			$this->assign('bcid',0);
+			$r=$this->buildHtml('index','./'.$lang,'./Ainaphp/Tpl/Home/'.$this->sysConfig['DEFAULT_THEME'].'/Index_index'.C('TMPL_TEMPLATE_SUFFIX'));
+		}else{
+			$this->assign('sitemap','1');
+			$r=$this->buildHtml('sitemap','./'.$lang,'./Ainaphp/Tpl/Home/'.$this->sysConfig['DEFAULT_THEME'].'/Sitemap'.C('TMPL_TEMPLATE_SUFFIX'));
+		}
+		if($r) return true;
+    }
+
+	function clisthtml($id){
+			$pagesize= 10;
+			$p = max(intval($p), 1);
+			$j = 1;
+			do {
+				$this->create_list($id,$p);
+				$j++;
+				$p++;
+				$pages = isset($pages) ? $pages : PAGESTOTAL;
+			} while ($j <= $pages && $j < $pagesize);
+	}
+}
+?>

+ 418 - 0
Ainaphp/Lib/Action/BaseAction.class.php

@@ -0,0 +1,418 @@
+<?php
+/**
+ *
+ * Base (前台公共模块)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class BaseAction extends Action
+{
+	protected   $Config ,$sysConfig,$categorys,$module,$moduleid,$mod,$dao,$Type,$Role,$_userid,$_groupid,$_email,$_username ,$forward ,$user_menu,$Lang,$member_config;
+    public function _initialize() {
+
+			$this->sysConfig = F('sys.config');
+			$this->module = F('Module');
+			$this->Role = F('Role');
+			$this->Type =F('Type');
+			$this->mod= F('Mod');
+			$this->moduleid=$this->mod[MODULE_NAME];
+			if(APP_LANG){
+				$this->Lang = F('Lang');
+				$this->assign('Lang',$this->Lang);
+				if(get_safe_replace($_GET['l'])){
+					if(!$this->Lang[$_GET['l']]['status'])$this->error ( L ( 'NO_LANG' ) );
+					$lang=$_GET['l'];
+				}else{
+					$lang=$this->sysConfig['DEFAULT_LANG'];
+				}
+				define('LANG_NAME', $lang);
+				define('LANG_ID', $this->Lang[$lang]['id']);
+				$this->categorys = F('Category_'.$lang);
+				$this->Config = F('Config_'.$lang);
+				$this->assign('l',$lang);
+				$this->assign('langid',LANG_ID);
+				$T = F('config_'.$lang,'', APP_PATH.'Tpl/Home/'.$this->sysConfig['DEFAULT_THEME'].'/');
+				C('TMPL_CACHFILE_SUFFIX','_'.$lang.'.php');
+				cookie('think_language',$lang);
+			}else{
+				$T = F('config_'.$this->sysConfig['DEFAULT_LANG'],'',  APP_PATH.'Tpl/Home/'.$this->sysConfig['DEFAULT_THEME'].'/');
+				$this->categorys = F('Category');
+				$this->Config = F('Config');
+				cookie('think_language',$this->sysConfig['DEFAULT_LANG']);
+			}
+			$this->assign('T',$T);
+			$this->assign($this->Config);
+			$this->assign('Role',$this->Role);
+			$this->assign('Type',$this->Type);
+			$this->assign('Module',$this->module);
+			$this->assign('Categorys',$this->categorys);
+			import("@.ORG.Form");
+			$this->assign ( 'form',new Form());
+
+			C('HOME_ISHTML',$this->sysConfig['HOME_ISHTML']);
+			C('PAGE_LISTROWS',$this->sysConfig['PAGE_LISTROWS']);
+			C('URL_M',$this->sysConfig['URL_MODEL']);
+			C('URL_M_PATHINFO_DEPR',$this->sysConfig['URL_PATHINFO_DEPR']);
+			C('URL_M_HTML_SUFFIX',$this->sysConfig['URL_HTML_SUFFIX']);
+			C('URL_LANG',$this->sysConfig['DEFAULT_LANG']);
+			C('DEFAULT_THEME_NAME',$this->sysConfig['DEFAULT_THEME']);
+
+
+			import("@.ORG.Online");
+			$session = new Online();
+			if(cookie('auth')){
+				$yourphp_auth_key = sysmd5($this->sysConfig['ADMIN_ACCESS'].$_SERVER['HTTP_USER_AGENT']);
+				list($userid,$groupid, $password) = explode("-", authcode(cookie('auth'), 'DECODE', $yourphp_auth_key));
+				$this->_userid = $userid;
+				$this->_username =  cookie('username');
+				$this->_groupid = $groupid;
+				$this->_email =  cookie('email');
+			}else{
+				$this->_groupid = cookie('groupid') ?  cookie('groupid') : 4;
+				$this->_userid =0;
+			}
+
+
+			foreach((array)$this->module as $r){
+				if($r['issearch'])$search_module[$r['name']] = L($r['name']);
+				if($r['ispost'] && (in_array($this->_groupid,explode(',',$r['postgroup']))))$this->user_menu[$r['id']]=$r;
+			}
+			if(GROUP_NAME=='User'){
+				$langext = $lang ? '_'.$lang : '';
+				$this->member_config=F('member.config'.$langext);
+				$this->assign('member_config',$this->member_config);
+				$this->assign('user_menu',$this->user_menu);
+				if($this->_groupid=='5' &&  MODULE_NAME!='Login'){
+					$this->assign('jumpUrl',URL('User-Login/emailcheck'));
+					$this->assign('waitSecond',3);
+					$this->success(L('no_regcheckemail'));
+					exit;
+				}
+				$this->assign('header',TMPL_PATH.'Home/'.THEME_NAME.'/Home_header.html');
+			}
+			if($_GET['forward'] || $_POST['forward']){
+				$this->forward = get_safe_replace($_GET['forward'].$_POST['forward']);
+			}else{
+				if(MODULE_NAME!='Register' || MODULE_NAME!='Login' )
+				$this->forward =isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] :  $this->Config['site_url'];
+			}
+			$this->assign('forward',$this->forward);
+
+			$this->assign('search_module',$search_module);
+			$this->assign('module_name',MODULE_NAME);
+			$this->assign('group_name',GROUP_NAME);
+			$this->assign('action_name',ACTION_NAME);
+
+	}
+
+    public function index($catid='',$module='')
+    {
+		$this->Urlrule =F('Urlrule');
+		if(empty($catid)) $catid =  intval($_REQUEST['id']);
+		$p= max(intval($_REQUEST[C('VAR_PAGE')]),1);
+		if($catid){
+			$cat = $this->categorys[$catid];
+			$bcid = explode(",",$cat['arrparentid']);
+			$bcid = $bcid[1];
+			if($bcid == '') $bcid=intval($catid);
+			if(empty($module))$module=$cat['module'];
+			$this->assign('module_name',$module);
+			unset($cat['id']);
+			$this->assign($cat);
+			$cat['id']=$catid;
+			$this->assign('catid',$catid);
+			$this->assign('bcid',$bcid);
+		}
+		if($cat['readgroup'] && $this->_groupid!=1 && !in_array($this->_groupid,explode(',',$cat['readgroup']))){$this->assign('jumpUrl',URL('User-Login/index'));$this->error (L('NO_READ'));}
+		$fields = F($this->mod[$module].'_Field');
+		foreach($fields as $key=>$r){
+			$fields[$key]['setup'] =string2array($fields[$key]['setup']);
+		}
+		$this->assign ( 'fields', $fields);
+
+
+		$seo_title = $cat['title'] ? $cat['title'] : $cat['catname'];
+		$this->assign ('seo_title',$seo_title);
+		$this->assign ('seo_keywords',$cat['keywords']);
+		$this->assign ('seo_description',$cat['description']);
+
+
+		if($module=='Guestbook'){
+			$where['status']=array('eq',1);
+			$this->dao= M($module);
+			$count = $this->dao->where($where)->count();
+			if($count){
+				import ( "@.ORG.Page_home" );
+				$listRows =  !empty($cat['pagesize']) ? $cat['pagesize'] : C('PAGE_LISTROWS');
+				$page = new Page_home ( $count, $listRows );
+				$page->urlrule = geturl($cat,'');
+				$pages = $page->show();
+				$field =  $this->module[$cat['moduleid']]['listfields'];
+				$field =  $field ? $field : '*';
+				$list = $this->dao->field($field)->where($where)->order('listorder desc,id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
+				$this->assign('pages',$pages);
+				$this->assign('list',$list);
+			}
+			$template = $cat['module']=='Guestbook' && $cat['template_list'] ? $cat['template_list'] : 'index';
+			$this->display(THEME_PATH.$module.'_'.$template.'.html');
+		}elseif($module=='Page'){
+			$modle=M('Page');
+			$data = $modle->find($catid);
+			unset($data['id']);
+
+			//分页
+			$CONTENT_POS = strpos($data['content'], '[page]');
+			if($CONTENT_POS !== false) {
+				$urlrule = geturl($cat,'',$this->Urlrule);
+				$urlrule[0] =  urldecode($urlrule[0]);
+				$urlrule[1] =  urldecode($urlrule[1]);
+				$contents = array_filter(explode('[page]',$data['content']));
+				$pagenumber = count($contents);
+				for($i=1; $i<=$pagenumber; $i++) {
+					$pageurls[$i] = str_replace('{$page}',$i,$urlrule);
+				}
+				$pages = content_pages($pagenumber,$p, $pageurls);
+				//判断[page]出现的位置
+				if($CONTENT_POS<7) {
+					$data['content'] = $contents[$p];
+				} else {
+					$data['content'] = $contents[$p-1];
+				}
+				$this->assign ('pages',$pages);
+			}
+
+			$template = $cat['template_list'] ? $cat['template_list'] :  'index' ;
+			$this->assign ($data);
+			$this->display(THEME_PATH.$module.'_'.$template.'.html');
+
+		}else{
+
+			if($catid){
+				$seo_title = $cat['title'] ? $cat['title'] : $cat['catname'];
+				$this->assign ('seo_title',$seo_title);
+				$this->assign ('seo_keywords',$cat['keywords']);
+				$this->assign ('seo_description',$cat['description']);
+
+
+				$where = " status=1 ";
+				if($cat['child']){
+					$where .= " and catid in(".$cat['arrchildid'].")";
+				}else{
+					$where .=  " and catid=".$catid;
+				}
+				
+				
+				$chengshi = $_GET['chengshi'];
+				$app = $_GET['app'];
+				$wangzhan = $_GET['wangzhan'];
+				$xiaochengxu = $_GET['xiaochengxu'];
+				
+				if($module == "Aticle" && $chengshi){
+					$where .=" and chengshi = {$chengshi}";
+				}
+				if($module == "Aticle" && $app){
+					$where .=" and app = {$app}";
+				}
+				if($module == "Aticle" && $wangzhan){
+					$where .=" and wangzhan = {$wangzhan}";
+				}
+				if($module == "Aticle" && $xiaochengxu){
+					$where .=" and xiaochengxu = {$xiaochengxu}";
+				}
+					
+					
+				if(empty($cat['listtype'])){
+					$this->dao= M($module);
+					$count = $this->dao->where($where)->count();
+					if($count){
+						import ( "@.ORG.Page_home" );
+						$listRows =  !empty($cat['pagesize']) ? $cat['pagesize'] : C('PAGE_LISTROWS');
+						$page = new Page_home ( $count, $listRows );
+						$page->urlrule = geturl($cat,'',$this->Urlrule);
+						$pages = $page->show();
+						$field =  $this->module[$this->mod[$module]]['listfields'];
+						$field =  $field ? $field : 'id,catid,userid,url,username,title,title_style,keywords,description,thumb,createtime,hits';
+						$list = $this->dao->field($field)->where($where)->order('listorder desc,id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
+						$this->assign('pages',$pages);
+						$this->assign('list',$list);
+					}
+					$template_r = 'list';
+				}else{
+					$template_r = 'index';
+				}
+			}else{
+				$template_r = 'list';
+			}
+			$template = $cat['template_list'] ? $cat['template_list'] : $template_r;
+			$this->display($module.':'.$template);
+		}
+    }
+
+
+
+	public function show($id='',$module='')
+    {
+		$this->Urlrule =F('Urlrule');
+		$p= max(intval($_REQUEST[C('VAR_PAGE')]),1);
+		$id = $id ? $id : intval($_REQUEST['id']);
+		$module = $module ? $module : MODULE_NAME;
+		$this->assign('module_name',$module);
+		$this->dao= M($module);;
+		$data = $this->dao->find($id);
+
+
+		$catid = $data['catid'];
+		$cat = $this->categorys[$data['catid']];
+		if(empty($cat['ishtml']))$this->dao->where("id=".$id)->setInc('hits'); //添加点击次数
+		$bcid = explode(",",$cat['arrparentid']);
+		$bcid = $bcid[1];
+		if($bcid == '') $bcid=intval($catid);
+
+		if($data['readgroup']){
+			if($this->_groupid!=1 && !in_array($this->_groupid,explode(',',$data['readgroup'])) )$noread=1;
+		}elseif($cat['readgroup']){
+			if($this->_groupid!=1 && !in_array($this->_groupid,explode(',',$cat['readgroup'])) )$noread=1;
+		}
+		if($noread==1){$this->assign('jumpUrl',URL('User-Login/index'));$this->error (L('NO_READ'));}
+
+		$chargepoint = $data['readpoint'] ? $data['readpoint'] : $cat['chargepoint'];
+		if($chargepoint && $data['userid'] !=$this->_userid){
+			$user = M('User');
+			$userdata =$user->find($this->_userid);
+			if($cat['paytype']==1 && $userdata['point']>=$chargepoint){
+				$chargepointok = $user->where("id=".$this->_userid)->setDec('point',$chargepoint);
+			}elseif($cat['paytype']==2 && $userdata['amount']>=$chargepoint){
+				$chargepointok = $user->where("id=".$this->_userid)->setDec('amount',$chargepoint);
+			}else{
+				$this->error (L('NO_READ'));
+			}
+		}
+
+		$seo_title = $data['title'].'-'.$cat['catname'];
+		$this->assign ('seo_title',$seo_title);
+		$this->assign ('seo_keywords',$data['keywords']);
+		$this->assign ('seo_description',$data['description']);
+		$this->assign ( 'fields', F($cat['moduleid'].'_Field') );
+
+
+		$fields = F($this->mod[$module].'_Field');
+		foreach($data as $key=>$c_d){
+			$setup='';
+			$fields[$key]['setup'] =$setup=string2array($fields[$key]['setup']);
+			if($setup['fieldtype']=='varchar' && $fields[$key]['type']!='text'){
+				$data[$key.'_old_val'] =$data[$key];
+				$data[$key]=fieldoption($fields[$key],$data[$key]);
+			}elseif($fields[$key]['type']=='images' || $fields[$key]['type']=='files'){
+				if(!empty($data[$key])){
+					$p_data=explode(':::',$data[$key]);
+					$data[$key]=array();
+					foreach($p_data as $k=>$res){
+						$p_data_arr=explode('|',$res);
+						$data[$key][$k]['filepath'] = $p_data_arr[0];
+						$data[$key][$k]['filename'] = $p_data_arr[1];
+					}
+					unset($p_data);
+					unset($p_data_arr);
+				}
+			}
+			unset($setup);
+		}
+		$this->assign('fields',$fields);
+
+
+		//手动分页
+		$CONTENT_POS = strpos($data['content'], '[page]');
+		if($CONTENT_POS !== false) {
+
+			$urlrule = geturl($cat,$data,$this->Urlrule);
+			$urlrule =  str_replace('%7B%24page%7D','{$page}',$urlrule);
+			$contents = array_filter(explode('[page]',$data['content']));
+			$pagenumber = count($contents);
+			for($i=1; $i<=$pagenumber; $i++) {
+				$pageurls[$i] = str_replace('{$page}',$i,$urlrule);
+			}
+			$pages = content_pages($pagenumber,$p, $pageurls);
+			//判断[page]出现的位置是否在文章开始
+			if($CONTENT_POS<7) {
+				$data['content'] = $contents[$p];
+			} else {
+				$data['content'] = $contents[$p-1];
+			}
+			$this->assign ('pages',$pages);
+		}
+
+		if(!empty($data['template'])){
+			$template = $data['template'];
+		}elseif(!empty($cat['template_show'])){
+			$template = $cat['template_show'];
+		}else{
+			$template =  'show';
+		}
+
+		$this->assign('catid',$catid);
+		$this->assign ($cat);
+		$this->assign('bcid',$bcid);
+
+		$this->assign ($data);
+
+		$this->display($module.':'.$template);
+    }
+
+	public function down()
+	{
+
+		$module = $module ? $module : MODULE_NAME;
+		$id = $id ? $id : intval($_REQUEST['id']);
+		$this->dao= M($module);
+		$filepath = $this->dao->where("id=".$id)->getField('file');
+		$this->dao->where("id=".$id)->setInc('downs');
+
+		if(strpos($filepath, ':/')) {
+			header("Location: $filepath");
+		} else {
+			$filepath = '.'.$filepath;
+			if(!$filename) $filename = basename($filepath);
+			$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
+			if(strpos($useragent, 'msie ') !== false) $filename = rawurlencode($filename);
+			$filetype = strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
+			$filesize = sprintf("%u", filesize($filepath));
+			if(ob_get_length() !== false) @ob_end_clean();
+			header('Pragma: public');
+			header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
+			header('Cache-Control: no-store, no-cache, must-revalidate');
+			header('Cache-Control: pre-check=0, post-check=0, max-age=0');
+			header('Content-Transfer-Encoding: binary');
+			header('Content-Encoding: none');
+			header('Content-type: '.$filetype);
+			header('Content-Disposition: attachment; filename="'.$filename.'"');
+			header('Content-length: '.$filesize);
+			readfile($filepath);
+		}
+		exit;
+	}
+
+	public function hits()
+	{
+		$module = $module ? $module : MODULE_NAME;
+		$id = $id ? $id : intval($_REQUEST['id']);
+		$this->dao= M($module);
+		$this->dao->where("id=".$id)->setInc('hits');
+
+		if($module=='Download'){
+			$r = $this->dao->find($id);
+			echo '$("#hits").html('.$r['hits'].');$("#downs").html('.$r['downs'].');';
+		}else{
+			$hits = $this->dao->where("id=".$id)->getField('hits');
+			echo '$("#hits").html('.$hits.');';
+		}
+		exit;
+	}
+	public function verify()
+    {
+		header('Content-type: image/jpeg');
+        $type	 =	 isset($_GET['type'])? get_safe_replace($_GET['type']):'jpeg';
+        import("@.ORG.Image");
+        Image::buildImageVerify(4,1,$type);
+    }
+}
+?>

+ 401 - 0
Ainaphp/Lib/Action/BaseAction1.class.php

@@ -0,0 +1,401 @@
+<?php
+/**
+ *
+ * Base (前台公共模块)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class BaseAction extends Action
+{
+	protected   $Config ,$sysConfig,$categorys,$module,$moduleid,$mod,$dao,$Type,$Role,$_userid,$_groupid,$_email,$_username ,$forward ,$user_menu,$Lang,$member_config;
+    public function _initialize() {
+
+			$this->sysConfig = F('sys.config');
+			$this->module = F('Module');
+			$this->Role = F('Role');
+			$this->Type =F('Type');
+			$this->mod= F('Mod');
+			$this->moduleid=$this->mod[MODULE_NAME];
+			if(APP_LANG){
+				$this->Lang = F('Lang');
+				$this->assign('Lang',$this->Lang);
+				if(get_safe_replace($_GET['l'])){
+					if(!$this->Lang[$_GET['l']]['status'])$this->error ( L ( 'NO_LANG' ) );
+					$lang=$_GET['l'];
+				}else{
+					$lang=$this->sysConfig['DEFAULT_LANG'];
+				}
+				define('LANG_NAME', $lang);
+				define('LANG_ID', $this->Lang[$lang]['id']);
+				$this->categorys = F('Category_'.$lang);
+				$this->Config = F('Config_'.$lang);
+				$this->assign('l',$lang);
+				$this->assign('langid',LANG_ID);
+				$T = F('config_'.$lang,'', APP_PATH.'Tpl/Home/'.$this->sysConfig['DEFAULT_THEME'].'/');
+				C('TMPL_CACHFILE_SUFFIX','_'.$lang.'.php');
+				cookie('think_language',$lang);
+			}else{
+				$T = F('config_'.$this->sysConfig['DEFAULT_LANG'],'',  APP_PATH.'Tpl/Home/'.$this->sysConfig['DEFAULT_THEME'].'/');
+				$this->categorys = F('Category');
+				$this->Config = F('Config');
+				cookie('think_language',$this->sysConfig['DEFAULT_LANG']);
+			}
+			$this->assign('T',$T);
+			$this->assign($this->Config);
+			$this->assign('Role',$this->Role);
+			$this->assign('Type',$this->Type);
+			$this->assign('Module',$this->module);
+			$this->assign('Categorys',$this->categorys);
+			import("@.ORG.Form");
+			$this->assign ( 'form',new Form());
+
+			C('HOME_ISHTML',$this->sysConfig['HOME_ISHTML']);
+			C('PAGE_LISTROWS',$this->sysConfig['PAGE_LISTROWS']);
+			C('URL_M',$this->sysConfig['URL_MODEL']);
+			C('URL_M_PATHINFO_DEPR',$this->sysConfig['URL_PATHINFO_DEPR']);
+			C('URL_M_HTML_SUFFIX',$this->sysConfig['URL_HTML_SUFFIX']);
+			C('URL_LANG',$this->sysConfig['DEFAULT_LANG']);
+			C('DEFAULT_THEME_NAME',$this->sysConfig['DEFAULT_THEME']);
+
+
+			import("@.ORG.Online");
+			$session = new Online();
+			if(cookie('auth')){
+				$yourphp_auth_key = sysmd5($this->sysConfig['ADMIN_ACCESS'].$_SERVER['HTTP_USER_AGENT']);
+				list($userid,$groupid, $password) = explode("-", authcode(cookie('auth'), 'DECODE', $yourphp_auth_key));
+				$this->_userid = $userid;
+				$this->_username =  cookie('username');
+				$this->_groupid = $groupid;
+				$this->_email =  cookie('email');
+			}else{
+				$this->_groupid = cookie('groupid') ?  cookie('groupid') : 4;
+				$this->_userid =0;
+			}
+
+
+			foreach((array)$this->module as $r){
+				if($r['issearch'])$search_module[$r['name']] = L($r['name']);
+				if($r['ispost'] && (in_array($this->_groupid,explode(',',$r['postgroup']))))$this->user_menu[$r['id']]=$r;
+			}
+			if(GROUP_NAME=='User'){
+				$langext = $lang ? '_'.$lang : '';
+				$this->member_config=F('member.config'.$langext);
+				$this->assign('member_config',$this->member_config);
+				$this->assign('user_menu',$this->user_menu);
+				if($this->_groupid=='5' &&  MODULE_NAME!='Login'){
+					$this->assign('jumpUrl',URL('User-Login/emailcheck'));
+					$this->assign('waitSecond',3);
+					$this->success(L('no_regcheckemail'));
+					exit;
+				}
+				$this->assign('header',TMPL_PATH.'Home/'.THEME_NAME.'/Home_header.html');
+			}
+			if($_GET['forward'] || $_POST['forward']){
+				$this->forward = get_safe_replace($_GET['forward'].$_POST['forward']);
+			}else{
+				if(MODULE_NAME!='Register' || MODULE_NAME!='Login' )
+				$this->forward =isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] :  $this->Config['site_url'];
+			}
+			$this->assign('forward',$this->forward);
+
+			$this->assign('search_module',$search_module);
+			$this->assign('module_name',MODULE_NAME);
+			$this->assign('group_name',GROUP_NAME);
+			$this->assign('action_name',ACTION_NAME);
+
+	}
+
+    public function index($catid='',$module='')
+    {
+		$this->Urlrule =F('Urlrule');
+		if(empty($catid)) $catid =  intval($_REQUEST['id']);
+		$p= max(intval($_REQUEST[C('VAR_PAGE')]),1);
+		if($catid){
+			$cat = $this->categorys[$catid];
+			$bcid = explode(",",$cat['arrparentid']);
+			$bcid = $bcid[1];
+			if($bcid == '') $bcid=intval($catid);
+			if(empty($module))$module=$cat['module'];
+			$this->assign('module_name',$module);
+			unset($cat['id']);
+			$this->assign($cat);
+			$cat['id']=$catid;
+			$this->assign('catid',$catid);
+			$this->assign('bcid',$bcid);
+		}
+		if($cat['readgroup'] && $this->_groupid!=1 && !in_array($this->_groupid,explode(',',$cat['readgroup']))){$this->assign('jumpUrl',URL('User-Login/index'));$this->error (L('NO_READ'));}
+		$fields = F($this->mod[$module].'_Field');
+		foreach($fields as $key=>$r){
+			$fields[$key]['setup'] =string2array($fields[$key]['setup']);
+		}
+		$this->assign ( 'fields', $fields);
+
+
+		$seo_title = $cat['title'] ? $cat['title'] : $cat['catname'];
+		$this->assign ('seo_title',$seo_title);
+		$this->assign ('seo_keywords',$cat['keywords']);
+		$this->assign ('seo_description',$cat['description']);
+
+
+		if($module=='Guestbook'){
+			$where['status']=array('eq',1);
+			$this->dao= M($module);
+			$count = $this->dao->where($where)->count();
+			if($count){
+				import ( "@.ORG.Page_home" );
+				$listRows =  !empty($cat['pagesize']) ? $cat['pagesize'] : C('PAGE_LISTROWS');
+				$page = new Page_home ( $count, $listRows );
+				$page->urlrule = geturl($cat,'');
+				$pages = $page->show();
+				$field =  $this->module[$cat['moduleid']]['listfields'];
+				$field =  $field ? $field : '*';
+				$list = $this->dao->field($field)->where($where)->order('listorder desc,id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
+				$this->assign('pages',$pages);
+				$this->assign('list',$list);
+			}
+			$template = $cat['module']=='Guestbook' && $cat['template_list'] ? $cat['template_list'] : 'index';
+			$this->display(THEME_PATH.$module.'_'.$template.'.html');
+		}elseif($module=='Page'){
+			$modle=M('Page');
+			$data = $modle->find($catid);
+			unset($data['id']);
+
+			//分页
+			$CONTENT_POS = strpos($data['content'], '[page]');
+			if($CONTENT_POS !== false) {
+				$urlrule = geturl($cat,'',$this->Urlrule);
+				$urlrule[0] =  urldecode($urlrule[0]);
+				$urlrule[1] =  urldecode($urlrule[1]);
+				$contents = array_filter(explode('[page]',$data['content']));
+				$pagenumber = count($contents);
+				for($i=1; $i<=$pagenumber; $i++) {
+					$pageurls[$i] = str_replace('{$page}',$i,$urlrule);
+				}
+				$pages = content_pages($pagenumber,$p, $pageurls);
+				//判断[page]出现的位置
+				if($CONTENT_POS<7) {
+					$data['content'] = $contents[$p];
+				} else {
+					$data['content'] = $contents[$p-1];
+				}
+				$this->assign ('pages',$pages);
+			}
+
+			$template = $cat['template_list'] ? $cat['template_list'] :  'index' ;
+			$this->assign ($data);
+			$this->display(THEME_PATH.$module.'_'.$template.'.html');
+
+		}else{
+
+			if($catid){
+				$seo_title = $cat['title'] ? $cat['title'] : $cat['catname'];
+				$this->assign ('seo_title',$seo_title);
+				$this->assign ('seo_keywords',$cat['keywords']);
+				$this->assign ('seo_description',$cat['description']);
+
+
+				$where = " status=1 ";
+				if($cat['child']){
+					$where .= " and catid in(".$cat['arrchildid'].")";
+				}else{
+					$where .=  " and catid=".$catid;
+				}
+				
+				
+				
+					
+				if(empty($cat['listtype'])){
+					$this->dao= M($module);
+					$count = $this->dao->where($where)->count();
+					if($count){
+						import ( "@.ORG.Page_home" );
+						$listRows =  !empty($cat['pagesize']) ? $cat['pagesize'] : C('PAGE_LISTROWS');
+						$page = new Page_home ( $count, $listRows );
+						$page->urlrule = geturl($cat,'',$this->Urlrule);
+						$pages = $page->show();
+						$field =  $this->module[$this->mod[$module]]['listfields'];
+						$field =  $field ? $field : 'id,catid,userid,url,username,title,title_style,keywords,description,thumb,createtime,hits';
+						$list = $this->dao->field($field)->where($where)->order('listorder desc,id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
+						$this->assign('pages',$pages);
+						$this->assign('list',$list);
+					}
+					$template_r = 'list';
+				}else{
+					$template_r = 'index';
+				}
+			}else{
+				$template_r = 'list';
+			}
+			$template = $cat['template_list'] ? $cat['template_list'] : $template_r;
+			$this->display($module.':'.$template);
+		}
+    }
+
+
+
+	public function show($id='',$module='')
+    {
+		$this->Urlrule =F('Urlrule');
+		$p= max(intval($_REQUEST[C('VAR_PAGE')]),1);
+		$id = $id ? $id : intval($_REQUEST['id']);
+		$module = $module ? $module : MODULE_NAME;
+		$this->assign('module_name',$module);
+		$this->dao= M($module);;
+		$data = $this->dao->find($id);
+
+
+		$catid = $data['catid'];
+		$cat = $this->categorys[$data['catid']];
+		if(empty($cat['ishtml']))$this->dao->where("id=".$id)->setInc('hits'); //添加点击次数
+		$bcid = explode(",",$cat['arrparentid']);
+		$bcid = $bcid[1];
+		if($bcid == '') $bcid=intval($catid);
+
+		if($data['readgroup']){
+			if($this->_groupid!=1 && !in_array($this->_groupid,explode(',',$data['readgroup'])) )$noread=1;
+		}elseif($cat['readgroup']){
+			if($this->_groupid!=1 && !in_array($this->_groupid,explode(',',$cat['readgroup'])) )$noread=1;
+		}
+		if($noread==1){$this->assign('jumpUrl',URL('User-Login/index'));$this->error (L('NO_READ'));}
+
+		$chargepoint = $data['readpoint'] ? $data['readpoint'] : $cat['chargepoint'];
+		if($chargepoint && $data['userid'] !=$this->_userid){
+			$user = M('User');
+			$userdata =$user->find($this->_userid);
+			if($cat['paytype']==1 && $userdata['point']>=$chargepoint){
+				$chargepointok = $user->where("id=".$this->_userid)->setDec('point',$chargepoint);
+			}elseif($cat['paytype']==2 && $userdata['amount']>=$chargepoint){
+				$chargepointok = $user->where("id=".$this->_userid)->setDec('amount',$chargepoint);
+			}else{
+				$this->error (L('NO_READ'));
+			}
+		}
+
+		$seo_title = $data['title'].'-'.$cat['catname'];
+		$this->assign ('seo_title',$seo_title);
+		$this->assign ('seo_keywords',$data['keywords']);
+		$this->assign ('seo_description',$data['description']);
+		$this->assign ( 'fields', F($cat['moduleid'].'_Field') );
+
+
+		$fields = F($this->mod[$module].'_Field');
+		foreach($data as $key=>$c_d){
+			$setup='';
+			$fields[$key]['setup'] =$setup=string2array($fields[$key]['setup']);
+			if($setup['fieldtype']=='varchar' && $fields[$key]['type']!='text'){
+				$data[$key.'_old_val'] =$data[$key];
+				$data[$key]=fieldoption($fields[$key],$data[$key]);
+			}elseif($fields[$key]['type']=='images' || $fields[$key]['type']=='files'){
+				if(!empty($data[$key])){
+					$p_data=explode(':::',$data[$key]);
+					$data[$key]=array();
+					foreach($p_data as $k=>$res){
+						$p_data_arr=explode('|',$res);
+						$data[$key][$k]['filepath'] = $p_data_arr[0];
+						$data[$key][$k]['filename'] = $p_data_arr[1];
+					}
+					unset($p_data);
+					unset($p_data_arr);
+				}
+			}
+			unset($setup);
+		}
+		$this->assign('fields',$fields);
+
+
+		//手动分页
+		$CONTENT_POS = strpos($data['content'], '[page]');
+		if($CONTENT_POS !== false) {
+
+			$urlrule = geturl($cat,$data,$this->Urlrule);
+			$urlrule =  str_replace('%7B%24page%7D','{$page}',$urlrule);
+			$contents = array_filter(explode('[page]',$data['content']));
+			$pagenumber = count($contents);
+			for($i=1; $i<=$pagenumber; $i++) {
+				$pageurls[$i] = str_replace('{$page}',$i,$urlrule);
+			}
+			$pages = content_pages($pagenumber,$p, $pageurls);
+			//判断[page]出现的位置是否在文章开始
+			if($CONTENT_POS<7) {
+				$data['content'] = $contents[$p];
+			} else {
+				$data['content'] = $contents[$p-1];
+			}
+			$this->assign ('pages',$pages);
+		}
+
+		if(!empty($data['template'])){
+			$template = $data['template'];
+		}elseif(!empty($cat['template_show'])){
+			$template = $cat['template_show'];
+		}else{
+			$template =  'show';
+		}
+
+		$this->assign('catid',$catid);
+		$this->assign ($cat);
+		$this->assign('bcid',$bcid);
+
+		$this->assign ($data);
+
+		$this->display($module.':'.$template);
+    }
+
+	public function down()
+	{
+
+		$module = $module ? $module : MODULE_NAME;
+		$id = $id ? $id : intval($_REQUEST['id']);
+		$this->dao= M($module);
+		$filepath = $this->dao->where("id=".$id)->getField('file');
+		$this->dao->where("id=".$id)->setInc('downs');
+
+		if(strpos($filepath, ':/')) {
+			header("Location: $filepath");
+		} else {
+			$filepath = '.'.$filepath;
+			if(!$filename) $filename = basename($filepath);
+			$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
+			if(strpos($useragent, 'msie ') !== false) $filename = rawurlencode($filename);
+			$filetype = strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
+			$filesize = sprintf("%u", filesize($filepath));
+			if(ob_get_length() !== false) @ob_end_clean();
+			header('Pragma: public');
+			header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
+			header('Cache-Control: no-store, no-cache, must-revalidate');
+			header('Cache-Control: pre-check=0, post-check=0, max-age=0');
+			header('Content-Transfer-Encoding: binary');
+			header('Content-Encoding: none');
+			header('Content-type: '.$filetype);
+			header('Content-Disposition: attachment; filename="'.$filename.'"');
+			header('Content-length: '.$filesize);
+			readfile($filepath);
+		}
+		exit;
+	}
+
+	public function hits()
+	{
+		$module = $module ? $module : MODULE_NAME;
+		$id = $id ? $id : intval($_REQUEST['id']);
+		$this->dao= M($module);
+		$this->dao->where("id=".$id)->setInc('hits');
+
+		if($module=='Download'){
+			$r = $this->dao->find($id);
+			echo '$("#hits").html('.$r['hits'].');$("#downs").html('.$r['downs'].');';
+		}else{
+			$hits = $this->dao->where("id=".$id)->getField('hits');
+			echo '$("#hits").html('.$hits.');';
+		}
+		exit;
+	}
+	public function verify()
+    {
+		header('Content-type: image/jpeg');
+        $type	 =	 isset($_GET['type'])? get_safe_replace($_GET['type']):'jpeg';
+        import("@.ORG.Image");
+        Image::buildImageVerify(4,1,$type);
+    }
+}
+?>

+ 149 - 0
Ainaphp/Lib/Action/Home/AjaxAction.class.php

@@ -0,0 +1,149 @@
+<?php
+/**
+ *
+ * AreaAction.class.php (ajax 获取地址)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class AjaxAction extends BaseAction
+{
+    public function index()
+    {
+	 exit;
+    }
+    public function area()
+    {
+		$module = M('Area');
+		$id = intval($_REQUEST['id']);
+		$level= intval($_REQUEST['level']);
+		$provinceid= intval($_REQUEST['provinceid']);
+		$cityid= intval($_REQUEST['cityid']);
+		$areaid= intval($_REQUEST['areaid']);
+
+
+		$province_str='<option value="0">请选择省份...</option>';
+		$city_str='<option value="0">请选择城市...</option>';
+		$area_str='<option value="0">请选择区域...</option>';
+		$str ='';
+
+		$r = $module->where("parentid=".$id)->select();
+		foreach($r as $key=>$pro){
+			$selected = ( $pro['id']==$provinceid) ? ' selected="selected" ' : '';
+			$str .='<option value="'.$pro['id'].'"'.$selected.'>'.$pro['name'].'</option>';
+		}
+		if($level==0){
+			$province_str .=$str;
+		}elseif($level==1){
+			$city_str .=$str;
+		}elseif($level==2){
+			$area_str .=$str;
+		}
+		$str='';
+		if($provinceid){
+
+			$rr = $module->where("parentid=".$provinceid)->select();
+			foreach($rr as $key=>$pro){
+				$selected = ($pro['id']==$cityid) ? ' selected="selected" ' : '';
+				$str .='<option value="'.$pro['id'].'"'.$selected.'>'.$pro['name'].'</option>';
+			}
+			$city_str .=$str;
+		}
+		$str='';
+		if($cityid){
+			$rrr = $module->where("parentid=".$cityid)->select();
+			foreach($rrr as $key=>$pro){
+				$selected = ($pro['id']==$areaid) ? ' selected="selected" ' : '';
+				$str .='<option value="'.$pro['id'].'"'.$selected.'>'.$pro['name'].'</option>';
+			}
+			$area_str .=$str;
+		}
+
+		$res=array();
+		$res['data']= $rs ? 1 : 0 ;
+		$res['province'] =$province_str;
+		$res['city'] =$city_str;
+		$res['area'] =$area_str;
+		echo json_encode($res); exit;
+	 exit;
+    }
+
+	public function address(){
+		$do=get_safe_replace($_REQUEST['do']);
+		$model = M('User_address');
+		$id = intval($_REQUEST['id']);
+
+		$provinceid= intval($_REQUEST['province']);
+		$cityid= intval($_REQUEST['city']);
+		$areaid= intval($_REQUEST['area']);
+
+		$userid = $_POST['userid'] = $this->_userid;
+		if($do=='save'){
+			$id= intval($_POST['id']);
+			$_POST['isdefault']=1;
+			if($userid){
+				$model->where("userid=".$userid)->save(array('isdefault'=>0));
+				if($id){
+					$r = $model->save($_POST);
+					if($model->getDbError())die(json_encode(array('id'=>0)));
+					$_POST['edit'] =1;
+				}else{
+					$where['province'] = array('eq',$provinceid);
+					$where['city'] = array('eq',$cityid);
+					$where['area'] = array('eq',$areaid);
+					$where['consignee'] = array('eq',$_POST['consignee']);
+					$where['address'] = array('eq',$_POST['address']);
+					$ir = $model->where($where)->find();
+					if($ir){
+						echo json_encode(array('error'=>'收货信息已经存在!'));exit;
+					}
+					$id=$model->add ($_POST);
+				}
+			}else{
+					$_POST['id']=1;
+					$data = serialize($_POST);
+					cookie('guest_address',$data,315360000);
+					$id=1;
+					$_POST['edit'] =1;
+			}
+			if($id){
+				$_POST['id'] =$id;
+				die(json_encode($_POST));
+			}else{
+				die(json_encode(array('id'=>0)));
+			}
+
+		}elseif($do=='get'){
+			if($userid){
+				$data=$model->find($id);
+			}else{
+				$data = unserialize( cookie('guest_address'));
+			}
+			if($data){
+				die(json_encode($data));
+			}else{
+				die(json_encode(array('id'=>0)));
+			}
+			exit;
+		}
+
+	}
+
+	public function shipping(){
+		$do=get_safe_replace($_REQUEST['do']);
+		$model = M('Shipping');
+		$id = intval($_REQUEST['id']);
+
+		if($do=='get'){
+			$data=$model->find($id);
+			if($data){
+				echo json_encode($data);
+			}else{
+				echo json_encode(array('id'=>0));
+			}
+			exit;
+		}
+
+	}
+
+}
+?>

+ 62 - 0
Ainaphp/Lib/Action/Home/EmptyAction.class.php

@@ -0,0 +1,62 @@
+<?php
+
+if(!defined("Ainaphp")) exit("Access Denied");
+class EmptyAction extends Action
+{
+	public function _empty()
+	{
+		//空操作 空模块
+		if(MODULE_NAME!='Urlrule'){
+			$Mod = F('Mod');
+			if(!$Mod[MODULE_NAME]){
+				throw_exception('404');
+			}
+		}
+
+		$a=ACTION_NAME;
+		$id =  intval($_REQUEST['id']);
+		$catid = intval($_REQUEST['catid']);
+		$moduleid =  intval($_REQUEST['moduleid']);
+		if(MODULE_NAME=='Urlrule'){
+			if(APP_LANG){
+				$l =get_safe_replace($_REQUEST['l']);
+				$lang= $l ? '_'.$l : '_'.C('DEFAULT_LANG');
+			}
+			$catdir =get_safe_replace($_REQUEST['catdir']);
+			if($catdir){
+				$Cat = F('Cat'.$lang);
+				$catid = $catid ? $catid : $Cat[$catdir];
+				unset($Cat);
+			}
+			if($_REQUEST['module']){
+				$m=get_safe_replace($_REQUEST['module']);
+			}elseif($moduleid){
+				$Module =F('Module');
+				$m=$Module[$moduleid]['module'];
+				unset($Module);
+			}elseif($catid){
+				$Category = F('Category'.$lang);
+				$m=$Category[$catid]['module'];
+				unset($Category);
+			}else{
+				throw_exception('404');
+			}
+			if($a=='index') $id=$catid;
+		}else{
+			if(empty($id)){
+				$Cat = F('Cat'.$lang);
+				$id = $Cat[$id];
+				unset($Cat);
+			}
+			$m=MODULE_NAME;
+		}
+		import('@.Action.Base');
+		$bae=new BaseAction();
+		if(!method_exists($bae,$a)){
+			throw_exception('404');
+		}
+		$bae->$a($id,$m);
+
+	}
+}
+?>

+ 64 - 0
Ainaphp/Lib/Action/Home/FormatAction.class.php

@@ -0,0 +1,64 @@
+<?php
+/**
+ *
+ * FormatAction.class.php (格式化输出)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class FormatAction extends BaseAction
+{
+
+	function _initialize()
+    {
+		parent::_initialize();
+		import("@.ORG.Cxml");
+    }
+
+    public function index()
+    {
+
+    }
+	public function rss()
+	{
+		$modle = M('Article');
+		$data = $modle->field('id,title,url,createtime,copyfrom,content')->where("status=1")->order('id desc')->limit('0,10')->select();
+
+
+		$arraya['title']['value']=$this->Config['site_name'];
+		$arraya['link']['value']=$this->Config['site_url'];
+		$arraya['description']['value']=$this->Config['seo_title'];
+		$arraya['generator']['value']='Ainaphp'.VERSION;
+		$arraya['lastBuildDate']['value']= gmdate('D, d M Y H:i:s \G\M\T',time()+ 3600 * 8);
+		$arraya['webMaster']['value']= $this->Config['site_email'];
+		$arraya['language']['value']= 'zh-cn';
+		foreach($data as $key=> $res){
+			//$arraya[$key]['NodeName']['attributes']=array('id'=>'3','class'=>'thue');
+			$arraya[$key]['NodeName']['value'] ='item';
+			$arraya[$key]['title']['value'] = $res['title'];
+			$arraya[$key]['link']['value'] = $this->Config['site_url'].$res['url'];
+			$arraya[$key]['description']['value'] = $res['content'];
+			$arraya[$key]['description']['ishtml']=1;
+			$arraya[$key]['pubDate']['value'] = gmdate('D, d M Y H:i:s \G\M\T',$res['createtime']+ 3600 * 8);
+			$arraya[$key]['author']['value'] = $res['copyfrom'] ?  $res['copyfrom'] : 'Ainaphp' ;
+		}
+
+		$array['channel'] =$arraya;
+		$Cxml = new Cxml();
+		$Cxml->root='rss';
+		$Cxml->root_attributes=array('version'=>'2.0');
+		$xmldata = $Cxml->Cxml($array);
+
+		echo $xmldata;
+	}
+
+	public function flashxml(){
+		$Cxml = new Cxml();
+		$Cxml->root='rss';
+		$Cxml->root_attributes=array('version'=>'2.0');
+		$Cxml->NodeName= 'item';
+		$xmldata = $Cxml->Cxml($array,'./rss.xml'); //生成xml
+
+	}
+
+}
+?>

+ 65 - 0
Ainaphp/Lib/Action/Home/IndexAction.class.php

@@ -0,0 +1,65 @@
+<?php
+/**
+ *
+ * IndexAction.class.php (前台首页)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class IndexAction extends BaseAction
+{
+    public function index()
+    {
+		$this->assign('bcid',0);//顶级栏目
+		$this->assign('ishome','home');
+        $this->display();
+    }
+
+	public function message(){
+		$mod = M("message");
+		$_POST = get_safe_replace($_POST);
+		if(false!==$mod->create()){
+			$mod->status = 1;
+			$mod->lang = 1;
+			$mod->createtime = time();
+			$mod->updatetime = time();
+			$mod->add();
+			$this->success("提交成功");
+
+		}else{
+			$this->error("提交失败");
+		}
+	}
+    
+	public function apply()
+	{
+	    session_start();
+		$this->stop_request();
+		$mod = M("try");
+		$_POST = get_safe_replace($_POST);
+		if (false !== $mod->create()) {
+			$mod->status = 1;
+			$mod->lang = 1;
+			$mod->createtime = time();
+			$mod->updatetime = time();
+			$mod->add();
+			$this->success("提交成功");
+		} else {
+			$this->error("提交失败");
+		}	
+	}
+    
+    	//防止恶意请求
+	public function stop_request(){
+		$allow_sep = '120';
+		if (isset($_SESSION["moban_apply"])){
+			if (time() - $_SESSION["moban_apply"] < $allow_sep){
+				$this->error('请不要反复提交~');
+			}else{
+				$_SESSION["moban_apply"] = time(); 
+			}
+		}
+		$_SESSION["moban_apply"] = time();
+	}
+    
+}
+?>

+ 105 - 0
Ainaphp/Lib/Action/Home/SearchAction.class.php

@@ -0,0 +1,105 @@
+<?php
+/**
+ *
+ * SearchAction.class.php (前台搜索功能)
+ *
+ */
+if(!defined("Ainaphp")) exit("Access Denied");
+class SearchAction extends BaseAction
+{
+
+	function _initialize()
+    {
+		parent::_initialize();
+    }
+
+    public function index()
+    {
+		//搜索
+		$_REQUEST['id'] = $catid =  intval($_REQUEST['id']);
+		$p= max(intval($_REQUEST[C('VAR_PAGE')]),1);
+		$_REQUEST['keyword'] = $keyword = get_safe_replace($_REQUEST['keyword']);
+		$_REQUEST['module'] = $module =  get_safe_replace($_REQUEST['module']);
+		$module =  $module ? $module  : 'Article' ;
+		$this->assign($_REQUEST);
+		$this->assign('bcid',0);
+		$where = " status=1 ";
+
+
+
+		if(APP_LANG){
+			$lang = LANG_NAME;
+			$langid= LANG_ID;
+			$where .=" and lang= $langid";
+			$this->assign('lang',$lang);
+			$this->assign('langid',$langid);
+		}
+
+		if($catid){
+			$cat = $this->categorys[$catid];
+			$bcid = explode(",",$cat['arrparentid']);
+			$bcid = $bcid[1];
+			if($bcid == '') $bcid=intval($catid);
+			if(empty($module))$module=$cat['module'];
+			unset($cat['id']);
+			$this->assign($cat);
+			$cat['id']=$catid;
+			$this->assign('catid',$catid);
+			$this->assign('bcid',$bcid);
+
+
+			if($cat['child']){
+				$where .= " and catid in(".$cat['arrchildid'].")";
+			}else{
+				$where .=  " and catid=".$catid;
+			}
+		}
+		$seo_title = $cat['title'] ? $cat['title'] : $cat['catname'];
+		$this->assign ('seo_title',$keyword.' '.$seo_title);
+		$this->assign ('seo_keywords',$keyword.$cat['keywords']);
+		$this->assign ('seo_description',$keyword.$cat['description']);
+
+
+
+		if($keyword){
+
+			if(strstr($keyword,'or')){
+				$keydo = ' or ';
+				$keyword_arr= explode('or',$keyword);
+			}elseif(strstr($keyword,' ')){
+				$keydo = ' AND ';
+				$keyword_arr= explode(' ',$keyword);
+			}
+
+			if(count($keyword_arr)>1){
+				foreach($keyword_arr as $key =>$keywordz){
+					$keyword_arr[$key] = ' title like "%'.trim($keywordz).'%" ';
+				}
+				$where .= ' AND ('.implode($keydo,$keyword_arr).')';
+			}else{
+				$where .= ' AND title like "%'.$keyword.'%" ';
+			}
+		}
+		$this->dao= M($module);
+		$count = $this->dao->where($where)->count();
+		$this->assign('count',$count);
+
+		if($count){
+			import ( "@.ORG.Page_home" );
+			$listRows =  !empty($cat['pagesize']) ? $cat['pagesize'] : C('PAGE_LISTROWS');
+			$page = new Page_home ( $count, $listRows );
+			$_REQUEST['p'] = '{$page}';
+			$page->urlrule =  URL('Home-Search/index',$_REQUEST);
+			$pages = $page->show();
+			$field =  $this->module[$cat['moduleid']]['listfields'];
+			$field =  $field ? $field : 'id,catid,userid,url,username,title,title_style,keywords,description,thumb,createtime,hits';
+			$list = $this->dao->field($field)->where($where)->order('id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
+			$this->assign('pages',$pages);
+			$this->assign('list',$list);
+		}
+
+		$this->display();
+
+    }
+}
+?>

+ 85 - 0
Ainaphp/Lib/Behavior/CheckLangBehavior.class.php

@@ -0,0 +1,85 @@
+<?php
+// +----------------------------------------------------------------------
+// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
+// +----------------------------------------------------------------------
+// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
+// +----------------------------------------------------------------------
+// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
+// +----------------------------------------------------------------------
+// | Author: liu21st <liu21st@gmail.com>
+// +----------------------------------------------------------------------
+// $Id: CheckLangBehavior.class.php 2721 2012-02-09 03:20:54Z liu21st $
+
+/**
+ +------------------------------------------------------------------------------
+ * 系统行为扩展 语言检测 并自动加载语言包
+ +------------------------------------------------------------------------------
+ */
+class CheckLangBehavior extends Behavior {
+    // 行为参数定义(默认值) 可在项目配置中覆盖
+    protected $options   =  array(
+            'LANG_SWITCH_ON'        => false,   // 默认关闭语言包功能
+            'LANG_AUTO_DETECT'      => true,   // 自动侦测语言 开启多语言功能后有效
+            'LANG_LIST' => 'zh-cn', // 允许切换的语言列表 用逗号分隔
+            'VAR_LANGUAGE'          => 'l',		// 默认语言切换变量
+        );
+
+    // 行为扩展的执行入口必须是run
+    public function run(&$params){
+        // 开启静态缓存
+        $this->checkLanguage();
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 语言检查
+     * 检查浏览器支持语言,并自动加载语言包
+     +----------------------------------------------------------
+     * @access private
+     +----------------------------------------------------------
+     * @return void
+     +----------------------------------------------------------
+     */
+    private function checkLanguage() {
+        // 不开启语言包功能,仅仅加载框架语言文件直接返回
+        if (!C('LANG_SWITCH_ON')){
+            return;
+        }
+
+        $langSet = C('DEFAULT_LANG');
+        // 启用了语言包功能
+        // 根据是否启用自动侦测设置获取语言选择
+        if (C('LANG_AUTO_DETECT')){
+            if(isset($_GET[C('VAR_LANGUAGE')])){
+                $langSet = $_GET[C('VAR_LANGUAGE')];// url中设置了语言变量
+                cookie('think_language',$langSet,3600);
+			}elseif(C('DEFAULT_LANG')){// liuxun add 默认语言
+                $langSet = C('DEFAULT_LANG');
+            }elseif(cookie('think_language')){// 获取上次用户的选择
+                $langSet = cookie('think_language');
+            }elseif(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){// 自动侦测浏览器语言
+                preg_match('/^([a-z\-]+)/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches);
+                $langSet = $matches[1];
+                cookie('think_language',$langSet,3600);
+            }
+            if(false === stripos(C('LANG_LIST'),$langSet)) { // 非法语言参数
+                $langSet = C('DEFAULT_LANG');
+            }
+        }
+        // 定义当前语言
+        define('LANG_SET',strtolower($langSet));
+        // 读取项目公共语言包
+        if (is_file(LANG_PATH.LANG_SET.'/common.php'))
+            L(include LANG_PATH.LANG_SET.'/common.php');
+        $group = '';
+        // 读取当前分组公共语言包
+        if (defined('GROUP_NAME')){
+            $group = GROUP_NAME.C('TMPL_FILE_DEPR');
+            if (is_file(LANG_PATH.LANG_SET.'/'.$group.'lang.php'))
+                L(include LANG_PATH.LANG_SET.'/'.$group.'lang.php');
+        }
+        // 读取当前模块语言包
+        if (is_file(LANG_PATH.LANG_SET.'/'.$group.strtolower(MODULE_NAME).'.php'))
+            L(include LANG_PATH.LANG_SET.'/'.$group.strtolower(MODULE_NAME).'.php');
+    }
+}

+ 21 - 0
Ainaphp/Lib/Model/Admin/AccessModel.class.php

@@ -0,0 +1,21 @@
+<?php
+class AccessModel extends RelationModel {
+	//权限
+	protected $_link = array(
+		"Role"=>array(
+			"mapping_type"=>BELONGS_TO,
+			"class_name"=>'Role',
+			"foreign_key"=>'role_id',
+			"mapping_name"=>'role',
+			"as_fields"=>'name',
+		),
+		"Node"=>array(
+			"mapping_type"=>BELONGS_TO,
+			"class_name"=>'Node',
+			"foreign_key"=>'node_id',
+			"mapping_name"=>'node',
+			"as_fields"=>'name:node_name,remark:node_remark',
+		),
+	);
+}
+?>

+ 10 - 0
Ainaphp/Lib/Model/Admin/CategoryModel.class.php

@@ -0,0 +1,10 @@
+<?php
+class CategoryModel extends Model {
+	/*
+	 * 表单验证
+	 */
+	protected  $_validate = array(
+		array('catname','require','{%catname_is_empty}',1,'regex',3),
+	);
+}
+?>

+ 20 - 0
Ainaphp/Lib/Model/Admin/FieldModel.class.php

@@ -0,0 +1,20 @@
+<?php
+class FieldModel extends  Model {
+	/*
+	 * 表单验证
+	 */
+	protected  $_validate = array(
+		array('type','require','{%field_empty_type}',1,'regex',1),
+		array('name','require','{%field_empty_name}',1,'regex',3),
+		array('field','require','{%field_empty_field}',1,'regex',1),
+	);
+
+	/*
+	 * 自动完成
+	 */
+	protected $_auto=array(
+		//array('setup','array2string',3,'function'),
+	);
+
+}
+?>

+ 12 - 0
Ainaphp/Lib/Model/Admin/MenuModel.class.php

@@ -0,0 +1,12 @@
+<?php
+class MenuModel extends Model {
+	/*
+	 * 表单验证
+	 */
+	protected  $_validate = array(
+		array('name','require','{%menu_user_is_empty}',1,'regex',3),
+		array('model','require','{%menu_model_is_empty}',1,'regex',3),
+	);
+
+}
+?>

+ 12 - 0
Ainaphp/Lib/Model/Admin/NodeModel.class.php

@@ -0,0 +1,12 @@
+<?php
+class NodeModel extends Model {
+	/*
+	 * 表单验证
+	 */
+	protected  $_validate = array(
+		array('name','require','{%node_name_empty}',1,'regex',3),
+		array('title','require','{%node_title_empty}',1,'regex',3),
+	);
+
+}
+?>

+ 11 - 0
Ainaphp/Lib/Model/Admin/RoleModel.class.php

@@ -0,0 +1,11 @@
+<?php
+class NodeModel extends Model {
+	/*
+	 * 表单验证
+	 */
+	protected  $_validate = array(
+		array('name','require','{%node_name_empty}',1,'regex',3)
+	);
+
+}
+?>

+ 50 - 0
Ainaphp/Lib/Model/Admin/UserModel.class.php

@@ -0,0 +1,50 @@
+<?php
+class UserModel extends Model {
+	/*
+	 * 表单验证
+	 */
+	protected  $_validate = array(
+		array('username','require','{%user_is_empty}',1,'regex',1),
+		array('username','','{%user_is_have}',1,'unique',1),
+		array('pwd','require','{%user_password_empty}',0,'regex',1),
+		array('email','require','{%email_is_empty}',1,'regex',3),
+		array('email','email','{%email_is_not}'),
+		array('email','checkEmail','{%email_is_have}',1,'callback',3),
+	);
+
+	/*
+	 * 字段映射
+	 */
+	protected $_map=array(
+		'pwd'=>'password',
+	);
+
+	/*
+	 * 自动完成
+	 */
+	protected $_auto=array(
+		array('password','sysmd5',1,'function'),
+		array('createtime','time',1,'function'),
+		array('updatetime','time',2,'function'),
+		array('reg_ip','get_client_ip',1,'function'),
+	);
+
+	function checkEmail(){
+		$user=M('User');
+		if(empty($_POST['id'])){
+			if($user->getByEmail($_POST['email'])){
+				return false;
+			}else{
+				return true;
+			}
+		}else{
+			//判断邮箱是否已经使用
+			if($user->where("id!={$_POST['id']} and email='{$_POST['email']}'")->find()){
+				return false;
+			}else{
+				return true;
+			}
+		}
+	}
+}
+?>

+ 154 - 0
Ainaphp/Lib/ORG/Cxml.class.php

@@ -0,0 +1,154 @@
+<?php
+
+class Cxml extends Think {
+
+	public $root='rss';
+	public $root_attributes=array();
+    public $charset='utf-8';
+	public $NodeName= 'item';
+	public $dom;
+
+    private function __constract() {
+    }
+
+    public function outHeader() {
+        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
+        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
+		header("Cache-Control: no-cache");
+        header("Pragma: no-cache");
+        header("Content-type: text/xml; charset=".$this->charset);
+    }
+
+    public function Cxml($data=null,$file='') {
+
+        if (!is_array($data) || count($data) == 0) return false;
+        $dom = new DOMDocument('1.0',$this->charset);
+
+        //添加DOM根元素
+        $resultElement = $dom->createElement($this->root);
+		//设置DOM根元素属性
+		$this->Attribute($this->root_attributes,$dom,$resultElement);
+        //将数组转换为xml添加到根元素
+        $this->Array2Xml($dom, $data, $resultElement);
+        //加入DOM对象
+        $dom->appendChild($resultElement);
+		if($file) {
+			//生成xml文件
+			$r = $dom->save($file);
+			return $r ;
+		}else{
+			//输出XML显示
+			$this->outHeader();
+			return $dom->saveXML();
+		}
+	}
+	public function Xml2Array($file=''){
+		if(!is_file($file)) return false;
+		//$dom = new DOMDocument('1.0',$this->charset);
+		//$array=$this->xml_to_array(simplexml_load_file($file));
+		$array=$this->simplexml2array(simplexml_load_file($file));
+		return $array;
+	}
+	public function Array2Xml($dom, $data, $result='') {
+        if (is_array($data)) {
+            foreach ($data as $key => $value) {
+                if (is_numeric($key)) {
+                    $NodeName = $value['NodeName']['value'];
+					if($value['NodeName']['attributes'])$value['attributes'] =  $value['NodeName']['attributes'];
+					unset($value['NodeName']);
+                } else {
+                    $NodeName = $key;
+                }
+                if (!isset($value['value'])) {
+                    $key_Element = $dom->createElement($NodeName);
+                    $result->appendChild($key_Element);
+					if($value['attributes']){
+						$this->Attribute($value['attributes'],$dom,$key_Element);
+						unset($value['attributes']);
+					}
+                    $this->Array2Xml($dom, $value, $key_Element);
+                } else {
+                	$key_Element = $dom->createElement($NodeName);
+
+					if($value['ishtml']){
+						$key_Element->appendChild($dom->createCDATASection($value['value']));
+					}else{
+						$key_Element->appendChild($dom->createTextNode($value['value']));
+					}
+					if($value['attributes']){
+						$this->Attribute($value['attributes'],$dom,$key_Element);
+					}
+                	$result->appendChild($key_Element);
+                }
+            }
+            return $result;
+        }
+	}
+	public function Attribute($att,$dom,$key_Element){
+		$attributes_element='';
+		foreach ($att as $key =>$rs){
+				$attributes_element = $dom->createAttribute($key);
+				$attributes_element->appendChild($dom->createTextNode($rs));
+				$key_Element->appendChild($attributes_element);
+		}
+	}
+
+	public function simplexml_to_array($xml) {
+	   $ar = array();
+	   foreach($xml->children() as $k => $v) {
+
+		   $child = simplexml_to_array($v);
+		   if( count($child) == 0 ) {
+			   $child = (string)$v;
+		   }
+		   foreach( $v->attributes() as $ak => $av ) {
+			   if( !is_array( $child ) ) {
+				   $child = array( "value" => $child );
+			   }
+			   $child[$ak] = (string)$av;
+		   }
+		   if (!in_array($k,array_keys($ar))) {
+			   $ar[$k] = $child;
+		   }else{
+				if($ar[$k][0]){
+					$ar[$k][] = $child;
+				}else{
+					$ar[$k] = array($ar[$k]);
+					$ar[$k][] = $child;
+				}
+		   }
+
+	   }
+	   return $ar;
+	}
+
+	public function simplexml2array($xml) {
+		$arXML=array();
+		$arXML['name']=trim($xml->getName());
+		$arXML['value']=trim((string)$xml);
+		$t=array();
+		foreach($xml->attributes() as $name => $value){
+			$t[$name]=trim($value);
+		}
+		$arXML['attr']=$t;
+		$t=array();
+		foreach($xml->children() as $name => $xmlchild) {
+
+			if (!in_array($name,array_keys($t))) {
+			   $t[$name] = $this->simplexml2array($xmlchild);
+			}else{
+				if(!$t[$name][0]){
+					$t[$name] = array($t[$name]);
+				}
+				$t[$name][]= $this->simplexml2array($xmlchild);
+		   }
+		}
+		$arXML['children']=$t;
+		return($arXML);
+	}
+
+
+
+
+}
+?>

+ 643 - 0
Ainaphp/Lib/ORG/Form.class.php

@@ -0,0 +1,643 @@
+<?php
+/**
+ *
+ * Form.php (模型表单生成)
+ *
+ */
+class Form extends Think {
+	public $data = array() ,$isadmin=1,$doThumb=1,$doAttach=1,$lang;
+
+    public function __construct($data=array()) {
+         $this->data = $data;
+		 if(APP_LANG)$this->lang = LANG_NAME;
+    }
+
+	public function catid($info,$value){
+        $validate = getvalidate($info);
+		if(APP_LANG){
+			$Category = F('Category_'.$this->lang);
+		}else{
+			$Category = F('Category');
+		}
+		$id = $field = $info['field'];
+		$value = $value ? $value : $this->data[$field];
+		$moduleid =$info['moduleid'];
+		foreach ($Category as $r){
+				$postgroup = explode(',',$r['postgroup']);
+				//if( ($this->isadmin && $_SESSION['groupid']!=1 && !in_array($_SESSION['groupid'],$postgroup)) ||  (empty($this->isadmin) && !in_array( cookie('groupid'),$postgroup)) ) continue;
+				//if($r['type']==1) continue;
+				$arr= explode(",",$r['arrchildid']);
+				$show=0;
+				foreach((array)$arr as $rr){
+					if($Category[$rr]['moduleid'] ==$moduleid) $show=1;
+				}
+				if(empty($show))continue;
+				$r['disabled'] = $r['child'] ? ' disabled' :'';
+				$array[] = $r;
+		}
+		import ( '@.ORG.Tree' );
+		$str  = "<option value='\$id' \$disabled \$selected>\$spacer \$catname</option>";
+		$tree = new Tree ($array);
+		$parseStr .= '<select  id="'.$id.'" name="'.$field.'" class=" '.$info['class'].'"  '.$validate.'>';
+		$parseStr .= '<option value="">'.L('please_chose').'</option>';
+		$parseStr .= $tree->get_tree(0, $str, $value);
+		$parseStr .= '</select>';
+		return $parseStr;
+	}
+
+
+	public function title($info,$value){
+		$info['setup']=is_array($info['setup']) ? $info['setup'] : string2array($info['setup']);
+		$thumb=$info['setup']['thumb'];
+		$style=$info['setup']['style'];
+		$id = $field = $info['field'];
+	    $validate = getvalidate($info);
+		$value = $value ? $value : $this->data[$field];
+
+		$title_style = explode(';',$this->data['title_style']);
+		$style_color = explode(':',$title_style[0]);
+		$style_color = $style_color[1];
+		$style_bold = explode(':',$title_style[1]);
+		$style_bold = $style_bold[1];
+
+		if(empty($info['setup']['upload_maxsize'])){
+
+			if(APP_LANG){
+				$Config = F('Config_'.$this->lang);
+			}else{
+				$Config = F('Config');
+			}
+
+			$info['setup']['upload_maxsize'] =  intval(byte_format($Config['attach_maxsize']));
+		}
+
+
+		$yourphp_auth_key = sysmd5(C('ADMIN_ACCESS').$_SERVER['HTTP_USER_AGENT']);
+		$yourphp_auth = authcode($this->isadmin.'-1-1-1-jpeg,jpg,png,gif-'.$info['setup']['upload_maxsize'].'-'.$info['moduleid'], 'ENCODE',$yourphp_auth_key);
+
+		$thumb_ico = $this->data['thumb']? $this->data['thumb'] : __ROOT__.'/Public/Images/admin_upload_thumb.png';
+		$boldchecked= $style_bold=='bold' ? 'checked' : '';
+		$thumbstr ='<div class="thumb_box"  id="thumb_box"><div id="thumb_aid_box"></div>
+				<a href="javascript:swfupload(\'thumb_uploadfile\',\'thumb\',\''.L('uploadfiles').'\','.$this->isadmin.',1,1,1,\'jpeg,jpg,png,gif\','.$info['setup']['upload_maxsize'].','.$info['moduleid'].',\''.$yourphp_auth.'\',yesdo,nodo)"><img src="'.$thumb_ico.'" id="thumb_pic" ></a><br> <input type="button" value="'.L('clean_thumb').'" onclick="javascript:clean_thumb(\'thumb\');" class="button" />
+				<input type="hidden"  id="thumb" name="thumb"  value="'.$this->data['thumb'].'" /><span class="thumb_tips"></span></div>';
+
+		$parseStr   = '<input type="text"   class="input-text input-title" name="'.$field.'"  id="'.$id.'" value="'.$value.'" size="'.$info['setup']['size'].'"  '.$validate.'  /> &nbsp;';
+		//gzse7en
+		/*
+		$stylestr = '<div id="'.$id.'_colorimg" class="colorimg" style="background-color:'.$style_color.'"><img src="__PUBLIC__/Images/admin_color_arrow.gif"></div><input type="hidden" id="'.$id.'_style_color" name="style_color" value="'.$style_color.'" /><input type="checkbox" class="style_bold" id="style_bold" name="style_bold" value="bold" '.$boldchecked.' /><b>'. L('style_bold').'</b><script>$.showcolor("'.$id.'_colorimg","'.$id.'_style_color");</script>';
+		*/
+		if($thumb &&  $this->doThumb)$parseStr = $thumbstr.$parseStr;
+		if($style) $parseStr = $parseStr.$stylestr;
+		return $parseStr;
+	}
+
+	public function text($info,$value){
+		$info['setup']=is_array($info['setup']) ? $info['setup'] : string2array($info['setup']);
+		$id = $field = $info['field'];
+	    $validate = getvalidate($info);
+		$info['setup']['ispassword'] ? $inputtext = 'password' : $inputtext = 'text';
+        if(ACTION_NAME=='add'){
+			$value = $value ? $value : $info['setup']['default'];
+        }else{
+			$value = $value ? $value : $this->data[$field];
+        }
+		$parseStr   = '<input type="'.$inputtext.'"   class="input-text '.$info['class'].'" name="'.$field.'"  id="'.$id.'" value="'.stripcslashes($value).'" size="'.$info['setup']['size'].'"  '.$validate.'/> ';
+		return $parseStr;
+	}
+
+
+
+	public function verify($info,$value){
+		$info['setup']=is_array($info['setup']) ? $info['setup'] : string2array($info['setup']);
+		$id = $field = $info['field'];
+	    $validate = getvalidate($info);
+		$parseStr   = '<input   class="input-text '.$info['class'].'" name="'.$field.'"  id="'.$id.'" value="" size="'.$info['setup']['size'].'"  '.$validate.' /><img src="'.URL('Home-Index/verify').'" onclick="javascript:resetVerifyCode();" class="checkcode" align="absmiddle"  title="点击刷新验证码" id="verifyImage"/>';
+		return $parseStr;
+	}
+
+
+
+
+	public function number($info,$value){
+		$info['setup']=is_array($info['setup']) ? $info['setup'] : string2array($info['setup']);
+		$id = $field = $info['field'];
+	    $validate = getvalidate($info);
+		$info['setup']['ispassowrd'] ? $inputtext = 'passowrd' : $inputtext = 'text';
+        if(ACTION_NAME=='add'){
+			$value = $value ? $value : $info['setup']['default'];
+        }else{
+			$value = $value ? $value : $this->data[$field];
+        }
+		$parseStr   = '<input type="'.$inputtext.'"   class="input-text '.$info['class'].'" name="'.$field.'"  id="'.$id.'" value="'.$value.'" size="'.$info['setup']['size'].'"  '.$validate.'/> ';
+		return $parseStr;
+	}
+
+	public function textarea($info,$value){
+		$info['setup']=is_array($info['setup']) ? $info['setup'] : string2array($info['setup']);
+		$id = $field = $info['field'];
+        $validate = getvalidate($info);
+        if(ACTION_NAME=='add'){
+			$value = $value ? $value : $info['setup']['default'];
+        }else{
+			$value = $value ? $value : $this->data[$field];
+        }
+
+		$parseStr   = '<textarea  class="'.$info['class'].'" name="'.$field.'"  rows="'.$info['setup']['rows'].'" cols="'.$info['setup']['cols'].'"  id="'.$id.'"   '.$validate.'/>'.stripcslashes($value).'</textarea>';
+		return $parseStr;
+	}
+
+
+	public function select($info,$value){
+
+		$info['setup']=is_array($info['setup']) ? $info['setup'] : string2array($info['setup']);
+		$id = $field = $info['field'];
+		$validate = getvalidate($info);
+        if(ACTION_NAME=='add'){
+			$value = $value ? $value : $info['setup']['default'];
+        }else{
+			$value = $value ? $value : $this->data[$field];
+        }
+        if($value != '') $value = strpos($value, ',') ? explode(',', $value) : $value;
+
+        if(is_array($info['options'])){
+             if($info['options_key']){
+				$options_key=explode(',',$info['options_key']);
+				foreach((array)$info['options'] as $key=>$res){
+					if($options_key[0]=='key'){
+						$optionsarr[$key]=$res[$options_key[1]];
+					}else{
+						$optionsarr[$res[$options_key[0]]]=$res[$options_key[1]];
+					}
+				}
+			}else{
+             $optionsarr = $info['options'];
+			}
+        }else{
+            $options    = $info['setup']['options'];
+            $options = explode("\n",$info['setup']['options']);
+        	foreach($options as $r) {
+        		$v = explode("|",$r);
+        		$k = trim($v[1]);
+        		$optionsarr[$k] = $v[0];
+        	}
+        }
+
+
+        if(!empty($info['setup']['multiple'])) {
+            $parseStr = '<select id="'.$id.'" name="'.$field.'"  onchange="'.$info['setup']['onchange'].'" class="'.$info['class'].'"  '.$validate.' size="'.$info['setup']['size'].'" multiple="multiple" >';
+        }else {
+        	$parseStr = '<select id="'.$id.'" name="'.$field.'" onchange="'.$info['setup']['onchange'].'"  class="'.$info['class'].'" '.$validate.'>';
+        }
+
+        if(is_array($optionsarr)) {
+			foreach($optionsarr as $key=>$val) {
+				if(!empty($value)){
+				    $selected='';
+					if($value==$key || in_array($key,$value)) $selected = ' selected="selected"';
+				    $parseStr   .= '<option '.$selected.' value="'.$key.'">'.$val.'</option>';
+				}else{
+					$parseStr   .= '<option value="'.$key.'">'.$val.'</option>';
+				}
+			}
+		}
+        $parseStr   .= '</select>';
+        return $parseStr;
+	}
+	public function checkbox($info,$value){
+
+		$info['setup']=is_array($info['setup']) ? $info['setup'] : string2array($info['setup']);
+		$id = $field = $info['field'];
+		$validate = getvalidate($info);
+		if(ACTION_NAME=='add'){
+			$value = $value ? $value : $info['setup']['default'];
+        }else{
+			$value = $value ? $value : $this->data[$field];
+        }
+        $labelwidth = $info['setup']['labelwidth'];
+
+
+        if(is_array($info['options'])){
+			if($info['options_key']){
+				$options_key=explode(',',$info['options_key']);
+				foreach((array)$info['options'] as $key=>$res){
+					if($options_key[0]=='key'){
+						$optionsarr[$key]=$res[$options_key[1]];
+					}else{
+						$optionsarr[$res[$options_key[0]]]=$res[$options_key[1]];
+					}
+				}
+			}else{
+             $optionsarr = $info['options'];
+			}
+        }else{
+            $options    = $info['setup']['options'];
+            $options = explode("\n",$info['setup']['options']);
+        	foreach($options as $r) {
+        		$v = explode("|",$r);
+        		$k = trim($v[1]);
+        		$optionsarr[$k] = $v[0];
+        	}
+        }
+		if($value != '') $value = (strpos($value, ',') && !is_array($value)) ? explode(',', $value) :  $value ;
+		$value = is_array($value) ? $value : array($value);
+		$i = 1;
+		$onclick = $info['setup']['onclick'] ? ' onclick="'.$info['setup']['onclick'].'" ' : '' ;
+
+		foreach($optionsarr as $key=>$r) {
+			$key = trim($key);
+            if($i>1) $validate='';
+			$checked = ($value && in_array($key, $value)) ? 'checked' : '';
+			if($labelwidth) $parseStr .= '<label style="float:left;width:'.$labelwidth.'px" class="checkbox_'.$id.'" >';
+			$parseStr .= '<input type="checkbox" class="input_checkbox '.$info['class'].'" name="'.$field.'[]" id="'.$id.'_'.$i.'" '.$checked.$onclick.' value="'.htmlspecialchars($key).'"  '.$validate.'> '.htmlspecialchars($r);
+			if($labelwidth) $parseStr .= '</label>';
+			$i++;
+		}
+		return $parseStr;
+
+	}
+	public function radio($info,$value){
+
+       $info['setup']=is_array($info['setup']) ? $info['setup'] : string2array($info['setup']);
+		$id = $field = $info['field'];
+		$validate = getvalidate($info);
+		if(ACTION_NAME=='add'){
+			$value = $value ? $value : $info['setup']['default'];
+        }else{
+			$value = $value ? $value : $this->data[$field];
+        }
+        $labelwidth = $info['setup']['labelwidth'];
+
+        if(is_array($info['options'])){
+             if($info['options_key']){
+				$options_key=explode(',',$info['options_key']);
+				foreach((array)$info['options'] as $key=>$res){
+					if($options_key[0]=='key'){
+						$optionsarr[$key]=$res[$options_key[1]];
+					}else{
+						$optionsarr[$res[$options_key[0]]]=$res[$options_key[1]];
+					}
+				}
+			}else{
+             $optionsarr = $info['options'];
+			}
+        }else{
+            $options    = $info['setup']['options'];
+            $options = explode("\n",$info['setup']['options']);
+        	foreach($options as $r) {
+        		$v = explode("|",$r);
+        		$k = trim($v[1]);
+        		$optionsarr[$k] = $v[0];
+        	}
+        }
+		$onclick = $info['setup']['onclick'] ? ' onclick="'.$info['setup']['onclick'].'" ' : '' ;
+        $i = 1;
+        foreach($optionsarr as $key=>$r) {
+            if($i>1) $validate ='';
+			$checked = trim($value)==trim($key) ? 'checked' : '';
+			if(empty($value) && empty($key) ) $checked = 'checked';
+			if($labelwidth) $parseStr .= '<label style="float:left;width:'.$labelwidth.'px" class="checkbox_'.$id.'" >';
+			$parseStr .= '<input type="radio" class="input_radio '.$info['class'].'" name="'.$field.'" id="'.$id.'_'.$i.'" '.$checked.$onclick.' value="'.$key.'" '.$validate.'> '.$r;
+			if($labelwidth) $parseStr .= '</label>';
+            $i++;
+		}
+		return $parseStr;
+	}
+
+
+	public function editor($info,$value){
+
+		$info['setup']=is_array($info['setup']) ? $info['setup'] : string2array($info['setup']);
+		$id = $field = $info['field'];
+		$validate = getvalidate($info);
+		if(ACTION_NAME=='add'){
+			$value = $value ? $value : $info['setup']['default'];
+        }else{
+			$value = $value ? $value : $this->data[$field];
+        }
+		 $textareaid = $field;
+		 $toolbar = $info['setup']['toolbar'];
+		 $moduleid = $info['moduleid'];
+		 $height = $info['setup']['height'] ? $info['setup']['height'] : 300;
+		 $flashupload = $info['setup']['flashupload']==1 ? 1 : '';
+		 $alowuploadexts = $info['setup']['alowuploadexts'] ? $info['setup']['alowuploadexts'] :  'jpg,gif,png';
+		 $alowuploadlimit=$info['setup']['alowuploadlimit'] ? $info['setup']['alowuploadlimit'] : 20 ;
+		 $show_page=$info['setup']['showpage'];
+
+		if(APP_LANG){
+				$Config = F('Config_'.$this->lang);
+		}else{
+				$Config = F('Config');
+		}
+		$file_size = intval(byte_format($Config['attach_maxsize']));
+
+		$yourphp_auth_key = sysmd5(C('ADMIN_ACCESS').$_SERVER['HTTP_USER_AGENT']);
+
+
+
+		$attach_auth = authcode("$this->isadmin-1-0-$alowuploadlimit-$Config[attach_allowext]-$file_size-$moduleid", 'ENCODE',$yourphp_auth_key);
+		$yourphp_auth = authcode("$this->isadmin-1-0-$alowuploadlimit-$alowuploadexts-$file_size-$moduleid", 'ENCODE',$yourphp_auth_key);
+
+		$str ='';
+		$str .= '<div class="editor_box"><div style="display:none;" id="'.$field.'_aid_box"></div><textarea name="'.$field.'" class="'.$info['class'].'"  id="'.$id.'"  boxid="'.$id.'" '.$validate.'  style="width:99%;height:'.$height.'px;visibility:hidden;">'.$value.'</textarea>';
+
+		$show_page =  $show_page ?  1 :  0;
+
+		if ($info['setup']['edittype']=='Xheditor'){
+
+
+			if($toolbar=='basic'){
+				$modtools = 'simple';
+			} elseif($toolbar == 'full') {
+				$modtools = $this->isadmin ? 'full' : 'mfull';
+			} elseif($toolbar == 'desc') {
+				$modtools = 'mini';
+			} else {
+				$modtools = '';
+			}
+
+			$str .="<script type=\"text/javascript\" src=\"".__ROOT__."/Public/Xheditor/xheditor-zh-cn.min.js\"></script>";
+			$str .="<script type=\"text/javascript\"> \r\n";
+			$str .="var editor_".$id."=$('#".$id."').xheditor({ ";
+			$str .="plugins:plugins,tools:'".$modtools."',loadCSS:'<style>pre{margin:12px;background:#EFEFEF;border:1px solid #ddd;border-left:3px solid #6CE26C;padding:10px;padding-top: 1px;}</style>',shortcuts:{'ctrl+enter':submitForm},width:\"100%\",height:\"$height\"";
+
+			if($flashupload){
+				$str .=",upLinkUrl:\"!".__ROOT__."/index.php?g=Admin&m=Attachment&a=index&isadmin=$this->isadmin&more=1&isthumb=0&file_limit=$alowuploadlimit&file_types=$Config[attach_allowext]&file_size=$file_size&moduleid=$moduleid&auth=$attach_auth&editorid=$id&immediate=1&l=$this->lang\"";
+				$str .=",upImgUrl:\"!".__ROOT__."/index.php?g=Admin&m=Attachment&a=index&isadmin=$this->isadmin&more=1&isthumb=0&file_limit=$alowuploadlimit&file_types=$alowuploadexts&file_size=$file_size&moduleid=$moduleid&auth=$yourphp_auth&editorid=$id&immediate=1&l=$this->lang\"";
+
+				$yourphp_auth = authcode("$this->isadmin-1-0-$alowuploadlimit-swf-$file_size-$moduleid", 'ENCODE',$yourphp_auth_key);
+				$str .=",upFlashUrl:\"!".__ROOT__."/index.php?g=Admin&m=Attachment&a=index&isadmin=$this->isadmin&more=1&isthumb=0&file_limit=$alowuploadlimit&file_types=swf&file_size=$file_size&moduleid=$moduleid&auth=$yourphp_auth&editorid=$id&immediate=1&l=$this->lang\"";
+
+				$yourphp_auth = authcode("$this->isadmin-1-0-$alowuploadlimit-mpg,wmv,avi,wma,mp3,mid,asf,rm-$file_size-$moduleid", 'ENCODE',$yourphp_auth_key);
+				$str .=",upMediaUrl:\"!".__ROOT__."/index.php?g=Admin&m=Attachment&a=index&isadmin=$this->isadmin&more=1&isthumb=0&file_limit=$alowuploadlimit&file_types=mpg,wmv,avi,wma,mp3,mid,asf,rm&file_size=$file_size&moduleid=$moduleid&auth=$yourphp_auth&editorid=$id&immediate=1&l=$this->lang\"";
+
+				$str .=",onUpload:upokis,modalWidth:\"600\",modalHeight:\"455\"";
+			}
+
+			$str .= "});</script>";
+
+			$str .='<div class=\'editor_bottom1\'>';
+
+			if($show_page) $str .='<a href="javascript:void(0);"  onclick="editor_'.$id.'.pasteText(\'[page]\');return false;">'.L('page_break').'</a>';
+			if($info['setup']['show_add_description']) $str .='<input type="checkbox" class="input_radio" name="add_description" value="1" checked /> '.L('add_description').' <input type="text"  name="description_length" value="200" style="width:24px;" size="3" />'.L('description_length');
+			if($info['setup']['show_auto_thumb']) $str .='<input type="checkbox" class="input_radio" name="auto_thumb" value="1" checked /> '.L('auto_thumb').'<input   type="text" name="auto_thumb_no" value="1" size="1" />'.L('auto_thumb_no');
+			$str .= '</div></div>';
+
+		}else{
+
+
+
+			$upurl= __ROOT__."/index.php?g=Admin&m=Attachment&a=index&isadmin=$this->isadmin&more=1&isthumb=0&file_limit=$alowuploadlimit&file_types=$Config[attach_allowext]&file_size=$file_size&moduleid=$moduleid&auth=$attach_auth&l=$this->lang";
+
+			$yourphp_auth = authcode("$this->isadmin-1-0-1-gif,jpg,jpeg,png,bmp-$file_size-$moduleid", 'ENCODE',$yourphp_auth_key);
+			$upImgUrl =__ROOT__."/index.php?g=Admin&m=Attachment&a=index&isadmin=$this->isadmin&more=1&isthumb=0&file_limit=1&file_types=gif,jpg,jpeg,png,bmp&file_size=$file_size&moduleid=$moduleid&auth=$yourphp_auth&l=$this->lang";
+
+			$yourphp_auth = authcode("$this->isadmin-1-0-1-swf,flv-$file_size-$moduleid", 'ENCODE',$yourphp_auth_key);
+			$upFlashUrl=__ROOT__."/index.php?g=Admin&m=Attachment&a=index&isadmin=$this->isadmin&more=1&isthumb=0&file_limit=1&file_types=swf,flv&file_size=$file_size&moduleid=$moduleid&auth=$yourphp_auth&l=$this->lang";
+
+			$yourphp_auth = authcode("$this->isadmin-1-0-1-mpg,wmv,avi,wma,mp3,mid,asf,rm,rmvb,wav,wma,mp4-$file_size-$moduleid", 'ENCODE',$yourphp_auth_key);
+			$upMediaUrl=__ROOT__."/index.php?g=Admin&m=Attachment&a=index&isadmin=$this->isadmin&more=1&isthumb=0&file_limit=1&file_types=mpg,wmv,avi,wma,mp3,mid,asf,rm,rmvb,wav,wma,mp4&file_size=$file_size&moduleid=$moduleid&auth=$yourphp_auth&l=$this->lang";
+
+			$str .="<script type=\"text/javascript\" src=\"".__ROOT__."/Public/Kindeditor/kindeditor-min.js\"></script>";
+			$str .= "<script type=\"text/javascript\">\r\n";
+			$str .= "KindEditor.ready(function(K) {\r\n";
+			$str .= "K.create('#".$id."', {\r\n";
+			$str .= "cssPath : '".__ROOT__."/Public/Kindeditor/plugins/code/prettify.css',";
+			//$str .= "uploadJson : '$upurl',";
+			$str .= "fileManagerJson:'$upurl',";
+			$str .= "editorid:'$id',";
+			$str .= "upImgUrl:'$upImgUrl',";
+			$str .= "upFlashUrl:'$upFlashUrl',";
+			$str .= "upMediaUrl:'$upMediaUrl',";
+			$str .= "allowFileManager : true\r\n";
+
+			$str .= "});\r\n";
+			$str .= "});\r\n";
+			$str .= '</script>';
+			$str .='<div  class=\'editor_bottom2\'>';
+			if($info['setup']['show_add_description']) $str .='<input type="checkbox" name="add_description" value="1" checked /> '.L('add_description').'
+				<input type="text" name="description_length" value="200" style="width:24px;" size="3" />'.L('description_length');
+			if($info['setup']['show_auto_thumb']) $str .='<input type="checkbox" name="auto_thumb" value="1" checked /> '.L('auto_thumb').'
+				<input type="text" name="auto_thumb_no" value="1" size="1" />'.L('auto_thumb_no');
+			$str .= '</div></div>';
+		}
+
+
+		return $str;
+	}
+	public function datetime($info,$value){
+		$info['setup']=is_array($info['setup']) ? $info['setup'] : string2array($info['setup']);
+		$id = $field = $info['field'];
+		$validate = getvalidate($info);
+		if(ACTION_NAME=='add'){
+			$value = $value ? $value : $info['setup']['default'];
+        }else{
+			$value = $value ? $value : $this->data[$field];
+        }
+		$value = $value ?  toDate($value,"Y-m-d H:i:s") : toDate(time(),"Y-m-d H:i:s");
+
+		$parseStr = '<input  class="Wdate input-text  '.$info['class'].'"  '.$validate.'  name="'.$field.'" type="text" id="'.$id.'" size="25" onFocus="WdatePicker({dateFmt:\'yyyy-MM-dd HH:mm:ss\'
+		})" value="'.$value.'" />';
+        return $parseStr;
+	}
+    public function groupid($info,$value){
+        $newinfo = $info;
+        $info['setup']=is_array($info['setup']) ? $info['setup'] : string2array($info['setup']);
+        $groups=F('Role');$options=array();
+        foreach($groups as $key=>$r) {
+            if($r['status']){
+                $options[$key]=$r['name'];
+            }
+		}
+        $newinfo['options']=$options;
+        $fun=$info['setup']['inputtype'];
+        return $this->$fun($newinfo,$value);
+    }
+    public function posid($info,$value){
+        $newinfo = $info;
+        $posids=F('Posid');
+        $options=array();
+        $options[0]= L('please_chose');
+        foreach($posids as $key=>$r) {
+           $options[$key]=$r['name'];
+		}
+        $newinfo['options']=$options;
+        $fun=$info['setup']['inputtype'];
+        return $this->select($newinfo,$value);
+    }
+
+	public function typeid($info,$value){
+        $newinfo = $info;
+        $types=F('Type');
+
+
+		$info['setup']=is_array($info['setup']) ? $info['setup'] : string2array($info['setup']);
+		$id = $field = $info['field'];
+		$value = $value ? $value : $this->data[$field];
+		$parentid=$info['setup']['default'];
+		$keyid = $types[$parentid]['keyid'];
+
+		$options=array();
+        $options[0]= L('please_chose');
+		foreach((array)$types as $key => $r) {
+			if($r['keyid']!=$keyid) continue;
+			$r['id']=$r['typeid'];
+			$array[] = $r;
+			$options[$key]=$r['name'];
+		}
+
+		import ( '@.ORG.Tree' );
+		$str  = "<option value='\$typeid' \$selected>\$spacer \$name</option>";
+		$tree = new Tree ($array);
+		$tree->nbsp='&nbsp;&nbsp;';
+		$select_type = $tree->get_tree(0, $str,$value);
+
+		$fun=$info['setup']['inputtype'];
+		if($fun=='select'){
+			return '<SELECT  id="'.$id.'" class="'.$info['class'].'"   name="'.$field.'"><option value="0">'.L('please_chose').'</option>'. $select_type.'</select>';
+		}else{
+			$newinfo['options']=$options;
+			return $this->$fun($newinfo,$value);
+		}
+    }
+
+    public function template($info,$value){
+
+        $templates= template_file(MODULE_NAME);
+        $newinfo = $info;
+        $info['setup']=is_array($info['setup']) ? $info['setup'] : string2array($info['setup']);
+        $options=array();
+        $options[0]= L('please_chose');
+        foreach($templates as $key=>$r) {
+            if(strstr($r['value'],'show')){
+                $options[$r['value']]=$r['filename'];
+            }
+		}
+        $newinfo['options']=$options;
+        $fun=$info['setup']['inputtype'];
+        return $this->select($newinfo,$value);
+    }
+
+
+	public function image($info,$value){
+		$info['setup']=is_array($info['setup']) ? $info['setup'] : string2array($info['setup']);
+		$id = $field = $info['field'];
+	    $validate = getvalidate($info);
+        if(ACTION_NAME=='add'){
+			$value = $value ? $value : $info['setup']['default'];
+        }else{
+			$value = $value ? $value : $this->data[$field];
+        }
+		if(empty($info['setup']['upload_maxsize'])){
+			if(APP_LANG){
+				$Config = F('Config_'.$this->lang);
+			}else{
+				$Config = F('Config');
+			}
+			$info['setup']['upload_maxsize'] =  intval(byte_format($Config['attach_maxsize']));
+		}
+
+
+		$yourphp_auth_key = sysmd5(C('ADMIN_ACCESS').$_SERVER['HTTP_USER_AGENT']);
+		$yourphp_auth = authcode($this->isadmin.'-'.$info['setup']['more'].'-0-1-'.$info['setup']['upload_allowext'].'-'.$info['setup']['upload_maxsize'].'-'.$info['moduleid'], 'ENCODE',$yourphp_auth_key);
+
+		$parseStr   = ' <div id="'.$field.'_aid_box"></div><input type="text"   class="input-text '.$info['class'].'" name="'.$field.'"  id="'.$id.'" value="'.$value.'" size="'.$info['setup']['size'].'"  '.$validate.'/> <input type="button" class="button" value="'.L('upload_images').'" onclick="javascript:swfupload(\''.$field.'_uploadfile\',\''.$field.'\',\''.L('uploadfiles').'\','.$this->isadmin.','.$info['setup']['more'].',0,1,\''.$info['setup']['upload_allowext'].'\','.$info['setup']['upload_maxsize'].','.$info['moduleid'].',\''.$yourphp_auth.'\',up_image,nodo)"> ';
+		return $parseStr;
+	}
+
+	public function images($info,$value){
+		$info['setup']=is_array($info['setup']) ? $info['setup'] : string2array($info['setup']);
+		$id = $field = $info['field'];
+	    $validate = getvalidate($info);
+        if(ACTION_NAME=='add'){
+			$value = $value ? $value : $info['setup']['default'];
+        }else{
+			$value = $value ? $value : $this->data[$field];
+        }
+		$data='';
+		$i=0;
+		if($value){
+			$options = explode(":::",$value);
+			if(is_array($options)){
+				foreach($options as  $r) {
+						$v = explode("|",$r);
+						$k = trim($v[1]);
+						$optionsarr[$k] = $v[0];
+						$data .='<div id="uplistd_'.$i.'"><input type="text" size="50" class="input-text" name="'.$field.'[]" value="'.$v[0].'"  /> <input type="text" class="input-text" name="'.$field.'_name[]" value="'.$v[1].'" size="30" /> &nbsp;<a href="javascript:remove_this(\'uplistd_'.$i.'\');">'.L('remove').'</a> </div>';
+						$i++;
+				}
+			}
+		}
+		if(empty($info['setup']['upload_maxsize'])){
+			if(APP_LANG){
+				$Config = F('Config_'.$this->lang);
+			}else{
+				$Config = F('Config');
+			}
+			$info['setup']['upload_maxsize'] =  intval(byte_format($Config['attach_maxsize']));
+		}
+		$yourphp_auth_key = sysmd5(C('ADMIN_ACCESS').$_SERVER['HTTP_USER_AGENT']);
+		$yourphp_auth = authcode($this->isadmin.'-'.$info['setup']['more'].'-0-'.$info['setup']['upload_maxnum'].'-'.$info['setup']['upload_allowext'].'-'.$info['setup']['upload_maxsize'].'-'.$info['moduleid'], 'ENCODE',$yourphp_auth_key);
+
+		$parseStr   = '
+		<fieldset class="images_box">
+        <legend>'.L('upload_images').'</legend><center><div>'.L('upload_maxfiles').' <font color=\'red\'>'.$info['setup']['upload_maxnum'].'</font> '.L('zhang').'</div></center>
+		<div id="'.$field.'_images" class="imagesList"><input type="hidden"  name="'.$field.'[]" value=""/><input type="hidden"   name="'.$field.'_name[]" value="" />'.$data.'</div>
+		</fieldset>
+		<div class="c"></div>
+		<input type="button" class="button" value="'.L('upload_images').'" onclick="javascript:swfupload(\''.$field.'_uploadfile\',\''.$field.'\',\''.L('uploadfiles').'\','.$this->isadmin.','.$info['setup']['more'].',0,'.$info['setup']['upload_maxnum'].',\''.$info['setup']['upload_allowext'].'\','.$info['setup']['upload_maxsize'].','.$info['moduleid'].',\''.$yourphp_auth.'\',up_images,nodo)">  ';
+
+		return $parseStr;
+	}
+	public function file($info,$value){
+		$info['setup']=is_array($info['setup']) ? $info['setup'] : string2array($info['setup']);
+		$id = $field = $info['field'];
+	    $validate = getvalidate($info);
+        if(ACTION_NAME=='add'){
+			$value = $value ? $value : $info['setup']['default'];
+        }else{
+			$value = $value ? $value : $this->data[$field];
+        }
+		if(empty($info['setup']['upload_maxsize'])){
+			if(APP_LANG){
+				$Config = F('Config_'.$this->lang);
+			}else{
+				$Config = F('Config');
+			}
+			$info['setup']['upload_maxsize'] =  intval(byte_format($Config['attach_maxsize']));
+		}
+		$yourphp_auth_key = sysmd5(C('ADMIN_ACCESS').$_SERVER['HTTP_USER_AGENT']);
+		$yourphp_auth = authcode($this->isadmin.'-'.$info['setup']['more'].'-0-1-'.$info['setup']['upload_allowext'].'-'.$info['setup']['upload_maxsize'].'-'.$info['moduleid'], 'ENCODE',$yourphp_auth_key);
+		$parseStr   = ' <div id="'.$field.'_aid_box"></div><input type="text"    class="input-text '.$info['class'].'" name="'.$field.'"  id="'.$id.'" value="'.$value.'" size="'.$info['setup']['size'].'"  '.$validate.'/> <input type="button" class="button" value="'.L('upload_files').'" onclick="javascript:swfupload(\''.$field.'_uploadfile\',\''.$field.'\',\''.L('uploadfiles').'\','.$this->isadmin.','.$info['setup']['more'].',0,1,\''.$info['setup']['upload_allowext'].'\','.$info['setup']['upload_maxsize'].','.$info['moduleid'].',\''.$yourphp_auth.'\',up_image,nodo)"> ';
+		return $parseStr;
+	}
+
+	public function files($info,$value){
+		$info['setup']=is_array($info['setup']) ? $info['setup'] : string2array($info['setup']);
+		$id = $field = $info['field'];
+	    $validate = getvalidate($info);
+        if(ACTION_NAME=='add'){
+			$value = $value ? $value : $info['setup']['default'];
+        }else{
+			$value = $value ? $value : $this->data[$field];
+        }
+		if(empty($info['setup']['upload_maxsize'])){
+			if(APP_LANG){
+				$Config = F('Config_'.$this->lang);
+			}else{
+				$Config = F('Config');
+			}
+			$info['setup']['upload_maxsize'] =  intval(byte_format($Config['attach_maxsize']));
+		}
+		$yourphp_auth_key = sysmd5(C('ADMIN_ACCESS').$_SERVER['HTTP_USER_AGENT']);
+		$yourphp_auth = authcode($this->isadmin.'-'.$info['setup']['more'].'-0-'.$info['setup']['upload_maxnum'].'-'.$info['setup']['upload_allowext'].'-'.$info['setup']['upload_maxsize'].'-'.$info['moduleid'], 'ENCODE',$yourphp_auth_key);
+
+		$parseStr   = '<fieldset class="images_box">
+        <legend>'.L('upload_images').'</legend><center><div>'.L('upload_maxfiles').' <font color=\'red\'>'.$info['setup']['upload_maxnum'].'</font> '.L('zhang').'</div></center>
+		<div id="'.$field.'_images" class="imagesList"></div>
+		</fieldset>
+		<input type="button"  style="margin-left:5px;" class="button" value="'.L('upload_files').'" onclick="javascript:swfupload(\''.$field.'_uploadfile\',\''.$field.'\',\''.L('uploadfiles').'\','.$this->isadmin.','.$info['setup']['more'].',0,'.$info['setup']['upload_maxnum'].',\''.$info['setup']['upload_allowext'].'\','.$info['setup']['upload_maxsize'].','.$info['moduleid'].',\''.$yourphp_auth.'\',up_images,nodo)">  ';
+
+		return $parseStr;
+	}
+}
+?>

+ 537 - 0
Ainaphp/Lib/ORG/Http.class.php

@@ -0,0 +1,537 @@
+<?php
+// +----------------------------------------------------------------------
+// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
+// +----------------------------------------------------------------------
+// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
+// +----------------------------------------------------------------------
+// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
+// +----------------------------------------------------------------------
+// | Author: liu21st <liu21st@gmail.com>
+// +----------------------------------------------------------------------
+// $Id: Http.class.php 2504 2011-12-28 07:35:29Z liu21st $
+
+/**
+ +------------------------------------------------------------------------------
+ * Http 工具类
+ * 提供一系列的Http方法
+ +------------------------------------------------------------------------------
+ * @category   ORG
+ * @package  ORG
+ * @subpackage  Net
+ * @author    liu21st <liu21st@gmail.com>
+ * @version   $Id: Http.class.php 2504 2011-12-28 07:35:29Z liu21st $
+ +------------------------------------------------------------------------------
+ */
+class Http  extends Think {
+
+    /**
+     +----------------------------------------------------------
+     * 采集远程文件
+     +----------------------------------------------------------
+     * @access public
+     +----------------------------------------------------------
+     * @param string $remote 远程文件名
+     * @param string $local 本地保存文件名
+     +----------------------------------------------------------
+     * @return mixed
+     +----------------------------------------------------------
+     */
+    static public function curlDownload($remote,$local) {
+        $cp = curl_init($remote);
+        $fp = fopen($local,"w");
+        curl_setopt($cp, CURLOPT_FILE, $fp);
+        curl_setopt($cp, CURLOPT_HEADER, 0);
+        curl_exec($cp);
+        curl_close($cp);
+        fclose($fp);
+    }
+
+   /**
+    +-----------------------------------------------------------
+    * 使用 fsockopen 通过 HTTP 协议直接访问(采集)远程文件
+    * 如果主机或服务器没有开启 CURL 扩展可考虑使用
+    * fsockopen 比 CURL 稍慢,但性能稳定
+    +-----------------------------------------------------------
+    * @static
+    * @access public
+    +-----------------------------------------------------------
+    * @param string $url 远程URL
+    * @param array $conf 其他配置信息
+    *        int   limit 分段读取字符个数
+    *        string post  post的内容,字符串或数组,key=value&形式
+    *        string cookie 携带cookie访问,该参数是cookie内容
+    *        string ip    如果该参数传入,$url将不被使用,ip访问优先
+    *        int    timeout 采集超时时间
+    *        bool   block 是否阻塞访问,默认为true
+    +-----------------------------------------------------------
+    * @return mixed
+    +-----------------------------------------------------------
+    */
+    static public function fsockopenDownload($url, $conf = array()) {
+        $return = '';
+        if(!is_array($conf)) return $return;
+
+        $matches = parse_url($url);
+        !isset($matches['host']) && $matches['host'] = '';
+        !isset($matches['path']) && $matches['path'] = '';
+        !isset($matches['query']) && $matches['query'] = '';
+        !isset($matches['port']) && $matches['port'] = '';
+        $host = $matches['host'];
+        $path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';
+        $port = !empty($matches['port']) ? $matches['port'] : 80;
+
+        $conf_arr = array(
+            'limit'=>0,
+            'post'=>'',
+            'cookie'=>'',
+            'ip'=>'',
+            'timeout'=>15,
+            'block'=>TRUE,
+            );
+
+        foreach (array_merge($conf_arr, $conf) as $k=>$v) ${$k} = $v;
+
+        if($post) {
+            if(is_array($post))
+            {
+                $post = http_build_query($post);
+            }
+            $out = "POST $path HTTP/1.0\r\n";
+            $out .= "Accept: */*\r\n";
+            //$out .= "Referer: $boardurl\r\n";
+            $out .= "Accept-Language: zh-cn\r\n";
+            $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
+            $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
+            $out .= "Host: $host\r\n";
+            $out .= 'Content-Length: '.strlen($post)."\r\n";
+            $out .= "Connection: Close\r\n";
+            $out .= "Cache-Control: no-cache\r\n";
+            $out .= "Cookie: $cookie\r\n\r\n";
+            $out .= $post;
+        } else {
+            $out = "GET $path HTTP/1.0\r\n";
+            $out .= "Accept: */*\r\n";
+            //$out .= "Referer: $boardurl\r\n";
+            $out .= "Accept-Language: zh-cn\r\n";
+            $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
+            $out .= "Host: $host\r\n";
+            $out .= "Connection: Close\r\n";
+            $out .= "Cookie: $cookie\r\n\r\n";
+        }
+        $fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
+        if(!$fp) {
+            return '';
+        } else {
+            stream_set_blocking($fp, $block);
+            stream_set_timeout($fp, $timeout);
+            @fwrite($fp, $out);
+            $status = stream_get_meta_data($fp);
+            if(!$status['timed_out']) {
+                while (!feof($fp)) {
+                    if(($header = @fgets($fp)) && ($header == "\r\n" ||  $header == "\n")) {
+                        break;
+                    }
+                }
+
+                $stop = false;
+                while(!feof($fp) && !$stop) {
+                    $data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
+                    $return .= $data;
+                    if($limit) {
+                        $limit -= strlen($data);
+                        $stop = $limit <= 0;
+                    }
+                }
+            }
+            @fclose($fp);
+            return $return;
+        }
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 下载文件
+     * 可以指定下载显示的文件名,并自动发送相应的Header信息
+     * 如果指定了content参数,则下载该参数的内容
+     +----------------------------------------------------------
+     * @static
+     * @access public
+     +----------------------------------------------------------
+     * @param string $filename 下载文件名
+     * @param string $showname 下载显示的文件名
+     * @param string $content  下载的内容
+     * @param integer $expire  下载内容浏览器缓存时间
+     +----------------------------------------------------------
+     * @return void
+     +----------------------------------------------------------
+     * @throws ThinkExecption
+     +----------------------------------------------------------
+     */
+    static public function download ($filename, $showname='',$content='',$expire=180) {
+        if(is_file($filename)) {
+            $length = filesize($filename);
+        }elseif(is_file(UPLOAD_PATH.$filename)) {
+            $filename = UPLOAD_PATH.$filename;
+            $length = filesize($filename);
+        }elseif($content != '') {
+            $length = strlen($content);
+        }else {
+            throw_exception($filename.L('下载文件不存在!'));
+        }
+        if(empty($showname)) {
+            $showname = $filename;
+        }
+        $showname = basename($showname);
+		if(!empty($filename)) {
+	        $type = mime_content_type($filename);
+		}else{
+			$type	 =	 "application/octet-stream";
+		}
+        //发送Http Header信息 开始下载
+        header("Pragma: public");
+        header("Cache-control: max-age=".$expire);
+        //header('Cache-Control: no-store, no-cache, must-revalidate');
+        header("Expires: " . gmdate("D, d M Y H:i:s",time()+$expire) . "GMT");
+        header("Last-Modified: " . gmdate("D, d M Y H:i:s",time()) . "GMT");
+        header("Content-Disposition: attachment; filename=".$showname);
+        header("Content-Length: ".$length);
+        header("Content-type: ".$type);
+        header('Content-Encoding: none');
+        header("Content-Transfer-Encoding: binary" );
+        if($content == '' ) {
+            readfile($filename);
+        }else {
+        	echo($content);
+        }
+        exit();
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 显示HTTP Header 信息
+     +----------------------------------------------------------
+     * @return string
+     +----------------------------------------------------------
+     */
+    static function getHeaderInfo($header='',$echo=true) {
+        ob_start();
+        $headers   = getallheaders();
+        if(!empty($header)) {
+            $info = $headers[$header];
+            echo($header.':'.$info."\n"); ;
+        }else {
+            foreach($headers as $key=>$val) {
+                echo("$key:$val\n");
+            }
+        }
+        $output = ob_get_clean();
+        if ($echo) {
+            echo (nl2br($output));
+        }else {
+            return $output;
+        }
+
+    }
+
+    /**
+     * HTTP Protocol defined status codes
+     * @param int $num
+     */
+	static function sendHttpStatus($code) {
+		static $_status = array(
+			// Informational 1xx
+			100 => 'Continue',
+			101 => 'Switching Protocols',
+
+			// Success 2xx
+			200 => 'OK',
+			201 => 'Created',
+			202 => 'Accepted',
+			203 => 'Non-Authoritative Information',
+			204 => 'No Content',
+			205 => 'Reset Content',
+			206 => 'Partial Content',
+
+			// Redirection 3xx
+			300 => 'Multiple Choices',
+			301 => 'Moved Permanently',
+			302 => 'Found',  // 1.1
+			303 => 'See Other',
+			304 => 'Not Modified',
+			305 => 'Use Proxy',
+			// 306 is deprecated but reserved
+			307 => 'Temporary Redirect',
+
+			// Client Error 4xx
+			400 => 'Bad Request',
+			401 => 'Unauthorized',
+			402 => 'Payment Required',
+			403 => 'Forbidden',
+			404 => 'Not Found',
+			405 => 'Method Not Allowed',
+			406 => 'Not Acceptable',
+			407 => 'Proxy Authentication Required',
+			408 => 'Request Timeout',
+			409 => 'Conflict',
+			410 => 'Gone',
+			411 => 'Length Required',
+			412 => 'Precondition Failed',
+			413 => 'Request Entity Too Large',
+			414 => 'Request-URI Too Long',
+			415 => 'Unsupported Media Type',
+			416 => 'Requested Range Not Satisfiable',
+			417 => 'Expectation Failed',
+
+			// Server Error 5xx
+			500 => 'Internal Server Error',
+			501 => 'Not Implemented',
+			502 => 'Bad Gateway',
+			503 => 'Service Unavailable',
+			504 => 'Gateway Timeout',
+			505 => 'HTTP Version Not Supported',
+			509 => 'Bandwidth Limit Exceeded'
+		);
+		if(isset($_status[$code])) {
+			header('HTTP/1.1 '.$code.' '.$_status[$code]);
+		}
+	}
+}//类定义结束
+if( !function_exists ('mime_content_type')) {
+    /**
+     +----------------------------------------------------------
+     * 获取文件的mime_content类型
+     +----------------------------------------------------------
+     * @return string
+     +----------------------------------------------------------
+     */
+    function mime_content_type($filename) {
+       static $contentType = array(
+			'ai'	=> 'application/postscript',
+				'aif'	=> 'audio/x-aiff',
+				'aifc'	=> 'audio/x-aiff',
+				'aiff'	=> 'audio/x-aiff',
+				'asc'	=> 'application/pgp', //changed by skwashd - was text/plain
+				'asf'	=> 'video/x-ms-asf',
+				'asx'	=> 'video/x-ms-asf',
+				'au'	=> 'audio/basic',
+				'avi'	=> 'video/x-msvideo',
+				'bcpio'	=> 'application/x-bcpio',
+				'bin'	=> 'application/octet-stream',
+				'bmp'	=> 'image/bmp',
+				'c'	=> 'text/plain', // or 'text/x-csrc', //added by skwashd
+				'cc'	=> 'text/plain', // or 'text/x-c++src', //added by skwashd
+				'cs'	=> 'text/plain', //added by skwashd - for C# src
+				'cpp'	=> 'text/x-c++src', //added by skwashd
+				'cxx'	=> 'text/x-c++src', //added by skwashd
+				'cdf'	=> 'application/x-netcdf',
+				'class'	=> 'application/octet-stream',//secure but application/java-class is correct
+				'com'	=> 'application/octet-stream',//added by skwashd
+				'cpio'	=> 'application/x-cpio',
+				'cpt'	=> 'application/mac-compactpro',
+				'csh'	=> 'application/x-csh',
+				'css'	=> 'text/css',
+				'csv'	=> 'text/comma-separated-values',//added by skwashd
+				'dcr'	=> 'application/x-director',
+				'diff'	=> 'text/diff',
+				'dir'	=> 'application/x-director',
+				'dll'	=> 'application/octet-stream',
+				'dms'	=> 'application/octet-stream',
+				'doc'	=> 'application/msword',
+				'dot'	=> 'application/msword',//added by skwashd
+				'dvi'	=> 'application/x-dvi',
+				'dxr'	=> 'application/x-director',
+				'eps'	=> 'application/postscript',
+				'etx'	=> 'text/x-setext',
+				'exe'	=> 'application/octet-stream',
+				'ez'	=> 'application/andrew-inset',
+				'gif'	=> 'image/gif',
+				'gtar'	=> 'application/x-gtar',
+				'gz'	=> 'application/x-gzip',
+				'h'	=> 'text/plain', // or 'text/x-chdr',//added by skwashd
+				'h++'	=> 'text/plain', // or 'text/x-c++hdr', //added by skwashd
+				'hh'	=> 'text/plain', // or 'text/x-c++hdr', //added by skwashd
+				'hpp'	=> 'text/plain', // or 'text/x-c++hdr', //added by skwashd
+				'hxx'	=> 'text/plain', // or 'text/x-c++hdr', //added by skwashd
+				'hdf'	=> 'application/x-hdf',
+				'hqx'	=> 'application/mac-binhex40',
+				'htm'	=> 'text/html',
+				'html'	=> 'text/html',
+				'ice'	=> 'x-conference/x-cooltalk',
+				'ics'	=> 'text/calendar',
+				'ief'	=> 'image/ief',
+				'ifb'	=> 'text/calendar',
+				'iges'	=> 'model/iges',
+				'igs'	=> 'model/iges',
+				'jar'	=> 'application/x-jar', //added by skwashd - alternative mime type
+				'java'	=> 'text/x-java-source', //added by skwashd
+				'jpe'	=> 'image/jpeg',
+				'jpeg'	=> 'image/jpeg',
+				'jpg'	=> 'image/jpeg',
+				'js'	=> 'application/x-javascript',
+				'kar'	=> 'audio/midi',
+				'latex'	=> 'application/x-latex',
+				'lha'	=> 'application/octet-stream',
+				'log'	=> 'text/plain',
+				'lzh'	=> 'application/octet-stream',
+				'm3u'	=> 'audio/x-mpegurl',
+				'man'	=> 'application/x-troff-man',
+				'me'	=> 'application/x-troff-me',
+				'mesh'	=> 'model/mesh',
+				'mid'	=> 'audio/midi',
+				'midi'	=> 'audio/midi',
+				'mif'	=> 'application/vnd.mif',
+				'mov'	=> 'video/quicktime',
+				'movie'	=> 'video/x-sgi-movie',
+				'mp2'	=> 'audio/mpeg',
+				'mp3'	=> 'audio/mpeg',
+				'mpe'	=> 'video/mpeg',
+				'mpeg'	=> 'video/mpeg',
+				'mpg'	=> 'video/mpeg',
+				'mpga'	=> 'audio/mpeg',
+				'ms'	=> 'application/x-troff-ms',
+				'msh'	=> 'model/mesh',
+				'mxu'	=> 'video/vnd.mpegurl',
+				'nc'	=> 'application/x-netcdf',
+				'oda'	=> 'application/oda',
+				'patch'	=> 'text/diff',
+				'pbm'	=> 'image/x-portable-bitmap',
+				'pdb'	=> 'chemical/x-pdb',
+				'pdf'	=> 'application/pdf',
+				'pgm'	=> 'image/x-portable-graymap',
+				'pgn'	=> 'application/x-chess-pgn',
+				'pgp'	=> 'application/pgp',//added by skwashd
+				'php'	=> 'application/x-httpd-php',
+				'php3'	=> 'application/x-httpd-php3',
+				'pl'	=> 'application/x-perl',
+				'pm'	=> 'application/x-perl',
+				'png'	=> 'image/png',
+				'pnm'	=> 'image/x-portable-anymap',
+				'po'	=> 'text/plain',
+				'ppm'	=> 'image/x-portable-pixmap',
+				'ppt'	=> 'application/vnd.ms-powerpoint',
+				'ps'	=> 'application/postscript',
+				'qt'	=> 'video/quicktime',
+				'ra'	=> 'audio/x-realaudio',
+				'rar'=>'application/octet-stream',
+				'ram'	=> 'audio/x-pn-realaudio',
+				'ras'	=> 'image/x-cmu-raster',
+				'rgb'	=> 'image/x-rgb',
+				'rm'	=> 'audio/x-pn-realaudio',
+				'roff'	=> 'application/x-troff',
+				'rpm'	=> 'audio/x-pn-realaudio-plugin',
+				'rtf'	=> 'text/rtf',
+				'rtx'	=> 'text/richtext',
+				'sgm'	=> 'text/sgml',
+				'sgml'	=> 'text/sgml',
+				'sh'	=> 'application/x-sh',
+				'shar'	=> 'application/x-shar',
+				'shtml'	=> 'text/html',
+				'silo'	=> 'model/mesh',
+				'sit'	=> 'application/x-stuffit',
+				'skd'	=> 'application/x-koan',
+				'skm'	=> 'application/x-koan',
+				'skp'	=> 'application/x-koan',
+				'skt'	=> 'application/x-koan',
+				'smi'	=> 'application/smil',
+				'smil'	=> 'application/smil',
+				'snd'	=> 'audio/basic',
+				'so'	=> 'application/octet-stream',
+				'spl'	=> 'application/x-futuresplash',
+				'src'	=> 'application/x-wais-source',
+				'stc'	=> 'application/vnd.sun.xml.calc.template',
+				'std'	=> 'application/vnd.sun.xml.draw.template',
+				'sti'	=> 'application/vnd.sun.xml.impress.template',
+				'stw'	=> 'application/vnd.sun.xml.writer.template',
+				'sv4cpio'	=> 'application/x-sv4cpio',
+				'sv4crc'	=> 'application/x-sv4crc',
+				'swf'	=> 'application/x-shockwave-flash',
+				'sxc'	=> 'application/vnd.sun.xml.calc',
+				'sxd'	=> 'application/vnd.sun.xml.draw',
+				'sxg'	=> 'application/vnd.sun.xml.writer.global',
+				'sxi'	=> 'application/vnd.sun.xml.impress',
+				'sxm'	=> 'application/vnd.sun.xml.math',
+				'sxw'	=> 'application/vnd.sun.xml.writer',
+				't'	=> 'application/x-troff',
+				'tar'	=> 'application/x-tar',
+				'tcl'	=> 'application/x-tcl',
+				'tex'	=> 'application/x-tex',
+				'texi'	=> 'application/x-texinfo',
+				'texinfo'	=> 'application/x-texinfo',
+				'tgz'	=> 'application/x-gtar',
+				'tif'	=> 'image/tiff',
+				'tiff'	=> 'image/tiff',
+				'tr'	=> 'application/x-troff',
+				'tsv'	=> 'text/tab-separated-values',
+				'txt'	=> 'text/plain',
+				'ustar'	=> 'application/x-ustar',
+				'vbs'	=> 'text/plain', //added by skwashd - for obvious reasons
+				'vcd'	=> 'application/x-cdlink',
+				'vcf'	=> 'text/x-vcard',
+				'vcs'	=> 'text/calendar',
+				'vfb'	=> 'text/calendar',
+				'vrml'	=> 'model/vrml',
+				'vsd'	=> 'application/vnd.visio',
+				'wav'	=> 'audio/x-wav',
+				'wax'	=> 'audio/x-ms-wax',
+				'wbmp'	=> 'image/vnd.wap.wbmp',
+				'wbxml'	=> 'application/vnd.wap.wbxml',
+				'wm'	=> 'video/x-ms-wm',
+				'wma'	=> 'audio/x-ms-wma',
+				'wmd'	=> 'application/x-ms-wmd',
+				'wml'	=> 'text/vnd.wap.wml',
+				'wmlc'	=> 'application/vnd.wap.wmlc',
+				'wmls'	=> 'text/vnd.wap.wmlscript',
+				'wmlsc'	=> 'application/vnd.wap.wmlscriptc',
+				'wmv'	=> 'video/x-ms-wmv',
+				'wmx'	=> 'video/x-ms-wmx',
+				'wmz'	=> 'application/x-ms-wmz',
+				'wrl'	=> 'model/vrml',
+				'wvx'	=> 'video/x-ms-wvx',
+				'xbm'	=> 'image/x-xbitmap',
+				'xht'	=> 'application/xhtml+xml',
+				'xhtml'	=> 'application/xhtml+xml',
+				'xls'	=> 'application/vnd.ms-excel',
+				'xlt'	=> 'application/vnd.ms-excel',
+				'xml'	=> 'application/xml',
+				'xpm'	=> 'image/x-xpixmap',
+				'xsl'	=> 'text/xml',
+				'xwd'	=> 'image/x-xwindowdump',
+				'xyz'	=> 'chemical/x-xyz',
+				'z'	=> 'application/x-compress',
+				'zip'	=> 'application/zip',
+       );
+       $type = strtolower(substr(strrchr($filename, '.'),1));
+       if(isset($contentType[$type])) {
+            $mime = $contentType[$type];
+       }else {
+       	    $mime = 'application/octet-stream';
+       }
+       return $mime;
+    }
+}
+
+if(!function_exists('image_type_to_extension')){
+   function image_type_to_extension($imagetype) {
+       if(empty($imagetype)) return false;
+       switch($imagetype) {
+           case IMAGETYPE_GIF    : return '.gif';
+           case IMAGETYPE_JPEG    : return '.jpg';
+           case IMAGETYPE_PNG    : return '.png';
+           case IMAGETYPE_SWF    : return '.swf';
+           case IMAGETYPE_PSD    : return '.psd';
+           case IMAGETYPE_BMP    : return '.bmp';
+           case IMAGETYPE_TIFF_II : return '.tiff';
+           case IMAGETYPE_TIFF_MM : return '.tiff';
+           case IMAGETYPE_JPC    : return '.jpc';
+           case IMAGETYPE_JP2    : return '.jp2';
+           case IMAGETYPE_JPX    : return '.jpf';
+           case IMAGETYPE_JB2    : return '.jb2';
+           case IMAGETYPE_SWC    : return '.swc';
+           case IMAGETYPE_IFF    : return '.aiff';
+           case IMAGETYPE_WBMP    : return '.wbmp';
+           case IMAGETYPE_XBM    : return '.xbm';
+           default                : return false;
+       }
+   }
+
+}

+ 756 - 0
Ainaphp/Lib/ORG/Image.class.php

@@ -0,0 +1,756 @@
+<?php
+
+/**
+ +------------------------------------------------------------------------------
+ * 图像操作类库
+ +------------------------------------------------------------------------------
+ * @category   ORG
+ * @package  ORG
+ * @subpackage  Util
+ * @author    liu21st <liu21st@gmail.com>
+ * @version   $Id$
+ +------------------------------------------------------------------------------
+ */
+class Image extends Think
+{//类定义开始
+
+    /**
+     +----------------------------------------------------------
+     * 取得图像信息
+     *
+     +----------------------------------------------------------
+     * @static
+     * @access public
+     +----------------------------------------------------------
+     * @param string $image 图像文件名
+     +----------------------------------------------------------
+     * @return mixed
+     +----------------------------------------------------------
+     */
+    static function getImageInfo($img) {
+        $imageInfo = getimagesize($img);
+        if( $imageInfo!== false) {
+            $imageType = strtolower(substr(image_type_to_extension($imageInfo[2]),1));
+            $imageSize = filesize($img);
+            $info = array(
+                "width"=>$imageInfo[0],
+                "height"=>$imageInfo[1],
+                "type"=>$imageType,
+                "size"=>$imageSize,
+                "mime"=>$imageInfo['mime']
+            );
+            return $info;
+        }else {
+            return false;
+        }
+    }
+    /**
+      +----------------------------------------------------------
+     * 为图片添加水印
+      +----------------------------------------------------------
+     * @static public
+      +----------------------------------------------------------
+     * @param string $source 原文件名
+     * @param string $water  水印图片
+     * @param string $$savename  添加水印后的图片名
+     * @param string $alpha  水印的透明度
+      +----------------------------------------------------------
+     * @return string
+      +----------------------------------------------------------
+     * @throws ThinkExecption
+      +----------------------------------------------------------
+     */
+    static public function water($source, $water, $savename=null, $alpha=80) {
+        //检查文件是否存在
+        if (!file_exists($source) || !file_exists($water))
+            return false;
+
+        //图片信息
+        $sInfo = self::getImageInfo($source);
+        $wInfo = self::getImageInfo($water);
+
+        //如果图片小于水印图片,不生成图片
+        if ($sInfo["width"] < $wInfo["width"] || $sInfo['height'] < $wInfo['height'])
+            return false;
+
+        //建立图像
+        $sCreateFun = "imagecreatefrom" . $sInfo['type'];
+        $sImage = $sCreateFun($source);
+        $wCreateFun = "imagecreatefrom" . $wInfo['type'];
+        $wImage = $wCreateFun($water);
+
+        //设定图像的混色模式
+        imagealphablending($wImage, true);
+
+        //图像位置,默认为右下角右对齐
+        $posY = $sInfo["height"] - $wInfo["height"];
+        $posX = $sInfo["width"] - $wInfo["width"];
+
+        //生成混合图像
+        imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo['width'], $wInfo['height'], $alpha);
+
+        //输出图像
+        $ImageFun = 'Image' . $sInfo['type'];
+        //如果没有给出保存文件名,默认为原图像名
+        if (!$savename) {
+            $savename = $source;
+            @unlink($source);
+        }
+        //保存图像
+        $ImageFun($sImage, $savename);
+        imagedestroy($sImage);
+    }
+
+	static public  function watermark($source,$target = '',$config ) {
+		$watermarkPadding = $config['watermark_pospadding'];
+		$w_pos = $config['watermark_pos'];
+		if($config['watermark_img'])$w_img = './Public/Images/'.$config['watermark_img'];
+		$w_text = $config['watemard_text'];
+		$w_font =  $config['watemard_text_size'];
+		$w_color =  $config['watemard_text_color'];
+		$fontface =  './Public/Images/font/'.$config['watemard_text_face'];
+
+		$w_pct =   $config['watermark_pct'];
+		$w_quality =  $config['watermark_quality'];
+		$w_minheight =  $config['watemard_text'];
+		$w_minwidth =  $config['watemard_text'];
+		$watermarkPadding = $config['watermark_pospadding'];
+		$w_pos = $config['watermark_pos'];
+
+		$positionPadding = ($watermarkPadding && $watermarkPadding > 0) ? $watermarkPadding : 5; 	// 边距
+
+		$w_pos = $w_pos ? $w_pos : 9;
+		$w_img = $w_img ? $w_img : $w_img;
+		if(!$target) $target = $source;
+
+		$source_info = getimagesize($source);
+		$source_w    = $source_info[0];
+		$source_h    = $source_info[1];
+		if($source_w < $w_minwidth || $source_h < $w_minheight) return false;
+
+		switch($source_info[2]) {
+			case 1 :
+				$source_img = imagecreatefromgif($source);
+				break;
+			case 2 :
+				$source_img = imagecreatefromjpeg($source);
+				break;
+			case 3 :
+				$source_img = imagecreatefrompng($source);
+				break;
+			default :
+				return false;
+		}
+		if(!empty($w_img) && file_exists($w_img)) {
+
+			$ifwaterimage = 1;
+			$water_info   = getimagesize($w_img);
+			$width        = $water_info[0];
+			$height       = $water_info[1];
+			switch($water_info[2]) {
+				case 1 :
+					$water_img = imagecreatefromgif($w_img);
+					break;
+				case 2 :
+					$water_img = imagecreatefromjpeg($w_img);
+					break;
+				case 3 :
+					$water_img = imagecreatefrompng($w_img);
+					break;
+				default :
+					return;
+			}
+		} else {
+
+			$ifwaterimage = 0;
+			$temp = imagettfbbox(ceil($w_font*2.5), 0, $fontface, $w_text);
+			$width = $temp[2] - $temp[6];
+			$height = $temp[3] - $temp[7];
+			unset($temp);
+
+		}
+		switch($w_pos) {
+			case 1:
+				$wx = $positionPadding;
+				$wy = $positionPadding;
+				break;
+			case 2:
+				$wx = ($source_w - $width) / 2;
+				$wy = $positionPadding;
+				break;
+			case 3:
+				$wx = $source_w - $width;
+				$wy = $positionPadding;
+				break;
+			case 4:
+				$wx = $positionPadding;
+				$wy = ($source_h - $height) / 2;
+				break;
+			case 5:
+				$wx = ($source_w - $width) / 2;
+				$wy = ($source_h - $height) / 2;
+				break;
+			case 6:
+				$wx = $source_w - $width - $positionPadding;
+				$wy = ($source_h - $height) / 2;
+				break;
+			case 7:
+				$wx = $positionPadding;
+				$wy = $source_h - $height;
+				break;
+			case 8:
+				$wx = ($source_w - $width) / 2;
+				$wy = $source_h - $height - $positionPadding;
+				break;
+			case 9:
+				$wx = $source_w - $width - $positionPadding;
+				$wy = $source_h - $height - $positionPadding ;
+				break;
+			case 10:
+				$wx = rand(0,($source_w - $width));
+				$wy = rand(0,($source_h - $height));
+				break;
+			default:
+				$wx = rand(0,($source_w - $width));
+				$wy = rand(0,($source_h - $height));
+				break;
+		}
+		if($ifwaterimage) {
+			if($water_info[2] == 3) {
+				imagecopy($source_img, $water_img, $wx, $wy, 0, 0, $width, $height);
+			} else {
+				imagecopymerge($source_img, $water_img, $wx, $wy, 0, 0, $width, $height, $w_pct);
+			}
+		} else {
+			if(!empty($w_color) && (strlen($w_color)==7)) {
+				$r = hexdec(substr($w_color,1,2));
+				$g = hexdec(substr($w_color,3,2));
+				$b = hexdec(substr($w_color,5));
+			} else {
+				return;
+			}
+
+			$black = imagecolorallocate($source_img, $r,$g, $b);//设置颜色
+			imagettftext($source_img, $w_font, 0, $wx, $wy, $black, $fontface, $w_text);//打印水印
+
+		}
+
+		switch($source_info[2]) {
+			case 1 :
+				imagegif($source_img, $target);
+				break;
+			case 2 :
+				imagejpeg($source_img, $target, $w_quality);
+				break;
+			case 3 :
+				imagepng($source_img, $target);
+				break;
+			default :
+				return;
+		}
+
+		if(isset($water_info)) {
+			unset($water_info);
+		}
+		if(isset($water_img)) {
+			imagedestroy($water_img);
+		}
+		unset($source_info);
+		imagedestroy($source_img);
+		return true;
+
+	}
+
+    /**
+     +----------------------------------------------------------
+     * 显示服务器图像文件
+     * 支持URL方式
+     +----------------------------------------------------------
+     * @static
+     * @access public
+     +----------------------------------------------------------
+     * @param string $imgFile 图像文件名
+     * @param string $text 文字字符串
+     * @param string $width 图像宽度
+     * @param string $height 图像高度
+     +----------------------------------------------------------
+     * @return void
+     +----------------------------------------------------------
+     */
+    static function showImg($imgFile,$text='',$width=80,$height=30) {
+        //获取图像文件信息
+        $info = Image::getImageInfo($imgFile);
+        if($info !== false) {
+            $createFun  =   str_replace('/','createfrom',$info['mime']);
+            $im = $createFun($imgFile);
+            if($im) {
+                $ImageFun= str_replace('/','',$info['mime']);
+                if(!empty($text)) {
+                    $tc  = imagecolorallocate($im, 0, 0, 0);
+                    imagestring($im, 3, 5, 5, $text, $tc);
+                }
+                if($info['type']=='png' || $info['type']=='gif') {
+                imagealphablending($im, false);//取消默认的混色模式
+                imagesavealpha($im,true);//设定保存完整的 alpha 通道信息
+                }
+                header("Content-type: ".$info['mime']);
+                $ImageFun($im);
+                imagedestroy($im);
+                return ;
+            }
+        }
+        //获取或者创建图像文件失败则生成空白PNG图片
+        $im  = imagecreatetruecolor($width, $height);
+        $bgc = imagecolorallocate($im, 255, 255, 255);
+        $tc  = imagecolorallocate($im, 0, 0, 0);
+        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
+        imagestring($im, 4, 5, 5, "NO PIC", $tc);
+        Image::output($im);
+        return ;
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 生成缩略图
+     +----------------------------------------------------------
+     * @static
+     * @access public
+     +----------------------------------------------------------
+     * @param string $image  原图
+     * @param string $type 图像格式
+     * @param string $thumbname 缩略图文件名
+     * @param string $maxWidth  宽度
+     * @param string $maxHeight  高度
+     * @param string $position 缩略图保存目录
+     * @param boolean $interlace 启用隔行扫描
+     +----------------------------------------------------------
+     * @return void
+     +----------------------------------------------------------
+     */
+    static function thumb($image,$thumbname,$type='',$maxWidth=200,$maxHeight=50,$interlace=true)
+    {
+        // 获取原图信息
+        $info  = Image::getImageInfo($image);
+         if($info !== false) {
+            $srcWidth  = $info['width'];
+            $srcHeight = $info['height'];
+            $type = empty($type)?$info['type']:$type;
+			$type = strtolower($type);
+            $interlace  =  $interlace? 1:0;
+            unset($info);
+            $scale = min($maxWidth/$srcWidth, $maxHeight/$srcHeight); // 计算缩放比例
+            if($scale>=1) {
+                // 超过原图大小不再缩略
+                $width   =  $srcWidth;
+                $height  =  $srcHeight;
+            }else{
+                // 缩略图尺寸
+                $width  = (int)($srcWidth*$scale);
+                $height = (int)($srcHeight*$scale);
+            }
+
+
+            // 载入原图
+            $createFun = 'ImageCreateFrom'.($type=='jpg'?'jpeg':$type);
+            $srcImg     = $createFun($image);
+
+            //创建缩略图
+            if($type!='gif' && function_exists('imagecreatetruecolor'))
+                $thumbImg = imagecreatetruecolor($width, $height);
+            else
+                $thumbImg = imagecreate($width, $height);
+
+            // 复制图片
+            if(function_exists("ImageCopyResampled"))
+                imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth,$srcHeight);
+            else
+                imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height,  $srcWidth,$srcHeight);
+            if('gif'==$type || 'png'==$type) {
+                //imagealphablending($thumbImg, false);//取消默认的混色模式
+                //imagesavealpha($thumbImg,true);//设定保存完整的 alpha 通道信息
+                $background_color  =  imagecolorallocate($thumbImg,  0,255,0);  //  指派一个绿色
+				imagecolortransparent($thumbImg,$background_color);  //  设置为透明色,若注释掉该行则输出绿色的图
+            }
+
+            // 对jpeg图形设置隔行扫描
+            if('jpg'==$type || 'jpeg'==$type) 	imageinterlace($thumbImg,$interlace);
+
+            //$gray=ImageColorAllocate($thumbImg,255,0,0);
+            //ImageString($thumbImg,2,5,5,"ThinkPHP",$gray);
+            // 生成图片
+           // $imageFun = 'image'.($type=='jpg'?'jpeg':$type);
+            //$imageFun($thumbImg,$thumbname);
+
+			if($type=='jpg' || $type=='jpeg')
+			{
+				imagejpeg($thumbImg,$thumbname, 100);
+			}
+			else
+			{
+				 $imageFun = 'image'.$type;
+				 $imageFun($thumbImg,$thumbname);
+			}
+            imagedestroy($thumbImg);
+            imagedestroy($srcImg);
+            return $thumbname;
+         }
+         return false;
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 根据给定的字符串生成图像
+     +----------------------------------------------------------
+     * @static
+     * @access public
+     +----------------------------------------------------------
+     * @param string $string  字符串
+     * @param string $size  图像大小 width,height 或者 array(width,height)
+     * @param string $font  字体信息 fontface,fontsize 或者 array(fontface,fontsize)
+     * @param string $type 图像格式 默认PNG
+     * @param integer $disturb 是否干扰 1 点干扰 2 线干扰 3 复合干扰 0 无干扰
+	 * @param bool $border  是否加边框 array(color)
+     +----------------------------------------------------------
+     * @return string
+     +----------------------------------------------------------
+     */
+	static function buildString($string,$rgb=array(),$filename='',$type='png',$disturb=1,$border=true) {
+		if(is_string($size))		$size	=	explode(',',$size);
+		$width	=	$size[0];
+		$height	=	$size[1];
+		if(is_string($font))		$font	=	explode(',',$font);
+		$fontface	=	$font[0];
+		$fontsize	 	=	$font[1];
+		$length		=	strlen($string);
+        $width = ($length*9+10)>$width?$length*9+10:$width;
+		$height	=	22;
+        if ( $type!='gif' && function_exists('imagecreatetruecolor')) {
+            $im = @imagecreatetruecolor($width,$height);
+        }else {
+            $im = @imagecreate($width,$height);
+        }
+		if(empty($rgb)) {
+			$color = imagecolorallocate($im, 102, 104, 104);
+		}else{
+			$color = imagecolorallocate($im, $rgb[0], $rgb[1], $rgb[2]);
+		}
+        $backColor = imagecolorallocate($im, 255,255,255);    //背景色(随机)
+		$borderColor = imagecolorallocate($im, 100, 100, 100);                    //边框色
+        $pointColor = imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));                 //点颜色
+
+        @imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
+        @imagerectangle($im, 0, 0, $width-1, $height-1, $borderColor);
+        @imagestring($im, 5, 5, 3, $string, $color);
+		if(!empty($disturb)) {
+			// 添加干扰
+			if($disturb=1 || $disturb=3) {
+				for($i=0;$i<25;$i++){
+					imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$pointColor);
+				}
+			}elseif($disturb=2 || $disturb=3){
+				for($i=0;$i<10;$i++){
+					imagearc($im,mt_rand(-10,$width),mt_rand(-10,$height),mt_rand(30,300),mt_rand(20,200),55,44,$pointColor);
+				}
+			}
+		}
+        Image::output($im,$type,$filename);
+	}
+
+    /**
+     +----------------------------------------------------------
+     * 生成图像验证码
+     +----------------------------------------------------------
+     * @static
+     * @access public
+     +----------------------------------------------------------
+     * @param string $length  位数
+     * @param string $mode  类型
+     * @param string $type 图像格式
+     * @param string $width  宽度
+     * @param string $height  高度
+     +----------------------------------------------------------
+     * @return string
+     +----------------------------------------------------------
+     */
+    static function buildImageVerify($length=4,$mode=1,$type='png',$width=48,$height=22,$verifyName='verify')
+    {
+		import('@.ORG.String');
+        $randval = String::rand_string($length,$mode);
+        $_SESSION[$verifyName]= md5($randval);
+        $width = ($length*10+10)>$width?$length*10+10:$width;
+        if ( $type!='gif' && function_exists('imagecreatetruecolor')) {
+            $im = @imagecreatetruecolor($width,$height);
+        }else {
+            $im = @imagecreate($width,$height);
+        }
+        $r = Array(225,255,255,223);
+        $g = Array(225,236,237,255);
+        $b = Array(225,236,166,125);
+        $key = mt_rand(0,3);
+
+        $backColor = imagecolorallocate($im, $r[$key],$g[$key],$b[$key]);    //背景色(随机)
+		$borderColor = imagecolorallocate($im, 100, 100, 100);                    //边框色
+        $pointColor = imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));                 //点颜色
+
+        @imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
+        @imagerectangle($im, 0, 0, $width-1, $height-1, $borderColor);
+        $stringColor = imagecolorallocate($im,mt_rand(0,200),mt_rand(0,120),mt_rand(0,120));
+		// 干扰
+		for($i=0;$i<10;$i++){
+			$fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
+			imagearc($im,mt_rand(-10,$width),mt_rand(-10,$height),mt_rand(30,300),mt_rand(20,200),55,44,$fontcolor);
+		}
+		for($i=0;$i<25;$i++){
+			$fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
+			imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$pointColor);
+		}
+		for($i=0;$i<$length;$i++) {
+			imagestring($im,5,$i*10+5,mt_rand(1,8),$randval{$i}, $stringColor);
+		}
+//        @imagestring($im, 5, 5, 3, $randval, $stringColor);
+        Image::output($im,$type);
+    }
+
+	// 中文验证码
+	static function GBVerify($length=4,$type='png',$width=180,$height=50,$fontface='simhei.ttf',$verifyName='verify') {
+		$code	=	rand_string($length,4);
+        $width = ($length*45)>$width?$length*45:$width;
+		$_SESSION[$verifyName]= md5($code);
+		$im=imagecreatetruecolor($width,$height);
+		$borderColor = imagecolorallocate($im, 100, 100, 100);                    //边框色
+		$bkcolor=imagecolorallocate($im,250,250,250);
+		imagefill($im,0,0,$bkcolor);
+        @imagerectangle($im, 0, 0, $width-1, $height-1, $borderColor);
+		// 干扰
+		for($i=0;$i<15;$i++){
+			$fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
+			imagearc($im,mt_rand(-10,$width),mt_rand(-10,$height),mt_rand(30,300),mt_rand(20,200),55,44,$fontcolor);
+		}
+		for($i=0;$i<255;$i++){
+			$fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
+			imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$fontcolor);
+		}
+		if(!is_file($fontface)) {
+			$fontface = dirname(__FILE__)."/".$fontface;
+		}
+		for($i=0;$i<$length;$i++){
+			$fontcolor=imagecolorallocate($im,mt_rand(0,120),mt_rand(0,120),mt_rand(0,120)); //这样保证随机出来的颜色较深。
+			$codex= msubstr($code,$i,1);
+			imagettftext($im,mt_rand(16,20),mt_rand(-60,60),40*$i+20,mt_rand(30,35),$fontcolor,$fontface,$codex);
+		}
+		Image::output($im,$type);
+	}
+
+    /**
+     +----------------------------------------------------------
+     * 把图像转换成字符显示
+     +----------------------------------------------------------
+     * @static
+     * @access public
+     +----------------------------------------------------------
+     * @param string $image  要显示的图像
+     * @param string $type  图像类型,默认自动获取
+     +----------------------------------------------------------
+     * @return string
+     +----------------------------------------------------------
+     */
+    static function showASCIIImg($image,$string='',$type='')
+    {
+        $info  = Image::getImageInfo($image);
+        if($info !== false) {
+            $type = empty($type)?$info['type']:$type;
+            unset($info);
+            // 载入原图
+            $createFun = 'ImageCreateFrom'.($type=='jpg'?'jpeg':$type);
+            $im     = $createFun($image);
+            $dx = imagesx($im);
+            $dy = imagesy($im);
+			$i	=	0;
+            $out   =  '<span style="padding:0px;margin:0;line-height:100%;font-size:1px;">';
+			set_time_limit(0);
+            for($y = 0; $y < $dy; $y++) {
+              for($x=0; $x < $dx; $x++) {
+                  $col = imagecolorat($im, $x, $y);
+                  $rgb = imagecolorsforindex($im,$col);
+				  $str	 =	 empty($string)?'*':$string[$i++];
+                  $out .= sprintf('<span style="margin:0px;color:#%02x%02x%02x">'.$str.'</span>',$rgb['red'],$rgb['green'],$rgb['blue']);
+             }
+             $out .= "<br>\n";
+            }
+            $out .=  '</span>';
+            imagedestroy($im);
+            return $out;
+        }
+        return false;
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 生成高级图像验证码
+     +----------------------------------------------------------
+     * @static
+     * @access public
+     +----------------------------------------------------------
+     * @param string $type 图像格式
+     * @param string $width  宽度
+     * @param string $height  高度
+     +----------------------------------------------------------
+     * @return string
+     +----------------------------------------------------------
+     */
+    static function showAdvVerify($type='png',$width=180,$height=40)
+    {
+		$rand	=	range('a','z');
+		shuffle($rand);
+		$verifyCode	=	array_slice($rand,0,10);
+        $letter = implode(" ",$verifyCode);
+        $_SESSION['verifyCode'] = $verifyCode;
+        $im = imagecreate($width,$height);
+        $r = array(225,255,255,223);
+        $g = array(225,236,237,255);
+        $b = array(225,236,166,125);
+        $key = mt_rand(0,3);
+        $backColor = imagecolorallocate($im, $r[$key],$g[$key],$b[$key]);
+		$borderColor = imagecolorallocate($im, 100, 100, 100);                    //边框色
+        imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
+        imagerectangle($im, 0, 0, $width-1, $height-1, $borderColor);
+        $numberColor = imagecolorallocate($im, 255,rand(0,100), rand(0,100));
+        $stringColor = imagecolorallocate($im, rand(0,100), rand(0,100), 255);
+		// 添加干扰
+		/*
+		for($i=0;$i<10;$i++){
+			$fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
+			imagearc($im,mt_rand(-10,$width),mt_rand(-10,$height),mt_rand(30,300),mt_rand(20,200),55,44,$fontcolor);
+		}
+		for($i=0;$i<255;$i++){
+			$fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
+			imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$fontcolor);
+		}*/
+        imagestring($im, 5, 5, 1, "0 1 2 3 4 5 6 7 8 9", $numberColor);
+        imagestring($im, 5, 5, 20, $letter, $stringColor);
+        Image::output($im,$type);
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 生成UPC-A条形码
+     +----------------------------------------------------------
+     * @static
+     +----------------------------------------------------------
+     * @param string $type 图像格式
+     * @param string $type 图像格式
+     * @param string $lw  单元宽度
+     * @param string $hi   条码高度
+     +----------------------------------------------------------
+     * @return string
+     +----------------------------------------------------------
+     */
+    static function UPCA($code,$type='png',$lw=2,$hi=100) {
+        static $Lencode = array('0001101','0011001','0010011','0111101','0100011',
+                         '0110001','0101111','0111011','0110111','0001011');
+        static $Rencode = array('1110010','1100110','1101100','1000010','1011100',
+                         '1001110','1010000','1000100','1001000','1110100');
+        $ends = '101';
+        $center = '01010';
+        /* UPC-A Must be 11 digits, we compute the checksum. */
+        if ( strlen($code) != 11 ) { die("UPC-A Must be 11 digits."); }
+        /* Compute the EAN-13 Checksum digit */
+        $ncode = '0'.$code;
+        $even = 0; $odd = 0;
+        for ($x=0;$x<12;$x++) {
+          if ($x % 2) { $odd += $ncode[$x]; } else { $even += $ncode[$x]; }
+        }
+        $code.=(10 - (($odd * 3 + $even) % 10)) % 10;
+        /* Create the bar encoding using a binary string */
+        $bars=$ends;
+        $bars.=$Lencode[$code[0]];
+        for($x=1;$x<6;$x++) {
+          $bars.=$Lencode[$code[$x]];
+        }
+        $bars.=$center;
+        for($x=6;$x<12;$x++) {
+          $bars.=$Rencode[$code[$x]];
+        }
+        $bars.=$ends;
+        /* Generate the Barcode Image */
+        if ( $type!='gif' && function_exists('imagecreatetruecolor')) {
+            $im = imagecreatetruecolor($lw*95+30,$hi+30);
+        }else {
+            $im = imagecreate($lw*95+30,$hi+30);
+        }
+        $fg = ImageColorAllocate($im, 0, 0, 0);
+        $bg = ImageColorAllocate($im, 255, 255, 255);
+        ImageFilledRectangle($im, 0, 0, $lw*95+30, $hi+30, $bg);
+        $shift=10;
+        for ($x=0;$x<strlen($bars);$x++) {
+          if (($x<10) || ($x>=45 && $x<50) || ($x >=85)) { $sh=10; } else { $sh=0; }
+          if ($bars[$x] == '1') { $color = $fg; } else { $color = $bg; }
+          ImageFilledRectangle($im, ($x*$lw)+15,5,($x+1)*$lw+14,$hi+5+$sh,$color);
+        }
+        /* Add the Human Readable Label */
+        ImageString($im,4,5,$hi-5,$code[0],$fg);
+        for ($x=0;$x<5;$x++) {
+          ImageString($im,5,$lw*(13+$x*6)+15,$hi+5,$code[$x+1],$fg);
+          ImageString($im,5,$lw*(53+$x*6)+15,$hi+5,$code[$x+6],$fg);
+        }
+        ImageString($im,4,$lw*95+17,$hi-5,$code[11],$fg);
+        /* Output the Header and Content. */
+        Image::output($im,$type);
+    }
+
+	// 生成手机号码
+	static public function buildPhone() {
+	}
+	// 生成邮箱图片
+	static public function buildEmail($email,$rgb=array(),$filename='',$type='png') {
+		$mail		=	explode('@',$email);
+		$user		=	trim($mail[0]);
+		$mail		=	strtolower(trim($mail[1]));
+		$path		=	dirname(__FILE__).'/Mail/';
+		if(is_file($path.$mail.'.png')) {
+			$im	= imagecreatefrompng($path.$mail.'.png');
+			$user_width = imagettfbbox(9, 0, dirname(__FILE__)."/Mail/tahoma.ttf", $user);
+			$x_value = (200 - ($user_width[2] + 113));
+			if(empty($rgb)) {
+				$color = imagecolorallocate($im, 102, 104, 104);
+			}else{
+				$color = imagecolorallocate($im, $rgb[0], $rgb[1], $rgb[2]);
+			}
+			imagettftext($im, 9, 0, $x_value, 16, $color, dirname(__FILE__)."/Mail/tahoma.ttf", $user);
+		}else{
+			$user_width = imagettfbbox(9, 0, dirname(__FILE__)."/Mail/tahoma.ttf", $email);
+			$width	=	$user_width[2]+15;
+			$height	=	20;
+			$im	=	imagecreate($width,20);
+			$backColor = imagecolorallocate($im, 255,255,255);    //背景色(随机)
+			$borderColor = imagecolorallocate($im, 100, 100, 100);                    //边框色
+			$pointColor = imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));                 //点颜色
+			imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
+			imagerectangle($im, 0, 0, $width-1, $height-1, $borderColor);
+			if(empty($rgb)) {
+				$color = imagecolorallocate($im, 102, 104, 104);
+			}else{
+				$color = imagecolorallocate($im, $rgb[0], $rgb[1], $rgb[2]);
+			}
+			imagettftext($im, 9, 0, 5, 16, $color, dirname(__FILE__)."/Mail/tahoma.ttf", $email);
+			for($i=0;$i<25;$i++){
+				imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$pointColor);
+			}
+		}
+		Image::output($im,$type,$filename);
+	}
+
+    static function output($im,$type='png',$filename='')
+    {
+        header("Content-type: image/".$type);
+        $ImageFun='image'.$type;
+		if(empty($filename)) {
+	        $ImageFun($im);
+		}else{
+	        $ImageFun($im,$filename);
+		}
+        imagedestroy($im);
+    }
+
+}//类定义结束
+?>

+ 63 - 0
Ainaphp/Lib/ORG/Online.class.php

@@ -0,0 +1,63 @@
+<?php
+class Online extends Think {
+
+   protected $lifeTime='1800' ,$sessionid='' ,$dao;
+
+
+   public function __construct(&$params='') {
+		$this->lifeTime = C('EXPIRE_TIME') ?  C('EXPIRE_TIME') : 1800;
+
+		if(cookie('onlineid')){
+			$this->sessionid = cookie('onlineid');
+		}else{
+			$this->sessionid = substr(MD5(session_id()), 0, 32);
+			cookie('onlineid',$this->sessionid,0);
+		}
+		$this->dao = M('Online');
+        //session_set_save_handler(array(&$this,'open'), array(&$this,'close'), array(&$this,'read'), array(&$this,'write'), array(&$this,'destroy'), array(&$this,'gc'));
+
+		$this->write($this->sessionid);
+		$this->gc($this->lifeTime);
+    }
+
+    public function open($savePath, $sessName) {
+       return true;
+    }
+
+   public function close() {
+	   return $this->gc($this->lifetime);
+   }
+
+   public function read($sessID) {
+	   $r = $this->dao->find($sessID);
+		return $r ? $r['data'] : '';
+   }
+
+   public function write($sessID,$sessData) {
+		$ip = get_client_ip();
+		$username = cookie('username') ? cookie('username') : '';
+		$groupid = cookie('groupid') ? intval(cookie('groupid')) : 4;
+		$sessiondata = array(
+							'sessionid'=>$sessID,
+							'userid'=>intval(cookie('userid')),
+							'username'=>$username,
+							'ip'=>$ip,
+							'lastvisit'=>time(),
+							'groupid'=> $groupid,
+							'data'=> '',
+		);
+		return $this->dao->add($sessiondata,'',true);
+   }
+
+
+   public function destroy($sessID) {
+	   return $this->dao->delete($this->sessionid);
+   }
+
+   public function gc($sessMaxLifeTime) {
+	   $expiretime = time() -$sessMaxLifeTime;
+		$r =  $this->dao->where(" lastvisit < $expiretime")->delete();
+		return $r;
+   }
+
+}

+ 2674 - 0
Ainaphp/Lib/ORG/PHPMailer.class.php

@@ -0,0 +1,2674 @@
+<?php
+/*~ class.phpmailer.php
+.---------------------------------------------------------------------------.
+|  Software: PHPMailer - PHP email class                                    |
+|   Version: 5.2.2                                                          |
+|      Site: https://code.google.com/a/apache-extras.org/p/phpmailer/       |
+| ------------------------------------------------------------------------- |
+|     Admin: Jim Jagielski (project admininistrator)                        |
+|   Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
+|          : Marcus Bointon (coolbru) coolbru@users.sourceforge.net         |
+|          : Jim Jagielski (jimjag) jimjag@gmail.com                        |
+|   Founder: Brent R. Matzelle (original founder)                           |
+| Copyright (c) 2010-2012, Jim Jagielski. All Rights Reserved.              |
+| Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved.               |
+| Copyright (c) 2001-2003, Brent R. Matzelle                                |
+| ------------------------------------------------------------------------- |
+|   License: Distributed under the Lesser General Public License (LGPL)     |
+|            http://www.gnu.org/copyleft/lesser.html                        |
+| This program is distributed in the hope that it will be useful - WITHOUT  |
+| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or     |
+| FITNESS FOR A PARTICULAR PURPOSE.                                         |
+'---------------------------------------------------------------------------'
+*/
+
+/**
+ * PHPMailer - PHP email transport class
+ * NOTE: Requires PHP version 5 or later
+ * @package PHPMailer
+ * @author Andy Prevost
+ * @author Marcus Bointon
+ * @author Jim Jagielski
+ * @copyright 2010 - 2012 Jim Jagielski
+ * @copyright 2004 - 2009 Andy Prevost
+ * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
+ */
+
+
+if (version_compare(PHP_VERSION, '5.0.0', '<') ) exit("Sorry, this version of PHPMailer will only run on PHP version 5 or greater!\n");
+
+/**
+ * Main PHPMailer class definition
+ */
+class PHPMailer {
+
+  /////////////////////////////////////////////////
+  // PROPERTIES, PUBLIC
+  /////////////////////////////////////////////////
+
+  /**
+   * Email priority (1 = High, 3 = Normal, 5 = low).
+   * @var int
+   */
+  public $Priority          = 3;
+
+  /**
+   * Sets the CharSet of the message.
+   * @var string
+   */
+  public $CharSet           = 'iso-8859-1';
+
+  /**
+   * Sets the Content-type of the message.
+   * @var string
+   */
+  public $ContentType       = 'text/plain';
+
+  /**
+   * Sets the Encoding of the message. Options for this are
+   *  "8bit", "7bit", "binary", "base64", and "quoted-printable".
+   * @var string
+   */
+  public $Encoding          = '8bit';
+
+  /**
+   * Holds the most recent mailer error message.
+   * @var string
+   */
+  public $ErrorInfo         = '';
+
+  /**
+   * Sets the From email address for the message.
+   * @var string
+   */
+  public $From              = 'root@localhost';
+
+  /**
+   * Sets the From name of the message.
+   * @var string
+   */
+  public $FromName          = 'Root User';
+
+  /**
+   * Sets the Sender email of the message.  If not empty,
+   * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
+   * If not empty, and ReturnPath is empty, will also be the
+   * Return-Path header.
+   * @var string
+   */
+  public $Sender            = '';
+
+  /**
+   * Sets the Return-Path of the message.  If empty, it will
+   * be set to either From or Sender.
+   * @var string
+   */
+  public $ReturnPath        = '';
+
+  /**
+   * Sets the Subject of the message.
+   * @var string
+   */
+  public $Subject           = '';
+
+  /**
+   * Sets the Body of the message.  This can be either an HTML or text body.
+   * If HTML then run IsHTML(true).
+   * @var string
+   */
+  public $Body              = '';
+
+  /**
+   * Sets the text-only body of the message.  This automatically sets the
+   * email to multipart/alternative.  This body can be read by mail
+   * clients that do not have HTML email capability such as mutt. Clients
+   * that can read HTML will view the normal Body.
+   * @var string
+   */
+  public $AltBody           = '';
+
+  /**
+   * Stores the complete compiled MIME message body.
+   * @var string
+   * @access protected
+   */
+  protected $MIMEBody       = '';
+
+  /**
+   * Stores the complete compiled MIME message headers.
+   * @var string
+   * @access protected
+   */
+  protected $MIMEHeader     = '';
+
+  /**
+   * Stores the extra header list which CreateHeader() doesn't fold in
+   * @var string
+   * @access protected
+  */
+  protected $mailHeader     = '';
+
+  /**
+   * Sets word wrapping on the body of the message to a given number of
+   * characters.
+   * @var int
+   */
+  public $WordWrap          = 0;
+
+  /**
+   * Method to send mail: ("mail", "sendmail", or "smtp").
+   * @var string
+   */
+  public $Mailer            = 'mail';
+
+  /**
+   * Sets the path of the sendmail program.
+   * @var string
+   */
+  public $Sendmail          = '/usr/sbin/sendmail';
+
+  /**
+   * Determine if mail() uses a fully sendmail compatible MTA that
+   * supports sendmail's "-oi -f" options
+   * @var boolean
+   */
+  public $UseSendmailOptions	= true;
+
+  /**
+   * Path to PHPMailer plugins.  Useful if the SMTP class
+   * is in a different directory than the PHP include path.
+   * @var string
+   */
+  public $PluginDir         = '';
+
+  /**
+   * Sets the email address that a reading confirmation will be sent.
+   * @var string
+   */
+  public $ConfirmReadingTo  = '';
+
+  /**
+   * Sets the hostname to use in Message-Id and Received headers
+   * and as default HELO string. If empty, the value returned
+   * by SERVER_NAME is used or 'localhost.localdomain'.
+   * @var string
+   */
+  public $Hostname          = '';
+
+  /**
+   * Sets the message ID to be used in the Message-Id header.
+   * If empty, a unique id will be generated.
+   * @var string
+   */
+  public $MessageID         = '';
+
+  /////////////////////////////////////////////////
+  // PROPERTIES FOR SMTP
+  /////////////////////////////////////////////////
+
+  /**
+   * Sets the SMTP hosts.
+   *
+   * All hosts must be separated by a
+   * semicolon.  You can also specify a different port
+   * for each host by using this format: [hostname:port]
+   * (e.g. "smtp1.example.com:25;smtp2.example.com").
+   * Hosts will be tried in order.
+   * @var string
+   */
+  public $Host          = 'localhost';
+
+  /**
+   * Sets the default SMTP server port.
+   * @var int
+   */
+  public $Port          = 25;
+
+  /**
+   * Sets the SMTP HELO of the message (Default is $Hostname).
+   * @var string
+   */
+  public $Helo          = '';
+
+  /**
+   * Sets connection prefix. Options are "", "ssl" or "tls"
+   * @var string
+   */
+  public $SMTPSecure    = '';
+
+  /**
+   * Sets SMTP authentication. Utilizes the Username and Password variables.
+   * @var bool
+   */
+  public $SMTPAuth      = false;
+
+  /**
+   * Sets SMTP username.
+   * @var string
+   */
+  public $Username      = '';
+
+  /**
+   * Sets SMTP password.
+   * @var string
+   */
+  public $Password      = '';
+
+  /**
+   *  Sets SMTP auth type. Options are LOGIN | PLAIN | NTLM  (default LOGIN)
+   *  @var string
+   */
+  public $AuthType      = '';
+
+  /**
+   *  Sets SMTP realm.
+   *  @var string
+   */
+  public $Realm         = '';
+
+  /**
+   *  Sets SMTP workstation.
+   *  @var string
+   */
+  public $Workstation   = '';
+
+  /**
+   * Sets the SMTP server   in seconds.
+   * This function will not work with the win32 version.
+   * @var int
+   */
+  public $Timeout       = 10;
+
+  /**
+   * Sets SMTP class debugging on or off.
+   * @var bool
+   */
+  public $SMTPDebug     = false;
+
+  /**
+   * Sets the function/method to use for debugging output.
+   * Right now we only honor "echo" or "error_log"
+   * @var string
+   */
+  public $Debugoutput     = "echo";
+
+  /**
+   * Prevents the SMTP connection from being closed after each mail
+   * sending.  If this is set to true then to close the connection
+   * requires an explicit call to SmtpClose().
+   * @var bool
+   */
+  public $SMTPKeepAlive = false;
+
+  /**
+   * Provides the ability to have the TO field process individual
+   * emails, instead of sending to entire TO addresses
+   * @var bool
+   */
+  public $SingleTo      = false;
+
+   /**
+   * If SingleTo is true, this provides the array to hold the email addresses
+   * @var bool
+   */
+  public $SingleToArray = array();
+
+ /**
+   * Provides the ability to change the generic line ending
+   * NOTE: The default remains '\n'. We force CRLF where we KNOW
+   *        it must be used via self::CRLF
+   * @var string
+   */
+  public $LE              = "\n";
+
+   /**
+   * Used with DKIM Signing
+   * required parameter if DKIM is enabled
+   *
+   * domain selector example domainkey
+   * @var string
+   */
+  public $DKIM_selector   = '';
+
+  /**
+   * Used with DKIM Signing
+   * required if DKIM is enabled, in format of email address 'you@yourdomain.com' typically used as the source of the email
+   * @var string
+   */
+  public $DKIM_identity   = '';
+
+  /**
+   * Used with DKIM Signing
+   * optional parameter if your private key requires a passphras
+   * @var string
+   */
+  public $DKIM_passphrase   = '';
+
+  /**
+   * Used with DKIM Singing
+   * required if DKIM is enabled, in format of email address 'domain.com'
+   * @var string
+   */
+  public $DKIM_domain     = '';
+
+  /**
+   * Used with DKIM Signing
+   * required if DKIM is enabled, path to private key file
+   * @var string
+   */
+  public $DKIM_private    = '';
+
+  /**
+   * Callback Action function name.
+   * The function that handles the result of the send email action.
+   * It is called out by Send() for each email sent.
+   *
+   * Value can be:
+   * - 'function_name' for function names
+   * - 'Class::Method' for static method calls
+   * - array($object, 'Method') for calling methods on $object
+   * See http://php.net/is_callable manual page for more details.
+   *
+   * Parameters:
+   *   bool    $result        result of the send action
+   *   string  $to            email address of the recipient
+   *   string  $cc            cc email addresses
+   *   string  $bcc           bcc email addresses
+   *   string  $subject       the subject
+   *   string  $body          the email body
+   *   string  $from          email address of sender
+   * @var string
+   */
+  public $action_function = ''; //'callbackAction';
+
+  /**
+   * Sets the PHPMailer Version number
+   * @var string
+   */
+  public $Version         = '5.2.2-rc1';
+
+  /**
+   * What to use in the X-Mailer header
+   * @var string NULL for default, whitespace for None, or actual string to use
+   */
+  public $XMailer         = '';
+
+  /////////////////////////////////////////////////
+  // PROPERTIES, PRIVATE AND PROTECTED
+  /////////////////////////////////////////////////
+
+  protected   $smtp           = NULL;
+  protected   $to             = array();
+  protected   $cc             = array();
+  protected   $bcc            = array();
+  protected   $ReplyTo        = array();
+  protected   $all_recipients = array();
+  protected   $attachment     = array();
+  protected   $CustomHeader   = array();
+  protected   $message_type   = '';
+  protected   $boundary       = array();
+  protected   $language       = array();
+  protected   $error_count    = 0;
+  protected   $sign_cert_file = '';
+  protected   $sign_key_file  = '';
+  protected   $sign_key_pass  = '';
+  protected   $exceptions     = false;
+
+  /////////////////////////////////////////////////
+  // CONSTANTS
+  /////////////////////////////////////////////////
+
+  const STOP_MESSAGE  = 0; // message only, continue processing
+  const STOP_CONTINUE = 1; // message?, likely ok to continue processing
+  const STOP_CRITICAL = 2; // message, plus full stop, critical error reached
+  const CRLF = "\r\n";     // SMTP RFC specified EOL
+
+  /////////////////////////////////////////////////
+  // METHODS, VARIABLES
+  /////////////////////////////////////////////////
+
+  /**
+   * Calls actual mail() function, but in a safe_mode aware fashion
+   * Also, unless sendmail_path points to sendmail (or something that
+   * claims to be sendmail), don't pass params (not a perfect fix,
+   * but it will do)
+   * @param string $to To
+   * @param string $subject Subject
+   * @param string $body Message Body
+   * @param string $header Additional Header(s)
+   * @param string $params Params
+   * @access private
+   * @return bool
+   */
+  private function mail_passthru($to, $subject, $body, $header, $params) {
+    if ( ini_get('safe_mode') || !($this->UseSendmailOptions) ) {
+        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header);
+    } else {
+        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header, $params);
+    }
+    return $rt;
+  }
+
+  /**
+   * Outputs debugging info via user-defined method
+   * @param string $str
+   */
+  private function edebug($str) {
+    if ($this->Debugoutput == "error_log") {
+        error_log($str);
+    } else {
+        echo $str;
+    }
+  }
+
+  /**
+   * Constructor
+   * @param boolean $exceptions Should we throw external exceptions?
+   */
+  public function __construct($exceptions = false) {
+    $this->exceptions = ($exceptions == true);
+  }
+
+  /**
+   * Sets message type to HTML.
+   * @param bool $ishtml
+   * @return void
+   */
+  public function IsHTML($ishtml = true) {
+    if ($ishtml) {
+      $this->ContentType = 'text/html';
+    } else {
+      $this->ContentType = 'text/plain';
+    }
+  }
+
+  /**
+   * Sets Mailer to send message using SMTP.
+   * @return void
+   * @deprecated
+   */
+  public function IsSMTP() {
+    $this->Mailer = 'smtp';
+  }
+
+  /**
+   * Sets Mailer to send message using PHP mail() function.
+   * @return void
+   * @deprecated
+   */
+  public function IsMail() {
+    $this->Mailer = 'mail';
+  }
+
+  /**
+   * Sets Mailer to send message using the $Sendmail program.
+   * @return void
+   * @deprecated
+   */
+  public function IsSendmail() {
+    if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
+      $this->Sendmail = '/var/qmail/bin/sendmail';
+    }
+    $this->Mailer = 'sendmail';
+  }
+
+  /**
+   * Sets Mailer to send message using the qmail MTA.
+   * @return void
+   * @deprecated
+   */
+  public function IsQmail() {
+    if (stristr(ini_get('sendmail_path'), 'qmail')) {
+      $this->Sendmail = '/var/qmail/bin/sendmail';
+    }
+    $this->Mailer = 'sendmail';
+  }
+
+  /////////////////////////////////////////////////
+  // METHODS, RECIPIENTS
+  /////////////////////////////////////////////////
+
+  /**
+   * Adds a "To" address.
+   * @param string $address
+   * @param string $name
+   * @return boolean true on success, false if address already used
+   */
+  public function AddAddress($address, $name = '') {
+    return $this->AddAnAddress('to', $address, $name);
+  }
+
+  /**
+   * Adds a "Cc" address.
+   * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
+   * @param string $address
+   * @param string $name
+   * @return boolean true on success, false if address already used
+   */
+  public function AddCC($address, $name = '') {
+    return $this->AddAnAddress('cc', $address, $name);
+  }
+
+  /**
+   * Adds a "Bcc" address.
+   * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
+   * @param string $address
+   * @param string $name
+   * @return boolean true on success, false if address already used
+   */
+  public function AddBCC($address, $name = '') {
+    return $this->AddAnAddress('bcc', $address, $name);
+  }
+
+  /**
+   * Adds a "Reply-to" address.
+   * @param string $address
+   * @param string $name
+   * @return boolean
+   */
+  public function AddReplyTo($address, $name = '') {
+    return $this->AddAnAddress('Reply-To', $address, $name);
+  }
+
+  /**
+   * Adds an address to one of the recipient arrays
+   * Addresses that have been added already return false, but do not throw exceptions
+   * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
+   * @param string $address The email address to send to
+   * @param string $name
+   * @return boolean true on success, false if address already used or invalid in some way
+   * @access protected
+   */
+  protected function AddAnAddress($kind, $address, $name = '') {
+    if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
+      $this->SetError($this->Lang('Invalid recipient array').': '.$kind);
+      if ($this->exceptions) {
+        throw new phpmailerException('Invalid recipient array: ' . $kind);
+      }
+      if ($this->SMTPDebug) {
+        $this->edebug($this->Lang('Invalid recipient array').': '.$kind);
+      }
+      return false;
+    }
+    $address = trim($address);
+    $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
+    if (!$this->ValidateAddress($address)) {
+      $this->SetError($this->Lang('invalid_address').': '. $address);
+      if ($this->exceptions) {
+        throw new phpmailerException($this->Lang('invalid_address').': '.$address);
+      }
+      if ($this->SMTPDebug) {
+        $this->edebug($this->Lang('invalid_address').': '.$address);
+      }
+      return false;
+    }
+    if ($kind != 'Reply-To') {
+      if (!isset($this->all_recipients[strtolower($address)])) {
+        array_push($this->$kind, array($address, $name));
+        $this->all_recipients[strtolower($address)] = true;
+        return true;
+      }
+    } else {
+      if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
+        $this->ReplyTo[strtolower($address)] = array($address, $name);
+      return true;
+    }
+  }
+  return false;
+}
+
+/**
+ * Set the From and FromName properties
+ * @param string $address
+ * @param string $name
+ * @param int $auto Also set Reply-To and Sender
+ * @return boolean
+ */
+  public function SetFrom($address, $name = '', $auto = 1) {
+    $address = trim($address);
+    $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
+    if (!$this->ValidateAddress($address)) {
+      $this->SetError($this->Lang('invalid_address').': '. $address);
+      if ($this->exceptions) {
+        throw new phpmailerException($this->Lang('invalid_address').': '.$address);
+      }
+      if ($this->SMTPDebug) {
+        $this->edebug($this->Lang('invalid_address').': '.$address);
+      }
+      return false;
+    }
+    $this->From = $address;
+    $this->FromName = $name;
+    if ($auto) {
+      if (empty($this->ReplyTo)) {
+        $this->AddAnAddress('Reply-To', $address, $name);
+      }
+      if (empty($this->Sender)) {
+        $this->Sender = $address;
+      }
+    }
+    return true;
+  }
+
+  /**
+   * Check that a string looks roughly like an email address should
+   * Static so it can be used without instantiation, public so people can overload
+   * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is
+   * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to
+   * not allow a@b type valid addresses :(
+   * @link http://squiloople.com/2009/12/20/email-address-validation/
+   * @copyright regex Copyright Michael Rushton 2009-10 | http://squiloople.com/ | Feel free to use and redistribute this code. But please keep this copyright notice.
+   * @param string $address The email address to check
+   * @return boolean
+   * @static
+   * @access public
+   */
+  public static function ValidateAddress($address) {
+	return preg_match('/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)((?>(?>(?>((?>(?>(?>\x0D\x0A)?[	 ])+|(?>[	 ]*\x0D\x0A)?[	 ]+)?)(\((?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}|(?!(?:.*[a-f0-9][:\]]){7,})((?6)(?>:(?6)){0,5})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:|(?!(?:.*[a-f0-9]:){5,})(?8)?::(?>((?6)(?>:(?6)){0,3}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $address);
+  }
+
+  /////////////////////////////////////////////////
+  // METHODS, MAIL SENDING
+  /////////////////////////////////////////////////
+
+  /**
+   * Creates message and assigns Mailer. If the message is
+   * not sent successfully then it returns false.  Use the ErrorInfo
+   * variable to view description of the error.
+   * @return bool
+   */
+  public function Send() {
+    try {
+      if(!$this->PreSend()) return false;
+      return $this->PostSend();
+    } catch (phpmailerException $e) {
+      $this->mailHeader = '';
+      $this->SetError($e->getMessage());
+      if ($this->exceptions) {
+        throw $e;
+      }
+      return false;
+    }
+  }
+
+  /**
+   * Prep mail by constructing all message entities
+   * @return bool
+   */
+  public function PreSend() {
+    try {
+      $this->mailHeader = "";
+      if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
+        throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
+      }
+
+      // Set whether the message is multipart/alternative
+      if(!empty($this->AltBody)) {
+        $this->ContentType = 'multipart/alternative';
+      }
+
+      $this->error_count = 0; // reset errors
+      $this->SetMessageType();
+      //Refuse to send an empty message
+      if (empty($this->Body)) {
+        throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
+      }
+
+      $this->MIMEHeader = $this->CreateHeader();
+      $this->MIMEBody = $this->CreateBody();
+
+      // To capture the complete message when using mail(), create
+      // an extra header list which CreateHeader() doesn't fold in
+      if ($this->Mailer == 'mail') {
+        if (count($this->to) > 0) {
+          $this->mailHeader .= $this->AddrAppend("To", $this->to);
+        } else {
+          $this->mailHeader .= $this->HeaderLine("To", "undisclosed-recipients:;");
+        }
+        $this->mailHeader .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader(trim($this->Subject))));
+        // if(count($this->cc) > 0) {
+            // $this->mailHeader .= $this->AddrAppend("Cc", $this->cc);
+        // }
+      }
+
+      // digitally sign with DKIM if enabled
+      if (!empty($this->DKIM_domain) && !empty($this->DKIM_private) && !empty($this->DKIM_selector) && !empty($this->DKIM_domain) && file_exists($this->DKIM_private)) {
+        $header_dkim = $this->DKIM_Add($this->MIMEHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody);
+        $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader;
+      }
+
+      return true;
+
+    } catch (phpmailerException $e) {
+      $this->SetError($e->getMessage());
+      if ($this->exceptions) {
+        throw $e;
+      }
+      return false;
+    }
+  }
+
+  /**
+   * Actual Email transport function
+   * Send the email via the selected mechanism
+   * @return bool
+   */
+  public function PostSend() {
+    $rtn = false;
+    try {
+      // Choose the mailer and send through it
+      switch($this->Mailer) {
+        case 'sendmail':
+          $rtn = $this->SendmailSend($this->MIMEHeader, $this->MIMEBody);
+          break;
+        case 'smtp':
+          $rtn = $this->SmtpSend($this->MIMEHeader, $this->MIMEBody);
+          break;
+        case 'mail':
+          $rtn = $this->MailSend($this->MIMEHeader, $this->MIMEBody);
+          break;
+        default:
+          $rtn = $this->MailSend($this->MIMEHeader, $this->MIMEBody);
+          break;
+      }
+
+    } catch (phpmailerException $e) {
+      $this->SetError($e->getMessage());
+      if ($this->exceptions) {
+        throw $e;
+      }
+      if ($this->SMTPDebug) {
+        $this->edebug($e->getMessage()."\n");
+      }
+      return false;
+    }
+    return $rtn;
+  }
+
+  /**
+   * Sends mail using the $Sendmail program.
+   * @param string $header The message headers
+   * @param string $body The message body
+   * @access protected
+   * @return bool
+   */
+  protected function SendmailSend($header, $body) {
+    if ($this->Sender != '') {
+      $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
+    } else {
+      $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
+    }
+    if ($this->SingleTo === true) {
+      foreach ($this->SingleToArray as $key => $val) {
+        if(!@$mail = popen($sendmail, 'w')) {
+          throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
+        }
+        fputs($mail, "To: " . $val . "\n");
+        fputs($mail, $header);
+        fputs($mail, $body);
+        $result = pclose($mail);
+        // implement call back function if it exists
+        $isSent = ($result == 0) ? 1 : 0;
+        $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
+        if($result != 0) {
+          throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
+        }
+      }
+    } else {
+      if(!@$mail = popen($sendmail, 'w')) {
+        throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
+      }
+      fputs($mail, $header);
+      fputs($mail, $body);
+      $result = pclose($mail);
+      // implement call back function if it exists
+      $isSent = ($result == 0) ? 1 : 0;
+      $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body);
+      if($result != 0) {
+        throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
+      }
+    }
+    return true;
+  }
+
+  /**
+   * Sends mail using the PHP mail() function.
+   * @param string $header The message headers
+   * @param string $body The message body
+   * @access protected
+   * @return bool
+   */
+  protected function MailSend($header, $body) {
+    $toArr = array();
+    foreach($this->to as $t) {
+      $toArr[] = $this->AddrFormat($t);
+    }
+    $to = implode(', ', $toArr);
+
+    if (empty($this->Sender)) {
+      $params = "-oi ";
+    } else {
+      $params = sprintf("-oi -f %s", $this->Sender);
+    }
+    if ($this->Sender != '' and !ini_get('safe_mode')) {
+      $old_from = ini_get('sendmail_from');
+      ini_set('sendmail_from', $this->Sender);
+    }
+    if ($this->SingleTo === true && count($toArr) > 1) {
+      foreach ($toArr as $key => $val) {
+        $rt = $this->mail_passthru($val, $this->Subject, $body, $header, $params);
+        // implement call back function if it exists
+        $isSent = ($rt == 1) ? 1 : 0;
+        $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
+      }
+    } else {
+      $rt = $this->mail_passthru($to, $this->Subject, $body, $header, $params);
+      // implement call back function if it exists
+      $isSent = ($rt == 1) ? 1 : 0;
+      $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
+    }
+    if (isset($old_from)) {
+      ini_set('sendmail_from', $old_from);
+    }
+    if(!$rt) {
+      throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
+    }
+    return true;
+  }
+
+  /**
+   * Sends mail via SMTP using PhpSMTP
+   * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
+   * @param string $header The message headers
+   * @param string $body The message body
+   * @uses SMTP
+   * @access protected
+   * @return bool
+   */
+  protected function SmtpSend($header, $body) {
+    require_once $this->PluginDir . 'class.smtp.php';
+    $bad_rcpt = array();
+
+    if(!$this->SmtpConnect()) {
+      throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
+    }
+    $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
+    if(!$this->smtp->Mail($smtp_from)) {
+      throw new phpmailerException($this->Lang('from_failed') . $smtp_from, self::STOP_CRITICAL);
+    }
+
+    // Attempt to send attach all recipients
+    foreach($this->to as $to) {
+      if (!$this->smtp->Recipient($to[0])) {
+        $bad_rcpt[] = $to[0];
+        // implement call back function if it exists
+        $isSent = 0;
+        $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
+      } else {
+        // implement call back function if it exists
+        $isSent = 1;
+        $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
+      }
+    }
+    foreach($this->cc as $cc) {
+      if (!$this->smtp->Recipient($cc[0])) {
+        $bad_rcpt[] = $cc[0];
+        // implement call back function if it exists
+        $isSent = 0;
+        $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
+      } else {
+        // implement call back function if it exists
+        $isSent = 1;
+        $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
+      }
+    }
+    foreach($this->bcc as $bcc) {
+      if (!$this->smtp->Recipient($bcc[0])) {
+        $bad_rcpt[] = $bcc[0];
+        // implement call back function if it exists
+        $isSent = 0;
+        $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
+      } else {
+        // implement call back function if it exists
+        $isSent = 1;
+        $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
+      }
+    }
+
+
+    if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses
+      $badaddresses = implode(', ', $bad_rcpt);
+      throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);
+    }
+    if(!$this->smtp->Data($header . $body)) {
+      throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
+    }
+    if($this->SMTPKeepAlive == true) {
+      $this->smtp->Reset();
+    }
+    return true;
+  }
+
+  /**
+   * Initiates a connection to an SMTP server.
+   * Returns false if the operation failed.
+   * @uses SMTP
+   * @access public
+   * @return bool
+   */
+  public function SmtpConnect() {
+    if ($this->smtp === null) {
+      $this->smtp = new SMTP();
+    }
+
+    $this->smtp->Timeout = $this->Timeout;
+    $this->smtp->do_debug = $this->SMTPDebug;
+    $hosts = explode(';', $this->Host);
+    $index = 0;
+    $connection = $this->smtp->Connected();
+    $rtn = true;
+
+    // Retry while there is no connection
+    try {
+      while($index < count($hosts) && !$connection) {
+        $hostinfo = array();
+        if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) {
+          $host = $hostinfo[1];
+          $port = $hostinfo[2];
+        } else {
+          $host = $hosts[$index];
+          $port = $this->Port;
+        }
+
+        $tls = ($this->SMTPSecure == 'tls');
+        $ssl = ($this->SMTPSecure == 'ssl');
+
+        if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) {
+
+          $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname());
+          $this->smtp->Hello($hello);
+
+          if ($tls) {
+            if (!$this->smtp->StartTLS()) {
+              $rtn = false;
+              throw new phpmailerException($this->Lang('tls'));
+            }
+
+            //We must resend HELO after tls negotiation
+            $this->smtp->Hello($hello);
+          }
+
+          $connection = true;
+          if ($this->SMTPAuth) {
+            if (!$this->smtp->Authenticate($this->Username, $this->Password, $this->AuthType,
+                                           $this->Realm, $this->Workstation)) {
+              $rtn = false;
+              throw new phpmailerException($this->Lang('authenticate'));
+            }
+          }
+        }
+        $index++;
+        if (!$connection) {
+          $rtn = false;
+          throw new phpmailerException($this->Lang('connect_host'));
+        }
+      }
+    } catch (phpmailerException $e) {
+      $this->smtp->Reset();
+      if ($this->exceptions) {
+        throw $e;
+      }
+      $rtn = false;
+    }
+    return $rtn;
+  }
+
+  /**
+   * Closes the active SMTP session if one exists.
+   * @return void
+   */
+  public function SmtpClose() {
+    if ($this->smtp !== null) {
+      if($this->smtp->Connected()) {
+        $this->smtp->Quit();
+        $this->smtp->Close();
+      }
+    }
+  }
+
+  /**
+  * Sets the language for all class error messages.
+  * Returns false if it cannot load the language file.  The default language is English.
+  * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
+  * @param string $lang_path Path to the language file directory
+  * @access public
+  */
+  function SetLanguage($langcode = 'en', $lang_path = 'language/') {
+    //Define full set of translatable strings
+    $PHPMAILER_LANG = array(
+      'authenticate'         => 'SMTP Error: Could not authenticate.',
+      'connect_host'         => 'SMTP Error: Could not connect to SMTP host.',
+      'data_not_accepted'    => 'SMTP Error: Data not accepted.',
+      'empty_message'        => 'Message body empty',
+      'encoding'             => 'Unknown encoding: ',
+      'execute'              => 'Could not execute: ',
+      'file_access'          => 'Could not access file: ',
+      'file_open'            => 'File Error: Could not open file: ',
+      'from_failed'          => 'The following From address failed: ',
+      'instantiate'          => 'Could not instantiate mail function.',
+      'invalid_address'      => 'Invalid address',
+      'mailer_not_supported' => ' mailer is not supported.',
+      'provide_address'      => 'You must provide at least one recipient email address.',
+      'recipients_failed'    => 'SMTP Error: The following recipients failed: ',
+      'signing'              => 'Signing Error: ',
+      'smtp_connect_failed'  => 'SMTP Connect() failed.',
+      'smtp_error'           => 'SMTP server error: ',
+      'variable_set'         => 'Cannot set or reset variable: '
+    );
+    //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
+    $l = true;
+    if ($langcode != 'en') { //There is no English translation file
+      $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
+    }
+    $this->language = $PHPMAILER_LANG;
+    return ($l == true); //Returns false if language not found
+  }
+
+  /**
+  * Return the current array of language strings
+  * @return array
+  */
+  public function GetTranslations() {
+    return $this->language;
+  }
+
+  /////////////////////////////////////////////////
+  // METHODS, MESSAGE CREATION
+  /////////////////////////////////////////////////
+
+  /**
+   * Creates recipient headers.
+   * @access public
+   * @return string
+   */
+  public function AddrAppend($type, $addr) {
+    $addr_str = $type . ': ';
+    $addresses = array();
+    foreach ($addr as $a) {
+      $addresses[] = $this->AddrFormat($a);
+    }
+    $addr_str .= implode(', ', $addresses);
+    $addr_str .= $this->LE;
+
+    return $addr_str;
+  }
+
+  /**
+   * Formats an address correctly.
+   * @access public
+   * @return string
+   */
+  public function AddrFormat($addr) {
+    if (empty($addr[1])) {
+      return $this->SecureHeader($addr[0]);
+    } else {
+      return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
+    }
+  }
+
+  /**
+   * Wraps message for use with mailers that do not
+   * automatically perform wrapping and for quoted-printable.
+   * Original written by philippe.
+   * @param string $message The message to wrap
+   * @param integer $length The line length to wrap to
+   * @param boolean $qp_mode Whether to run in Quoted-Printable mode
+   * @access public
+   * @return string
+   */
+  public function WrapText($message, $length, $qp_mode = false) {
+    $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
+    // If utf-8 encoding is used, we will need to make sure we don't
+    // split multibyte characters when we wrap
+    $is_utf8 = (strtolower($this->CharSet) == "utf-8");
+    $lelen = strlen($this->LE);
+    $crlflen = strlen(self::CRLF);
+
+    $message = $this->FixEOL($message);
+    if (substr($message, -$lelen) == $this->LE) {
+      $message = substr($message, 0, -$lelen);
+    }
+
+    $line = explode($this->LE, $message);   // Magic. We know FixEOL uses $LE
+    $message = '';
+    for ($i = 0 ;$i < count($line); $i++) {
+      $line_part = explode(' ', $line[$i]);
+      $buf = '';
+      for ($e = 0; $e<count($line_part); $e++) {
+        $word = $line_part[$e];
+        if ($qp_mode and (strlen($word) > $length)) {
+          $space_left = $length - strlen($buf) - $crlflen;
+          if ($e != 0) {
+            if ($space_left > 20) {
+              $len = $space_left;
+              if ($is_utf8) {
+                $len = $this->UTF8CharBoundary($word, $len);
+              } elseif (substr($word, $len - 1, 1) == "=") {
+                $len--;
+              } elseif (substr($word, $len - 2, 1) == "=") {
+                $len -= 2;
+              }
+              $part = substr($word, 0, $len);
+              $word = substr($word, $len);
+              $buf .= ' ' . $part;
+              $message .= $buf . sprintf("=%s", self::CRLF);
+            } else {
+              $message .= $buf . $soft_break;
+            }
+            $buf = '';
+          }
+          while (strlen($word) > 0) {
+            $len = $length;
+            if ($is_utf8) {
+              $len = $this->UTF8CharBoundary($word, $len);
+            } elseif (substr($word, $len - 1, 1) == "=") {
+              $len--;
+            } elseif (substr($word, $len - 2, 1) == "=") {
+              $len -= 2;
+            }
+            $part = substr($word, 0, $len);
+            $word = substr($word, $len);
+
+            if (strlen($word) > 0) {
+              $message .= $part . sprintf("=%s", self::CRLF);
+            } else {
+              $buf = $part;
+            }
+          }
+        } else {
+          $buf_o = $buf;
+          $buf .= ($e == 0) ? $word : (' ' . $word);
+
+          if (strlen($buf) > $length and $buf_o != '') {
+            $message .= $buf_o . $soft_break;
+            $buf = $word;
+          }
+        }
+      }
+      $message .= $buf . self::CRLF;
+    }
+
+    return $message;
+  }
+
+  /**
+   * Finds last character boundary prior to maxLength in a utf-8
+   * quoted (printable) encoded string.
+   * Original written by Colin Brown.
+   * @access public
+   * @param string $encodedText utf-8 QP text
+   * @param int    $maxLength   find last character boundary prior to this length
+   * @return int
+   */
+  public function UTF8CharBoundary($encodedText, $maxLength) {
+    $foundSplitPos = false;
+    $lookBack = 3;
+    while (!$foundSplitPos) {
+      $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
+      $encodedCharPos = strpos($lastChunk, "=");
+      if ($encodedCharPos !== false) {
+        // Found start of encoded character byte within $lookBack block.
+        // Check the encoded byte value (the 2 chars after the '=')
+        $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
+        $dec = hexdec($hex);
+        if ($dec < 128) { // Single byte character.
+          // If the encoded char was found at pos 0, it will fit
+          // otherwise reduce maxLength to start of the encoded char
+          $maxLength = ($encodedCharPos == 0) ? $maxLength :
+          $maxLength - ($lookBack - $encodedCharPos);
+          $foundSplitPos = true;
+        } elseif ($dec >= 192) { // First byte of a multi byte character
+          // Reduce maxLength to split at start of character
+          $maxLength = $maxLength - ($lookBack - $encodedCharPos);
+          $foundSplitPos = true;
+        } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
+          $lookBack += 3;
+        }
+      } else {
+        // No encoded character found
+        $foundSplitPos = true;
+      }
+    }
+    return $maxLength;
+  }
+
+
+  /**
+   * Set the body wrapping.
+   * @access public
+   * @return void
+   */
+  public function SetWordWrap() {
+    if($this->WordWrap < 1) {
+      return;
+    }
+
+    switch($this->message_type) {
+      case 'alt':
+      case 'alt_inline':
+      case 'alt_attach':
+      case 'alt_inline_attach':
+        $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
+        break;
+      default:
+        $this->Body = $this->WrapText($this->Body, $this->WordWrap);
+        break;
+    }
+  }
+
+  /**
+   * Assembles message header.
+   * @access public
+   * @return string The assembled header
+   */
+  public function CreateHeader() {
+    $result = '';
+
+    // Set the boundaries
+    $uniq_id = md5(uniqid(time()));
+    $this->boundary[1] = 'b1_' . $uniq_id;
+    $this->boundary[2] = 'b2_' . $uniq_id;
+    $this->boundary[3] = 'b3_' . $uniq_id;
+
+    $result .= $this->HeaderLine('Date', self::RFCDate());
+    if ($this->ReturnPath) {
+      $result .= $this->HeaderLine('Return-Path', trim($this->ReturnPath));
+    } elseif ($this->Sender == '') {
+      $result .= $this->HeaderLine('Return-Path', trim($this->From));
+    } else {
+      $result .= $this->HeaderLine('Return-Path', trim($this->Sender));
+    }
+
+    // To be created automatically by mail()
+    if($this->Mailer != 'mail') {
+      if ($this->SingleTo === true) {
+        foreach($this->to as $t) {
+          $this->SingleToArray[] = $this->AddrFormat($t);
+        }
+      } else {
+        if(count($this->to) > 0) {
+          $result .= $this->AddrAppend('To', $this->to);
+        } elseif (count($this->cc) == 0) {
+          $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
+        }
+      }
+    }
+
+    $from = array();
+    $from[0][0] = trim($this->From);
+    $from[0][1] = $this->FromName;
+    $result .= $this->AddrAppend('From', $from);
+
+    // sendmail and mail() extract Cc from the header before sending
+    if(count($this->cc) > 0) {
+      $result .= $this->AddrAppend('Cc', $this->cc);
+    }
+
+    // sendmail and mail() extract Bcc from the header before sending
+    if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
+      $result .= $this->AddrAppend('Bcc', $this->bcc);
+    }
+
+    if(count($this->ReplyTo) > 0) {
+      $result .= $this->AddrAppend('Reply-To', $this->ReplyTo);
+    }
+
+    // mail() sets the subject itself
+    if($this->Mailer != 'mail') {
+      $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
+    }
+
+    if($this->MessageID != '') {
+      $result .= $this->HeaderLine('Message-ID', $this->MessageID);
+    } else {
+      $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
+    }
+    $result .= $this->HeaderLine('X-Priority', $this->Priority);
+    if ($this->XMailer == '') {
+        $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (http://code.google.com/a/apache-extras.org/p/phpmailer/)');
+    } else {
+      $myXmailer = trim($this->XMailer);
+      if ($myXmailer) {
+        $result .= $this->HeaderLine('X-Mailer', $myXmailer);
+      }
+    }
+
+    if($this->ConfirmReadingTo != '') {
+      $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
+    }
+
+    // Add custom headers
+    for($index = 0; $index < count($this->CustomHeader); $index++) {
+      $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
+    }
+    if (!$this->sign_key_file) {
+      $result .= $this->HeaderLine('MIME-Version', '1.0');
+      $result .= $this->GetMailMIME();
+    }
+
+    return $result;
+  }
+
+  /**
+   * Returns the message MIME.
+   * @access public
+   * @return string
+   */
+  public function GetMailMIME() {
+    $result = '';
+    switch($this->message_type) {
+      case 'inline':
+        $result .= $this->HeaderLine('Content-Type', 'multipart/related;');
+        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
+        break;
+      case 'attach':
+      case 'inline_attach':
+      case 'alt_attach':
+      case 'alt_inline_attach':
+        $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
+        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
+        break;
+      case 'alt':
+      case 'alt_inline':
+        $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
+        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
+        break;
+      default:
+        // Catches case 'plain': and case '':
+        $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
+        $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset='.$this->CharSet);
+        break;
+    }
+
+    if($this->Mailer != 'mail') {
+      $result .= $this->LE;
+    }
+
+    return $result;
+  }
+
+  /**
+   * Returns the MIME message (headers and body). Only really valid post PreSend().
+   * @access public
+   * @return string
+   */
+  public function GetSentMIMEMessage() {
+    return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
+  }
+
+
+  /**
+   * Assembles the message body.  Returns an empty string on failure.
+   * @access public
+   * @return string The assembled message body
+   */
+  public function CreateBody() {
+    $body = '';
+
+    if ($this->sign_key_file) {
+      $body .= $this->GetMailMIME().$this->LE;
+    }
+
+    $this->SetWordWrap();
+
+    switch($this->message_type) {
+      case 'inline':
+        $body .= $this->GetBoundary($this->boundary[1], '', '', '');
+        $body .= $this->EncodeString($this->Body, $this->Encoding);
+        $body .= $this->LE.$this->LE;
+        $body .= $this->AttachAll("inline", $this->boundary[1]);
+        break;
+      case 'attach':
+        $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
+        $body .= $this->EncodeString($this->Body, $this->Encoding);
+        $body .= $this->LE.$this->LE;
+        $body .= $this->AttachAll("attachment", $this->boundary[1]);
+        break;
+      case 'inline_attach':
+        $body .= $this->TextLine("--" . $this->boundary[1]);
+        $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
+        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
+        $body .= $this->LE;
+        $body .= $this->GetBoundary($this->boundary[2], '', '', '');
+        $body .= $this->EncodeString($this->Body, $this->Encoding);
+        $body .= $this->LE.$this->LE;
+        $body .= $this->AttachAll("inline", $this->boundary[2]);
+        $body .= $this->LE;
+        $body .= $this->AttachAll("attachment", $this->boundary[1]);
+        break;
+      case 'alt':
+        $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
+        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
+        $body .= $this->LE.$this->LE;
+        $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
+        $body .= $this->EncodeString($this->Body, $this->Encoding);
+        $body .= $this->LE.$this->LE;
+        $body .= $this->EndBoundary($this->boundary[1]);
+        break;
+      case 'alt_inline':
+        $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
+        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
+        $body .= $this->LE.$this->LE;
+        $body .= $this->TextLine("--" . $this->boundary[1]);
+        $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
+        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
+        $body .= $this->LE;
+        $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
+        $body .= $this->EncodeString($this->Body, $this->Encoding);
+        $body .= $this->LE.$this->LE;
+        $body .= $this->AttachAll("inline", $this->boundary[2]);
+        $body .= $this->LE;
+        $body .= $this->EndBoundary($this->boundary[1]);
+        break;
+      case 'alt_attach':
+        $body .= $this->TextLine("--" . $this->boundary[1]);
+        $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
+        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
+        $body .= $this->LE;
+        $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
+        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
+        $body .= $this->LE.$this->LE;
+        $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
+        $body .= $this->EncodeString($this->Body, $this->Encoding);
+        $body .= $this->LE.$this->LE;
+        $body .= $this->EndBoundary($this->boundary[2]);
+        $body .= $this->LE;
+        $body .= $this->AttachAll("attachment", $this->boundary[1]);
+        break;
+      case 'alt_inline_attach':
+        $body .= $this->TextLine("--" . $this->boundary[1]);
+        $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
+        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
+        $body .= $this->LE;
+        $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
+        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
+        $body .= $this->LE.$this->LE;
+        $body .= $this->TextLine("--" . $this->boundary[2]);
+        $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
+        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3] . '"');
+        $body .= $this->LE;
+        $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', '');
+        $body .= $this->EncodeString($this->Body, $this->Encoding);
+        $body .= $this->LE.$this->LE;
+        $body .= $this->AttachAll("inline", $this->boundary[3]);
+        $body .= $this->LE;
+        $body .= $this->EndBoundary($this->boundary[2]);
+        $body .= $this->LE;
+        $body .= $this->AttachAll("attachment", $this->boundary[1]);
+        break;
+      default:
+        // catch case 'plain' and case ''
+        $body .= $this->EncodeString($this->Body, $this->Encoding);
+        break;
+    }
+
+    if ($this->IsError()) {
+      $body = '';
+    } elseif ($this->sign_key_file) {
+      try {
+        $file = tempnam('', 'mail');
+        file_put_contents($file, $body); //TODO check this worked
+        $signed = tempnam("", "signed");
+        if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) {
+          @unlink($file);
+          $body = file_get_contents($signed);
+          @unlink($signed);
+        } else {
+          @unlink($file);
+          @unlink($signed);
+          throw new phpmailerException($this->Lang("signing").openssl_error_string());
+        }
+      } catch (phpmailerException $e) {
+        $body = '';
+        if ($this->exceptions) {
+          throw $e;
+        }
+      }
+    }
+
+    return $body;
+  }
+
+  /**
+   * Returns the start of a message boundary.
+   * @access protected
+   * @return string
+   */
+  protected function GetBoundary($boundary, $charSet, $contentType, $encoding) {
+    $result = '';
+    if($charSet == '') {
+      $charSet = $this->CharSet;
+    }
+    if($contentType == '') {
+      $contentType = $this->ContentType;
+    }
+    if($encoding == '') {
+      $encoding = $this->Encoding;
+    }
+    $result .= $this->TextLine('--' . $boundary);
+    $result .= sprintf("Content-Type: %s; charset=%s", $contentType, $charSet);
+    $result .= $this->LE;
+    $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
+    $result .= $this->LE;
+
+    return $result;
+  }
+
+  /**
+   * Returns the end of a message boundary.
+   * @access protected
+   * @return string
+   */
+  protected function EndBoundary($boundary) {
+    return $this->LE . '--' . $boundary . '--' . $this->LE;
+  }
+
+  /**
+   * Sets the message type.
+   * @access protected
+   * @return void
+   */
+  protected function SetMessageType() {
+    $this->message_type = array();
+    if($this->AlternativeExists()) $this->message_type[] = "alt";
+    if($this->InlineImageExists()) $this->message_type[] = "inline";
+    if($this->AttachmentExists()) $this->message_type[] = "attach";
+    $this->message_type = implode("_", $this->message_type);
+    if($this->message_type == "") $this->message_type = "plain";
+  }
+
+  /**
+   *  Returns a formatted header line.
+   * @access public
+   * @return string
+   */
+  public function HeaderLine($name, $value) {
+    return $name . ': ' . $value . $this->LE;
+  }
+
+  /**
+   * Returns a formatted mail line.
+   * @access public
+   * @return string
+   */
+  public function TextLine($value) {
+    return $value . $this->LE;
+  }
+
+  /////////////////////////////////////////////////
+  // CLASS METHODS, ATTACHMENTS
+  /////////////////////////////////////////////////
+
+  /**
+   * Adds an attachment from a path on the filesystem.
+   * Returns false if the file could not be found
+   * or accessed.
+   * @param string $path Path to the attachment.
+   * @param string $name Overrides the attachment name.
+   * @param string $encoding File encoding (see $Encoding).
+   * @param string $type File extension (MIME) type.
+   * @return bool
+   */
+  public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
+    try {
+      if ( !@is_file($path) ) {
+        throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE);
+      }
+      $filename = basename($path);
+      if ( $name == '' ) {
+        $name = $filename;
+      }
+
+      $this->attachment[] = array(
+        0 => $path,
+        1 => $filename,
+        2 => $name,
+        3 => $encoding,
+        4 => $type,
+        5 => false,  // isStringAttachment
+        6 => 'attachment',
+        7 => 0
+      );
+
+    } catch (phpmailerException $e) {
+      $this->SetError($e->getMessage());
+      if ($this->exceptions) {
+        throw $e;
+      }
+      if ($this->SMTPDebug) {
+        $this->edebug($e->getMessage()."\n");
+      }
+      if ( $e->getCode() == self::STOP_CRITICAL ) {
+        return false;
+      }
+    }
+    return true;
+  }
+
+  /**
+  * Return the current array of attachments
+  * @return array
+  */
+  public function GetAttachments() {
+    return $this->attachment;
+  }
+
+  /**
+   * Attaches all fs, string, and binary attachments to the message.
+   * Returns an empty string on failure.
+   * @access protected
+   * @return string
+   */
+  protected function AttachAll($disposition_type, $boundary) {
+    // Return text of body
+    $mime = array();
+    $cidUniq = array();
+    $incl = array();
+
+    // Add all attachments
+    foreach ($this->attachment as $attachment) {
+      // CHECK IF IT IS A VALID DISPOSITION_FILTER
+      if($attachment[6] == $disposition_type) {
+        // Check for string attachment
+        $bString = $attachment[5];
+        if ($bString) {
+          $string = $attachment[0];
+        } else {
+          $path = $attachment[0];
+        }
+
+        $inclhash = md5(serialize($attachment));
+        if (in_array($inclhash, $incl)) { continue; }
+        $incl[]      = $inclhash;
+        $filename    = $attachment[1];
+        $name        = $attachment[2];
+        $encoding    = $attachment[3];
+        $type        = $attachment[4];
+        $disposition = $attachment[6];
+        $cid         = $attachment[7];
+        if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; }
+        $cidUniq[$cid] = true;
+
+        $mime[] = sprintf("--%s%s", $boundary, $this->LE);
+        $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
+        $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
+
+        if($disposition == 'inline') {
+          $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
+        }
+
+        $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
+
+        // Encode as string attachment
+        if($bString) {
+          $mime[] = $this->EncodeString($string, $encoding);
+          if($this->IsError()) {
+            return '';
+          }
+          $mime[] = $this->LE.$this->LE;
+        } else {
+          $mime[] = $this->EncodeFile($path, $encoding);
+          if($this->IsError()) {
+            return '';
+          }
+          $mime[] = $this->LE.$this->LE;
+        }
+      }
+    }
+
+    $mime[] = sprintf("--%s--%s", $boundary, $this->LE);
+
+    return implode("", $mime);
+  }
+
+  /**
+   * Encodes attachment in requested format.
+   * Returns an empty string on failure.
+   * @param string $path The full path to the file
+   * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
+   * @see EncodeFile()
+   * @access protected
+   * @return string
+   */
+  protected function EncodeFile($path, $encoding = 'base64') {
+    try {
+      if (!is_readable($path)) {
+        throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE);
+      }
+      //  if (!function_exists('get_magic_quotes')) {
+      //    function get_magic_quotes() {
+      //      return false;
+      //    }
+      //  }
+      $magic_quotes = get_magic_quotes_runtime();
+      if ($magic_quotes) {
+        if (version_compare(PHP_VERSION, '5.3.0', '<')) {
+          set_magic_quotes_runtime(0);
+        } else {
+          ini_set('magic_quotes_runtime', 0);
+        }
+      }
+      $file_buffer  = file_get_contents($path);
+      $file_buffer  = $this->EncodeString($file_buffer, $encoding);
+      if ($magic_quotes) {
+        if (version_compare(PHP_VERSION, '5.3.0', '<')) {
+          set_magic_quotes_runtime($magic_quotes);
+        } else {
+          ini_set('magic_quotes_runtime', $magic_quotes);
+        }
+      }
+      return $file_buffer;
+    } catch (Exception $e) {
+      $this->SetError($e->getMessage());
+      return '';
+    }
+  }
+
+  /**
+   * Encodes string to requested format.
+   * Returns an empty string on failure.
+   * @param string $str The text to encode
+   * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
+   * @access public
+   * @return string
+   */
+  public function EncodeString($str, $encoding = 'base64') {
+    $encoded = '';
+    switch(strtolower($encoding)) {
+      case 'base64':
+        $encoded = chunk_split(base64_encode($str), 76, $this->LE);
+        break;
+      case '7bit':
+      case '8bit':
+        $encoded = $this->FixEOL($str);
+        //Make sure it ends with a line break
+        if (substr($encoded, -(strlen($this->LE))) != $this->LE)
+          $encoded .= $this->LE;
+        break;
+      case 'binary':
+        $encoded = $str;
+        break;
+      case 'quoted-printable':
+        $encoded = $this->EncodeQP($str);
+        break;
+      default:
+        $this->SetError($this->Lang('encoding') . $encoding);
+        break;
+    }
+    return $encoded;
+  }
+
+  /**
+   * Encode a header string to best (shortest) of Q, B, quoted or none.
+   * @access public
+   * @return string
+   */
+  public function EncodeHeader($str, $position = 'text') {
+    $x = 0;
+
+    switch (strtolower($position)) {
+      case 'phrase':
+        if (!preg_match('/[\200-\377]/', $str)) {
+          // Can't use addslashes as we don't know what value has magic_quotes_sybase
+          $encoded = addcslashes($str, "\0..\37\177\\\"");
+          if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
+            return ($encoded);
+          } else {
+            return ("\"$encoded\"");
+          }
+        }
+        $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
+        break;
+      case 'comment':
+        $x = preg_match_all('/[()"]/', $str, $matches);
+        // Fall-through
+      case 'text':
+      default:
+        $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
+        break;
+    }
+
+    if ($x == 0) {
+      return ($str);
+    }
+
+    $maxlen = 75 - 7 - strlen($this->CharSet);
+    // Try to select the encoding which should produce the shortest output
+    if (strlen($str)/3 < $x) {
+      $encoding = 'B';
+      if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
+        // Use a custom function which correctly encodes and wraps long
+        // multibyte strings without breaking lines within a character
+        $encoded = $this->Base64EncodeWrapMB($str, "\n");
+      } else {
+        $encoded = base64_encode($str);
+        $maxlen -= $maxlen % 4;
+        $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
+      }
+    } else {
+      $encoding = 'Q';
+      $encoded = $this->EncodeQ($str, $position);
+      $encoded = $this->WrapText($encoded, $maxlen, true);
+      $encoded = str_replace('='.self::CRLF, "\n", trim($encoded));
+    }
+
+    $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
+    $encoded = trim(str_replace("\n", $this->LE, $encoded));
+
+    return $encoded;
+  }
+
+  /**
+   * Checks if a string contains multibyte characters.
+   * @access public
+   * @param string $str multi-byte text to wrap encode
+   * @return bool
+   */
+  public function HasMultiBytes($str) {
+    if (function_exists('mb_strlen')) {
+      return (strlen($str) > mb_strlen($str, $this->CharSet));
+    } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
+      return false;
+    }
+  }
+
+  /**
+   * Correctly encodes and wraps long multibyte strings for mail headers
+   * without breaking lines within a character.
+   * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
+   * @access public
+   * @param string $str multi-byte text to wrap encode
+   * @param string $lf string to use as linefeed/end-of-line
+   * @return string
+   */
+  public function Base64EncodeWrapMB($str, $lf=null) {
+    $start = "=?".$this->CharSet."?B?";
+    $end = "?=";
+    $encoded = "";
+    if ($lf === null) {
+      $lf = $this->LE;
+    }
+
+    $mb_length = mb_strlen($str, $this->CharSet);
+    // Each line must have length <= 75, including $start and $end
+    $length = 75 - strlen($start) - strlen($end);
+    // Average multi-byte ratio
+    $ratio = $mb_length / strlen($str);
+    // Base64 has a 4:3 ratio
+    $offset = $avgLength = floor($length * $ratio * .75);
+
+    for ($i = 0; $i < $mb_length; $i += $offset) {
+      $lookBack = 0;
+
+      do {
+        $offset = $avgLength - $lookBack;
+        $chunk = mb_substr($str, $i, $offset, $this->CharSet);
+        $chunk = base64_encode($chunk);
+        $lookBack++;
+      }
+      while (strlen($chunk) > $length);
+
+      $encoded .= $chunk . $lf;
+    }
+
+    // Chomp the last linefeed
+    $encoded = substr($encoded, 0, -strlen($lf));
+    return $encoded;
+  }
+
+  /**
+  * Encode string to quoted-printable.
+  * Only uses standard PHP, slow, but will always work
+  * @access public
+  * @param string $string the text to encode
+  * @param integer $line_max Number of chars allowed on a line before wrapping
+  * @return string
+  */
+  public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) {
+    $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
+    $lines = preg_split('/(?:\r\n|\r|\n)/', $input);
+    $eol = "\r\n";
+    $escape = '=';
+    $output = '';
+    while( list(, $line) = each($lines) ) {
+      $linlen = strlen($line);
+      $newline = '';
+      for($i = 0; $i < $linlen; $i++) {
+        $c = substr( $line, $i, 1 );
+        $dec = ord( $c );
+        if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E
+          $c = '=2E';
+        }
+        if ( $dec == 32 ) {
+          if ( $i == ( $linlen - 1 ) ) { // convert space at eol only
+            $c = '=20';
+          } else if ( $space_conv ) {
+            $c = '=20';
+          }
+        } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
+          $h2 = floor($dec/16);
+          $h1 = floor($dec%16);
+          $c = $escape.$hex[$h2].$hex[$h1];
+        }
+        if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
+          $output .= $newline.$escape.$eol; //  soft line break; " =\r\n" is okay
+          $newline = '';
+          // check if newline first character will be point or not
+          if ( $dec == 46 ) {
+            $c = '=2E';
+          }
+        }
+        $newline .= $c;
+      } // end of for
+      $output .= $newline.$eol;
+    } // end of while
+    return $output;
+  }
+
+  /**
+  * Encode string to RFC2045 (6.7) quoted-printable format
+  * Uses a PHP5 stream filter to do the encoding about 64x faster than the old version
+  * Also results in same content as you started with after decoding
+  * @see EncodeQPphp()
+  * @access public
+  * @param string $string the text to encode
+  * @param integer $line_max Number of chars allowed on a line before wrapping
+  * @param boolean $space_conv Dummy param for compatibility with existing EncodeQP function
+  * @return string
+  * @author Marcus Bointon
+  */
+  public function EncodeQP($string, $line_max = 76, $space_conv = false) {
+    if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
+      return quoted_printable_encode($string);
+    }
+    $filters = stream_get_filters();
+    if (!in_array('convert.*', $filters)) { //Got convert stream filter?
+      return $this->EncodeQPphp($string, $line_max, $space_conv); //Fall back to old implementation
+    }
+    $fp = fopen('php://temp/', 'r+');
+    $string = preg_replace('/\r\n?/', $this->LE, $string); //Normalise line breaks
+    $params = array('line-length' => $line_max, 'line-break-chars' => $this->LE);
+    $s = stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params);
+    fputs($fp, $string);
+    rewind($fp);
+    $out = stream_get_contents($fp);
+    stream_filter_remove($s);
+    $out = preg_replace('/^\./m', '=2E', $out); //Encode . if it is first char on a line, workaround for bug in Exchange
+    fclose($fp);
+    return $out;
+  }
+
+  /**
+   * Encode string to q encoding.
+   * @link http://tools.ietf.org/html/rfc2047
+   * @param string $str the text to encode
+   * @param string $position Where the text is going to be used, see the RFC for what that means
+   * @access public
+   * @return string
+   */
+  public function EncodeQ($str, $position = 'text') {
+    //There should not be any EOL in the string
+	$pattern="";
+    $encoded = str_replace(array("\r", "\n"), '', $str);
+    switch (strtolower($position)) {
+      case 'phrase':
+        $pattern = '^A-Za-z0-9!*+\/ -';
+        break;
+
+      case 'comment':
+        $pattern = '\(\)"';
+        //note that we dont break here!
+        //for this reason we build the $pattern withoud including delimiters and []
+
+      case 'text':
+      default:
+        //Replace every high ascii, control =, ? and _ characters
+        //We put \075 (=) as first value to make sure it's the first one in being converted, preventing double encode
+        $pattern = '\075\000-\011\013\014\016-\037\077\137\177-\377' . $pattern;
+        break;
+    }
+
+    if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
+      foreach (array_unique($matches[0]) as $char) {
+        $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
+      }
+    }
+
+    //Replace every spaces to _ (more readable than =20)
+    return str_replace(' ', '_', $encoded);
+}
+
+
+  /**
+   * Adds a string or binary attachment (non-filesystem) to the list.
+   * This method can be used to attach ascii or binary data,
+   * such as a BLOB record from a database.
+   * @param string $string String attachment data.
+   * @param string $filename Name of the attachment.
+   * @param string $encoding File encoding (see $Encoding).
+   * @param string $type File extension (MIME) type.
+   * @return void
+   */
+  public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') {
+    // Append to $attachment array
+    $this->attachment[] = array(
+      0 => $string,
+      1 => $filename,
+      2 => basename($filename),
+      3 => $encoding,
+      4 => $type,
+      5 => true,  // isStringAttachment
+      6 => 'attachment',
+      7 => 0
+    );
+  }
+
+  /**
+   * Adds an embedded attachment.  This can include images, sounds, and
+   * just about any other document.  Make sure to set the $type to an
+   * image type.  For JPEG images use "image/jpeg" and for GIF images
+   * use "image/gif".
+   * @param string $path Path to the attachment.
+   * @param string $cid Content ID of the attachment.  Use this to identify
+   *        the Id for accessing the image in an HTML form.
+   * @param string $name Overrides the attachment name.
+   * @param string $encoding File encoding (see $Encoding).
+   * @param string $type File extension (MIME) type.
+   * @return bool
+   */
+  public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
+
+    if ( !@is_file($path) ) {
+      $this->SetError($this->Lang('file_access') . $path);
+      return false;
+    }
+
+    $filename = basename($path);
+    if ( $name == '' ) {
+      $name = $filename;
+    }
+
+    // Append to $attachment array
+    $this->attachment[] = array(
+      0 => $path,
+      1 => $filename,
+      2 => $name,
+      3 => $encoding,
+      4 => $type,
+      5 => false,  // isStringAttachment
+      6 => 'inline',
+      7 => $cid
+    );
+
+    return true;
+  }
+
+  public function AddStringEmbeddedImage($string, $cid, $filename = '', $encoding = 'base64', $type = 'application/octet-stream') {
+    // Append to $attachment array
+    $this->attachment[] = array(
+      0 => $string,
+      1 => $filename,
+      2 => basename($filename),
+      3 => $encoding,
+      4 => $type,
+      5 => true,  // isStringAttachment
+      6 => 'inline',
+      7 => $cid
+    );
+  }
+
+  /**
+   * Returns true if an inline attachment is present.
+   * @access public
+   * @return bool
+   */
+  public function InlineImageExists() {
+    foreach($this->attachment as $attachment) {
+      if ($attachment[6] == 'inline') {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  public function AttachmentExists() {
+    foreach($this->attachment as $attachment) {
+      if ($attachment[6] == 'attachment') {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  public function AlternativeExists() {
+    return !empty($this->AltBody);
+  }
+
+  /////////////////////////////////////////////////
+  // CLASS METHODS, MESSAGE RESET
+  /////////////////////////////////////////////////
+
+  /**
+   * Clears all recipients assigned in the TO array.  Returns void.
+   * @return void
+   */
+  public function ClearAddresses() {
+    foreach($this->to as $to) {
+      unset($this->all_recipients[strtolower($to[0])]);
+    }
+    $this->to = array();
+  }
+
+  /**
+   * Clears all recipients assigned in the CC array.  Returns void.
+   * @return void
+   */
+  public function ClearCCs() {
+    foreach($this->cc as $cc) {
+      unset($this->all_recipients[strtolower($cc[0])]);
+    }
+    $this->cc = array();
+  }
+
+  /**
+   * Clears all recipients assigned in the BCC array.  Returns void.
+   * @return void
+   */
+  public function ClearBCCs() {
+    foreach($this->bcc as $bcc) {
+      unset($this->all_recipients[strtolower($bcc[0])]);
+    }
+    $this->bcc = array();
+  }
+
+  /**
+   * Clears all recipients assigned in the ReplyTo array.  Returns void.
+   * @return void
+   */
+  public function ClearReplyTos() {
+    $this->ReplyTo = array();
+  }
+
+  /**
+   * Clears all recipients assigned in the TO, CC and BCC
+   * array.  Returns void.
+   * @return void
+   */
+  public function ClearAllRecipients() {
+    $this->to = array();
+    $this->cc = array();
+    $this->bcc = array();
+    $this->all_recipients = array();
+  }
+
+  /**
+   * Clears all previously set filesystem, string, and binary
+   * attachments.  Returns void.
+   * @return void
+   */
+  public function ClearAttachments() {
+    $this->attachment = array();
+  }
+
+  /**
+   * Clears all custom headers.  Returns void.
+   * @return void
+   */
+  public function ClearCustomHeaders() {
+    $this->CustomHeader = array();
+  }
+
+  /////////////////////////////////////////////////
+  // CLASS METHODS, MISCELLANEOUS
+  /////////////////////////////////////////////////
+
+  /**
+   * Adds the error message to the error container.
+   * @access protected
+   * @return void
+   */
+  protected function SetError($msg) {
+    $this->error_count++;
+    if (($this->Mailer == 'smtp') and ($this->smtp !== null)) {
+      $lasterror = $this->smtp->getError();
+      if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
+        $msg .= '<p>' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
+      }
+    }
+    $this->ErrorInfo = $msg;
+  }
+
+  /**
+   * Returns the proper RFC 822 formatted date.
+   * @access public
+   * @return string
+   * @static
+   */
+  public static function RFCDate() {
+    $tz = date('Z');
+    $tzs = ($tz < 0) ? '-' : '+';
+    $tz = abs($tz);
+    $tz = (int)($tz/3600)*100 + ($tz%3600)/60;
+    $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
+
+    return $result;
+  }
+
+  /**
+   * Returns the server hostname or 'localhost.localdomain' if unknown.
+   * @access protected
+   * @return string
+   */
+  protected function ServerHostname() {
+    if (!empty($this->Hostname)) {
+      $result = $this->Hostname;
+    } elseif (isset($_SERVER['SERVER_NAME'])) {
+      $result = $_SERVER['SERVER_NAME'];
+    } else {
+      $result = 'localhost.localdomain';
+    }
+
+    return $result;
+  }
+
+  /**
+   * Returns a message in the appropriate language.
+   * @access protected
+   * @return string
+   */
+  protected function Lang($key) {
+    if(count($this->language) < 1) {
+      $this->SetLanguage('en'); // set the default language
+    }
+
+    if(isset($this->language[$key])) {
+      return $this->language[$key];
+    } else {
+      return 'Language string failed to load: ' . $key;
+    }
+  }
+
+  /**
+   * Returns true if an error occurred.
+   * @access public
+   * @return bool
+   */
+  public function IsError() {
+    return ($this->error_count > 0);
+  }
+
+  /**
+   * Changes every end of line from CRLF, CR or LF to $this->LE.
+   * @access public
+   * @param string $str String to FixEOL
+   * @return string
+   */
+  public function FixEOL($str) {
+	// condense down to \n
+	$nstr = str_replace(array("\r\n", "\r"), "\n", $str);
+	// Now convert LE as needed
+	if ($this->LE !== "\n") {
+		$nstr = str_replace("\n", $this->LE, $nstr);
+	}
+    return  $nstr;
+  }
+
+  /**
+   * Adds a custom header. $name value can be overloaded to contain
+   * both header name and value (name:value)
+   * @access public
+   * @param string $name custom header name
+   * @param string $value header value
+   * @return void
+   */
+  public function AddCustomHeader($name, $value=null) {
+	if ($value === null) {
+		// Value passed in as name:value
+		$this->CustomHeader[] = explode(':', $name, 2);
+	} else {
+		$this->CustomHeader[] = array($name, $value);
+	}
+  }
+
+  /**
+   * Evaluates the message and returns modifications for inline images and backgrounds
+   * @access public
+   * @param string $message Text to be HTML modified
+   * @param string $basedir baseline directory for path
+   * @return $message
+   */
+  public function MsgHTML($message, $basedir = '') {
+    preg_match_all("/(src|background)=[\"'](.*)[\"']/Ui", $message, $images);
+    if(isset($images[2])) {
+      foreach($images[2] as $i => $url) {
+        // do not change urls for absolute images (thanks to corvuscorax)
+        if (!preg_match('#^[A-z]+://#', $url)) {
+          $filename = basename($url);
+          $directory = dirname($url);
+          ($directory == '.') ? $directory='': '';
+          $cid = 'cid:' . md5($filename);
+          $ext = pathinfo($filename, PATHINFO_EXTENSION);
+          $mimeType  = self::_mime_types($ext);
+          if ( strlen($basedir) > 1 && substr($basedir, -1) != '/') { $basedir .= '/'; }
+          if ( strlen($directory) > 1 && substr($directory, -1) != '/') { $directory .= '/'; }
+          if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($filename), $filename, 'base64', $mimeType) ) {
+            $message = preg_replace("/".$images[1][$i]."=[\"']".preg_quote($url, '/')."[\"']/Ui", $images[1][$i]."=\"".$cid."\"", $message);
+          }
+        }
+      }
+    }
+    $this->IsHTML(true);
+    $this->Body = $message;
+    if (empty($this->AltBody)) {
+        $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $message)));
+        if (!empty($textMsg)) {
+            $this->AltBody = html_entity_decode($textMsg, ENT_QUOTES, $this->CharSet);
+        }
+    }
+    if (empty($this->AltBody)) {
+      $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n";
+    }
+    return $message;
+  }
+
+  /**
+   * Gets the MIME type of the embedded or inline image
+   * @param string $ext File extension
+   * @access public
+   * @return string MIME type of ext
+   * @static
+   */
+  public static function _mime_types($ext = '') {
+    $mimes = array(
+      'xl'    =>  'application/excel',
+      'hqx'   =>  'application/mac-binhex40',
+      'cpt'   =>  'application/mac-compactpro',
+      'bin'   =>  'application/macbinary',
+      'doc'   =>  'application/msword',
+      'doc'   =>  'application/msword',
+      'word'  =>  'application/msword',
+      'class' =>  'application/octet-stream',
+      'dll'   =>  'application/octet-stream',
+      'dms'   =>  'application/octet-stream',
+      'exe'   =>  'application/octet-stream',
+      'lha'   =>  'application/octet-stream',
+      'lzh'   =>  'application/octet-stream',
+      'psd'   =>  'application/octet-stream',
+      'sea'   =>  'application/octet-stream',
+      'so'    =>  'application/octet-stream',
+      'oda'   =>  'application/oda',
+      'pdf'   =>  'application/pdf',
+      'ai'    =>  'application/postscript',
+      'eps'   =>  'application/postscript',
+      'ps'    =>  'application/postscript',
+      'smi'   =>  'application/smil',
+      'smil'  =>  'application/smil',
+      'mif'   =>  'application/vnd.mif',
+      'xls'   =>  'application/vnd.ms-excel',
+      'ppt'   =>  'application/vnd.ms-powerpoint',
+      'wbxml' =>  'application/vnd.wap.wbxml',
+      'wmlc'  =>  'application/vnd.wap.wmlc',
+      'dcr'   =>  'application/x-director',
+      'dir'   =>  'application/x-director',
+      'dxr'   =>  'application/x-director',
+      'dvi'   =>  'application/x-dvi',
+      'gtar'  =>  'application/x-gtar',
+      'php3'  =>  'application/x-httpd-php',
+      'php4'  =>  'application/x-httpd-php',
+      'php'   =>  'application/x-httpd-php',
+      'phtml' =>  'application/x-httpd-php',
+      'phps'  =>  'application/x-httpd-php-source',
+      'js'    =>  'application/x-javascript',
+      'swf'   =>  'application/x-shockwave-flash',
+      'sit'   =>  'application/x-stuffit',
+      'tar'   =>  'application/x-tar',
+      'tgz'   =>  'application/x-tar',
+      'xht'   =>  'application/xhtml+xml',
+      'xhtml' =>  'application/xhtml+xml',
+      'zip'   =>  'application/zip',
+      'mid'   =>  'audio/midi',
+      'midi'  =>  'audio/midi',
+      'mp2'   =>  'audio/mpeg',
+      'mp3'   =>  'audio/mpeg',
+      'mpga'  =>  'audio/mpeg',
+      'aif'   =>  'audio/x-aiff',
+      'aifc'  =>  'audio/x-aiff',
+      'aiff'  =>  'audio/x-aiff',
+      'ram'   =>  'audio/x-pn-realaudio',
+      'rm'    =>  'audio/x-pn-realaudio',
+      'rpm'   =>  'audio/x-pn-realaudio-plugin',
+      'ra'    =>  'audio/x-realaudio',
+      'wav'   =>  'audio/x-wav',
+      'bmp'   =>  'image/bmp',
+      'gif'   =>  'image/gif',
+      'jpeg'  =>  'image/jpeg',
+      'jpe'   =>  'image/jpeg',
+      'jpg'   =>  'image/jpeg',
+      'png'   =>  'image/png',
+      'tiff'  =>  'image/tiff',
+      'tif'   =>  'image/tiff',
+      'eml'   =>  'message/rfc822',
+      'css'   =>  'text/css',
+      'html'  =>  'text/html',
+      'htm'   =>  'text/html',
+      'shtml' =>  'text/html',
+      'log'   =>  'text/plain',
+      'text'  =>  'text/plain',
+      'txt'   =>  'text/plain',
+      'rtx'   =>  'text/richtext',
+      'rtf'   =>  'text/rtf',
+      'xml'   =>  'text/xml',
+      'xsl'   =>  'text/xml',
+      'mpeg'  =>  'video/mpeg',
+      'mpe'   =>  'video/mpeg',
+      'mpg'   =>  'video/mpeg',
+      'mov'   =>  'video/quicktime',
+      'qt'    =>  'video/quicktime',
+      'rv'    =>  'video/vnd.rn-realvideo',
+      'avi'   =>  'video/x-msvideo',
+      'movie' =>  'video/x-sgi-movie'
+    );
+    return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
+  }
+
+  /**
+  * Set (or reset) Class Objects (variables)
+  *
+  * Usage Example:
+  * $page->set('X-Priority', '3');
+  *
+  * @access public
+  * @param string $name Parameter Name
+  * @param mixed $value Parameter Value
+  * NOTE: will not work with arrays, there are no arrays to set/reset
+  * @todo Should this not be using __set() magic function?
+  */
+  public function set($name, $value = '') {
+    try {
+      if (isset($this->$name) ) {
+        $this->$name = $value;
+      } else {
+        throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL);
+      }
+    } catch (Exception $e) {
+      $this->SetError($e->getMessage());
+      if ($e->getCode() == self::STOP_CRITICAL) {
+        return false;
+      }
+    }
+    return true;
+  }
+
+  /**
+   * Strips newlines to prevent header injection.
+   * @access public
+   * @param string $str String
+   * @return string
+   */
+  public function SecureHeader($str) {
+    return trim(str_replace(array("\r", "\n"), '', $str));
+  }
+
+  /**
+   * Set the private key file and password to sign the message.
+   *
+   * @access public
+   * @param string $key_filename Parameter File Name
+   * @param string $key_pass Password for private key
+   */
+  public function Sign($cert_filename, $key_filename, $key_pass) {
+    $this->sign_cert_file = $cert_filename;
+    $this->sign_key_file = $key_filename;
+    $this->sign_key_pass = $key_pass;
+  }
+
+  /**
+   * Set the private key file and password to sign the message.
+   *
+   * @access public
+   * @param string $key_filename Parameter File Name
+   * @param string $key_pass Password for private key
+   */
+  public function DKIM_QP($txt) {
+    $tmp = '';
+    $line = '';
+    for ($i = 0; $i < strlen($txt); $i++) {
+      $ord = ord($txt[$i]);
+      if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) {
+        $line .= $txt[$i];
+      } else {
+        $line .= "=".sprintf("%02X", $ord);
+      }
+    }
+    return $line;
+  }
+
+  /**
+   * Generate DKIM signature
+   *
+   * @access public
+   * @param string $s Header
+   */
+  public function DKIM_Sign($s) {
+    $privKeyStr = file_get_contents($this->DKIM_private);
+    if ($this->DKIM_passphrase != '') {
+      $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
+    } else {
+      $privKey = $privKeyStr;
+    }
+    if (openssl_sign($s, $signature, $privKey)) {
+      return base64_encode($signature);
+    }
+  }
+
+  /**
+   * Generate DKIM Canonicalization Header
+   *
+   * @access public
+   * @param string $s Header
+   */
+  public function DKIM_HeaderC($s) {
+    $s = preg_replace("/\r\n\s+/", " ", $s);
+    $lines = explode("\r\n", $s);
+    foreach ($lines as $key => $line) {
+      list($heading, $value) = explode(":", $line, 2);
+      $heading = strtolower($heading);
+      $value = preg_replace("/\s+/", " ", $value) ; // Compress useless spaces
+      $lines[$key] = $heading.":".trim($value) ; // Don't forget to remove WSP around the value
+    }
+    $s = implode("\r\n", $lines);
+    return $s;
+  }
+
+  /**
+   * Generate DKIM Canonicalization Body
+   *
+   * @access public
+   * @param string $body Message Body
+   */
+  public function DKIM_BodyC($body) {
+    if ($body == '') return "\r\n";
+    // stabilize line endings
+    $body = str_replace("\r\n", "\n", $body);
+    $body = str_replace("\n", "\r\n", $body);
+    // END stabilize line endings
+    while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
+      $body = substr($body, 0, strlen($body) - 2);
+    }
+    return $body;
+  }
+
+  /**
+   * Create the DKIM header, body, as new header
+   *
+   * @access public
+   * @param string $headers_line Header lines
+   * @param string $subject Subject
+   * @param string $body Body
+   */
+  public function DKIM_Add($headers_line, $subject, $body) {
+    $DKIMsignatureType    = 'rsa-sha1'; // Signature & hash algorithms
+    $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
+    $DKIMquery            = 'dns/txt'; // Query method
+    $DKIMtime             = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
+    $subject_header       = "Subject: $subject";
+    $headers              = explode($this->LE, $headers_line);
+    foreach($headers as $header) {
+      if (strpos($header, 'From:') === 0) {
+        $from_header = $header;
+      } elseif (strpos($header, 'To:') === 0) {
+        $to_header = $header;
+      }
+    }
+    $from     = str_replace('|', '=7C', $this->DKIM_QP($from_header));
+    $to       = str_replace('|', '=7C', $this->DKIM_QP($to_header));
+    $subject  = str_replace('|', '=7C', $this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable
+    $body     = $this->DKIM_BodyC($body);
+    $DKIMlen  = strlen($body) ; // Length of body
+    $DKIMb64  = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body
+    $ident    = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";";
+    $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n".
+                "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n".
+                "\th=From:To:Subject;\r\n".
+                "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n".
+                "\tz=$from\r\n".
+                "\t|$to\r\n".
+                "\t|$subject;\r\n".
+                "\tbh=" . $DKIMb64 . ";\r\n".
+                "\tb=";
+    $toSign   = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs);
+    $signed   = $this->DKIM_Sign($toSign);
+    return "X-PHPMAILER-DKIM: phpmailer.worxware.com\r\n".$dkimhdrs.$signed."\r\n";
+  }
+
+  /**
+   * Perform callback
+   */
+  protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from=null) {
+    if (!empty($this->action_function) && is_callable($this->action_function)) {
+      $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
+      call_user_func_array($this->action_function, $params);
+    }
+  }
+}
+
+/**
+ * Exception handling
+ */
+class phpmailerException extends Exception {
+  public function errorMessage() {
+    $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
+    return $errorMsg;
+  }
+}
+?>

+ 147 - 0
Ainaphp/Lib/ORG/Page.class.php

@@ -0,0 +1,147 @@
+<?php
+
+
+class Page extends Think {
+    // 起始行数
+    public $firstRow	;
+    // 列表每页显示行数
+    public $listRows	;
+    // 页数跳转时要带的参数
+    public $parameter  ;
+    // 分页总页面数
+    public $totalPages  ;
+    // 总行数
+    public $totalRows  ;
+    // 当前页数
+    public $nowPage    ;
+    // 分页的栏的总页数
+    public $coolPages   ;
+    // 分页栏每页显示的页数
+    public $rollPage   ;
+	// 分页url定制
+	public $urlrule;
+
+
+    /**
+     +----------------------------------------------------------
+     * 架构函数
+     +----------------------------------------------------------
+     * @access public
+     +----------------------------------------------------------
+     * @param array $totalRows  总的记录数
+     * @param array $listRows  每页显示记录数
+     * @param array $parameter  分页跳转的参数
+     +----------------------------------------------------------
+     */
+    public function __construct($totalRows,$listRows,$p='') {
+        $this->totalRows = $totalRows;
+        $this->parameter = $parameter;
+        $this->rollPage = C('PAGE_ROLLPAGE') ? C('PAGE_ROLLPAGE') : 2;
+        $this->listRows = !empty($listRows)?$listRows:C('PAGE_LISTROWS');
+        $this->totalPages = ceil($this->totalRows/$this->listRows);     //总页数
+		if (!define('PAGESTOTAL')) define('PAGESTOTAL', $this->totalPages);
+        $this->coolPages  = ceil($this->totalPages/$this->rollPage);
+		if($p){
+			$this->nowPage =$p;
+			}else{
+			$this->nowPage  = !empty($_GET[C('VAR_PAGE')])?intval($_GET[C('VAR_PAGE')]):1;
+		}
+        if(!empty($this->totalPages) && $this->nowPage>$this->totalPages) {
+            $this->nowPage = $this->totalPages;
+        }
+        $this->firstRow = $this->listRows*($this->nowPage-1);
+    }
+
+	public function  show(){
+
+		if($this->totalRows == 0 OR $this->listRows == 0 OR $this->totalPages <= 1){
+			return '';
+		}
+		$urlrule =  str_replace('%7B%24page%7D','{$page}',$this->urlrule); //urldecode
+		if(!$urlrule){
+			$p = C('VAR_PAGE');
+			$nowCoolPage      = ceil($this->nowPage/$this->rollPage);
+			$url  =  $_SERVER['REQUEST_URI'].(strpos($_SERVER['REQUEST_URI'],'?')?'':"?").$this->parameter;
+			$parse = parse_url($url);
+			if(isset($parse['query'])) {
+				parse_str($parse['query'],$params);
+				unset($params[$p]);
+				$urlrule   =  $parse['path'].'?'.http_build_query($params);
+			}
+			$urlrule = $urlrule."&".$p.'={$page}';
+		}
+
+
+		$pre_page = $this->nowPage-1;
+		$next_page = $this->nowPage +1;
+
+		if($this->nowPage >=$this->totalPages){
+			$next_page =  $this->nowPage = $this->totalPages;
+		}
+		if($this->nowPage <= 1){
+			$pre_page =  $this->nowPage = 1;
+		}
+
+		$output = '';
+		$output .= '<a class="a1">'.$this->totalRows.L('page_item').'</a>';
+		$output .= '<a href="'.$this->pageurl($urlrule, 1,$this->parameter).'">'.L('first_page').'</a>';
+		$output .= '<a href="'.$this->pageurl($urlrule, $pre_page,$this->parameter).'">'.L('previous').'</a>';
+		$show_nums = $this->rollPage*2+1;// 显示页码的个数
+
+		if($this->totalPages <= $show_nums){
+			for($i = 1;$i<=$this->totalPages;$i++){
+				if($i == $this->nowPage){
+					$output .= '<span>'.$i.'</span>';
+				}else{
+					$output .= '<a href="'.$this->pageurl($urlrule,$i,$this->parameter).'">'.$i.'</a>';
+				}
+			}
+		}else{
+			if($this->nowPage < (1+$this->rollPage)){
+				for($i = 1;$i<=$show_nums;$i++){
+					if($i == $this->nowPage){
+						$output .=  '<span>'.$i.'</span>';
+					}else{
+						$output .= '<a href="'.$this->pageurl($urlrule,$i,$this->parameter).'">'.$i.'</a>';
+					}
+				}
+			}else if($this->nowPage >= ($this->totalPages - $this->rollPage)){
+				for($i = $this->totalPages - $show_nums ; $i <= $this->totalPages ; $i++){
+					if($i == $this->nowPage){
+						$output .=  '<span>'.$i.'</span>';
+					}else{
+						$output .= '<a href="'.$this->pageurl($urlrule,$i,$this->parameter).'">'.$i.'</a>';
+					}
+				}
+			}else{
+				$start_page = $this->nowPage - $this->rollPage;
+				$end_page = $this->nowPage + $this->rollPage;
+				for($i = $start_page ; $i<=$end_page ; $i++){
+					if($i == $this->nowPage){
+						$output .=  '<span>'.$i.'</span>';
+					}else{
+						$output .= '<a href="'.$this->pageurl($urlrule,$i,$this->parameter).'">'.$i.'</a>';
+					}
+				}
+			}
+		}
+
+		$output .='<a href="'.$this->pageurl($urlrule,$next_page,$this->parameter).'">'.L('next')."</a>";
+		$output .='<a href="'.$this->pageurl($urlrule,$this->totalPages,$this->parameter).'">'.L('Last_page')."</a>";
+		return $output;
+	}
+
+	public function pageurl($urlrule, $page, $array = array())
+	{
+		@extract($array, EXTR_SKIP);
+		if(is_array($urlrule))
+		{
+			//$urlrules = explode('|', $urlrule);
+			$urlrule = $page < 2 ? $urlrule[0] : $urlrule[1];
+		}
+		$url = str_replace('{$page}', $page, $urlrule);
+		return $url;
+	}
+
+}
+?>

+ 165 - 0
Ainaphp/Lib/ORG/Page_home.class.php

@@ -0,0 +1,165 @@
+<?php
+
+
+class Page_home extends Think {
+    // 起始行数
+    public $firstRow	;
+    // 列表每页显示行数
+    public $listRows	;
+    // 页数跳转时要带的参数
+    public $parameter  ;
+    // 分页总页面数
+    public $totalPages  ;
+    // 总行数
+    public $totalRows  ;
+    // 当前页数
+    public $nowPage    ;
+    // 分页的栏的总页数
+    public $coolPages   ;
+    // 分页栏每页显示的页数
+    public $rollPage   ;
+	// 分页url定制
+	public $urlrule;
+
+
+    /**
+     +----------------------------------------------------------
+     * 架构函数
+     +----------------------------------------------------------
+     * @access public
+     +----------------------------------------------------------
+     * @param array $totalRows  总的记录数
+     * @param array $listRows  每页显示记录数
+     * @param array $parameter  分页跳转的参数
+     +----------------------------------------------------------
+     */
+    public function __construct($totalRows,$listRows,$p='') {
+        $this->totalRows = $totalRows;
+        $this->parameter = $parameter;
+        $this->rollPage = C('PAGE_ROLLPAGE') ? C('PAGE_ROLLPAGE') : 2;
+        $this->listRows = !empty($listRows)?$listRows:C('PAGE_LISTROWS');
+        $this->totalPages = ceil($this->totalRows/$this->listRows);     //总页数
+		if (!define('PAGESTOTAL')) define('PAGESTOTAL', $this->totalPages);
+        $this->coolPages  = ceil($this->totalPages/$this->rollPage);
+		if($p){
+			$this->nowPage =$p;
+			}else{
+			$this->nowPage  = !empty($_GET[C('VAR_PAGE')])?intval($_GET[C('VAR_PAGE')]):1;
+		}
+        if(!empty($this->totalPages) && $this->nowPage>$this->totalPages) {
+            $this->nowPage = $this->totalPages;
+        }
+        $this->firstRow = $this->listRows*($this->nowPage-1);
+    }
+
+function is_mobile() {
+   $user_agent = $_SERVER['HTTP_USER_AGENT'];
+   $mobile_agents = Array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi","android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio","au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu","cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ","fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi","htc","huawei","hutchison","inno","ipaq","ipod","jbrowser","kddi","kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo","mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mot-","moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia","nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-","playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo","samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank","sony","spice","sprint","spv","symbian","tablet","talkabout","tcl-","teleca","telit","tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin","vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce","wireless","xda","xde","zte");
+   $is_mobile = false;
+   foreach ($mobile_agents as $device) {
+    if (stristr($user_agent, $device)) {
+     $is_mobile = true;
+     break;
+    }
+   }
+   return $is_mobile;
+ }
+
+	public function  show(){
+
+		if($this->totalRows == 0 OR $this->listRows == 0 OR $this->totalPages <= 1){
+			return '';
+		}
+		$urlrule =  str_replace('%7B%24page%7D','{$page}',$this->urlrule); //urldecode
+		if(!$urlrule){
+			$p = C('VAR_PAGE');
+			$nowCoolPage      = ceil($this->nowPage/$this->rollPage);
+			$url  =  $_SERVER['REQUEST_URI'].(strpos($_SERVER['REQUEST_URI'],'?')?'':"?").$this->parameter;
+			$parse = parse_url($url);
+			if(isset($parse['query'])) {
+				parse_str($parse['query'],$params);
+				unset($params[$p]);
+				$urlrule   =  $parse['path'].'?'.http_build_query($params);
+			}
+			$urlrule = $urlrule."&".$p.'={$page}';
+		}
+
+
+		$pre_page = $this->nowPage-1;
+		$next_page = $this->nowPage +1;
+
+		if($this->nowPage >=$this->totalPages){
+			$next_page =  $this->nowPage = $this->totalPages;
+		}
+		if($this->nowPage <= 1){
+			$pre_page =  $this->nowPage = 1;
+		}
+
+
+		if(is_mobile()){
+		  $output = '<div class="ajaxpage">';
+		  $output .= '<a href="'.$this->pageurl($urlrule, $next_page,$this->parameter).'" title="" style="display:none;" id="page_ajax"></a>';
+		  $output .= '<a href="'.$this->pageurl($urlrule, $this->nowPage ,$this->parameter).'" title="" style="display:none;" id="page_ajax_now"></a>';
+		  $output .='</div>';
+		}else{
+		$output = '';
+		$output .= '<a href="'.$this->pageurl($urlrule, $pre_page,$this->parameter).'">上一页</a>';
+		$show_nums = $this->rollPage*2+1;// 显示页码的个数
+
+		if($this->totalPages <= $show_nums){
+			for($i = 1;$i<=$this->totalPages;$i++){
+				if($i == $this->nowPage){
+					$output .= '<span>'.$i.'</span>';
+				}else{
+					$output .= '<a href="'.$this->pageurl($urlrule,$i,$this->parameter).'">'.$i.'</a>';
+				}
+			}
+		}else{
+			if($this->nowPage < (1+$this->rollPage)){
+				for($i = 1;$i<=$show_nums;$i++){
+					if($i == $this->nowPage){
+						$output .=  '<span>'.$i.'</span>';
+					}else{
+						$output .= '<a href="'.$this->pageurl($urlrule,$i,$this->parameter).'">'.$i.'</a>';
+					}
+				}
+			}else if($this->nowPage >= ($this->totalPages - $this->rollPage)){
+				for($i = $this->totalPages - $show_nums ; $i <= $this->totalPages ; $i++){
+					if($i == $this->nowPage){
+						$output .=  '<span>'.$i.'</span>';
+					}else{
+						$output .= '<a href="'.$this->pageurl($urlrule,$i,$this->parameter).'">'.$i.'</a>';
+					}
+				}
+			}else{
+				$start_page = $this->nowPage - $this->rollPage;
+				$end_page = $this->nowPage + $this->rollPage;
+				for($i = $start_page ; $i<=$end_page ; $i++){
+					if($i == $this->nowPage){
+						$output .=  '<span>'.$i.'</span>';
+					}else{
+						$output .= '<a href="'.$this->pageurl($urlrule,$i,$this->parameter).'">'.$i.'</a>';
+					}
+				}
+			}
+		}
+
+		$output .='<a href="'.$this->pageurl($urlrule,$next_page,$this->parameter).'">下一页</a>';
+		}
+		return $output;
+	}
+
+	public function pageurl($urlrule, $page, $array = array())
+	{
+		@extract($array, EXTR_SKIP);
+		if(is_array($urlrule))
+		{
+			//$urlrules = explode('|', $urlrule);
+			$urlrule = $page < 2 ? $urlrule[0] : $urlrule[1];
+		}
+		$url = str_replace('{$page}', $page, $urlrule);
+		return $url;
+	}
+
+}
+?>

+ 489 - 0
Ainaphp/Lib/ORG/Phpzip.class.php

@@ -0,0 +1,489 @@
+<?php
+class Phpzip extends Think {
+	private $ctrl_dir = array();
+	private $datasec  = array();
+
+	 /**********************************************************
+	  * 压缩部分
+	  * **********************************************************/
+	// ------------------------------------------------------ //
+	// #遍历指定文件夹
+	//
+	// $archive  = new PHPZip();
+	// $filelist = $archive->visitFile(文件夹路径);
+	// print "当前文件夹的文件:<p>\r\n";
+	// foreach($filelist as $file)
+	// printf("%s<br>\r\n", $file);
+	// ------------------------------------------------------ //
+	var $fileList = array();
+	public function visitFile($path)
+	{
+		global $fileList;
+		$path = str_replace("\\", "/", $path);
+		$fdir = dir($path);
+		while(($file = $fdir->read()) !== false)
+		{
+			if($file == '.' || $file == '..'){ continue; }
+			$pathSub    = preg_replace("*/{2,}*", "/", $path."/".$file);  // 替换多个反斜杠
+			$fileList[] = is_dir($pathSub) ? $pathSub."/" : $pathSub;
+			if(is_dir($pathSub)){ self::visitFile($pathSub); } }
+			$fdir->close();
+			return $fileList;
+	}
+
+	private function unix2DosTime($unixtime = 0)
+	{
+		$timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);
+		if($timearray['year'] < 1980)
+		{
+			$timearray['year']    = 1980;
+			$timearray['mon']     = 1;
+			$timearray['mday']    = 1;
+			$timearray['hours']   = 0;
+			$timearray['minutes'] = 0;
+			$timearray['seconds'] = 0;
+		}
+		return (
+			($timearray['year'] - 1980) << 25)
+			| ($timearray['mon'] << 21)
+			| ($timearray['mday'] << 16)
+			| ($timearray['hours'] << 11)
+			| ($timearray['minutes'] << 5)
+			| ($timearray['seconds'] >> 1);
+	}
+
+	   var $old_offset = 0;
+	   private function addFile($data, $filename, $time = 0)
+	   {
+		     $filename = str_replace('\\', '/', $filename);
+		     $dtime    = dechex(self::unix2DosTime($time));
+		     $hexdtime = '\x' . $dtime[6] . $dtime[7]
+		     . '\x' . $dtime[4] . $dtime[5]. '\x'
+		     . $dtime[2] . $dtime[3]. '\x'
+		     . $dtime[0] . $dtime[1];
+
+		     eval('$hexdtime = "' . $hexdtime . '";');
+
+		     $fr       = "\x50\x4b\x03\x04";
+		     $fr      .= "\x14\x00";
+		     $fr      .= "\x00\x00";
+		     $fr      .= "\x08\x00";
+		     $fr      .= $hexdtime;
+		     $unc_len  = strlen($data);
+		     $crc      = crc32($data);
+		     $zdata    = gzcompress($data);
+		     $c_len    = strlen($zdata);
+		     $zdata    = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
+		     $fr      .= pack('V', $crc);
+		     $fr      .= pack('V', $c_len);
+		     $fr      .= pack('V', $unc_len);
+		     $fr      .= pack('v', strlen($filename));
+		     $fr      .= pack('v', 0);
+		     $fr      .= $filename;
+		     $fr      .= $zdata;
+		     $fr      .= pack('V', $crc);
+		     $fr      .= pack('V', $c_len);
+		     $fr      .= pack('V', $unc_len);
+		     $this->datasec[] = $fr;
+		     $new_offset      = strlen(implode('', $this->datasec));
+		     $cdrec  = "\x50\x4b\x01\x02";
+		     $cdrec .= "\x00\x00";
+		     $cdrec .= "\x14\x00";
+		     $cdrec .= "\x00\x00";
+		     $cdrec .= "\x08\x00";
+		     $cdrec .= $hexdtime;
+		     $cdrec .= pack('V', $crc);
+		     $cdrec .= pack('V', $c_len);
+		     $cdrec .= pack('V', $unc_len);
+		     $cdrec .= pack('v', strlen($filename) );
+		     $cdrec .= pack('v', 0 );
+		     $cdrec .= pack('v', 0 );
+		     $cdrec .= pack('v', 0 );
+		     $cdrec .= pack('v', 0 );
+		     $cdrec .= pack('V', 32 );
+		     $cdrec .= pack('V', $this->old_offset );
+		     $this->old_offset = $new_offset;
+		     $cdrec .= $filename;
+
+		     $this->ctrl_dir[] = $cdrec;
+	 }
+
+	var $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
+	private function file(){
+		$data    = implode('', $this->datasec);
+		$ctrldir = implode('', $this->ctrl_dir);
+		return   $data . $ctrldir. $this->eof_ctrl_dir
+			.pack('v', sizeof($this->ctrl_dir))
+			.pack('v', sizeof($this->ctrl_dir))
+			.pack('V', strlen($ctrldir))
+			.pack('V', strlen($data)). "\x00\x00";
+	}
+
+	// ------------------------------------------------------ //
+	// #压缩到服务器        //
+	// $archive = new PHPZip();
+	// $archive->Zip("需压缩的文件所在目录", "ZIP压缩文件名");
+	// ------------------------------------------------------ //
+	 public function Zip($dir, $saveName)
+	 {
+		 if(@!function_exists('gzcompress'))
+		 {
+		 	ECHO 'fuck';exit;
+		 	return;
+		 }
+
+		 $filelist = self::visitFile($dir);
+		 if(count($filelist) == 0)
+		 { return; }
+
+		 foreach($filelist as $file)
+		 {
+			 if(!file_exists($file) || !is_file($file)){ continue; }
+			 $fd       = fopen($file, "rb");
+			 $content  = @fread($fd, filesize($file));
+			 fclose($fd);
+			 // 1.删除$dir的字符(./folder/file.txt删除./folder/)
+			  // 2.如果存在/就删除(/file.txt删除/)
+			  $file = substr($file, strlen($dir));
+			  if(substr($file, 0, 1) == "\\" || substr($file, 0, 1) == "/"){ $file = substr($file, 1); }
+			  self::addFile($content, $file);
+			 }
+			 $out = self::file();
+			 $fp = fopen($saveName, "wb");
+			 fwrite($fp, $out, strlen($out));
+			 fclose($fp);
+	 }
+
+	 // ------------------------------------------------------ //
+	 // #压缩并直接下载        //
+	 // $archive = new PHPZip();
+	 // $archive->ZipAndDownload("需压缩的文件所在目录");
+	 // ------------------------------------------------------ //
+	   public function ZipAndDownload($dir)
+	   {
+		   if(@!function_exists('gzcompress'))
+		   {
+		   		return;
+		   }
+
+		   $filelist = self::visitFile($dir);
+
+		   if(count($filelist) == 0)
+		   { return; }
+
+		   foreach($filelist as $file)
+		   {
+			   if(!file_exists($file) || !is_file($file)){ continue; }
+			   $fd       = fopen($file, "rb");
+			   $content  = @fread($fd, filesize($file));
+			   fclose($fd);
+
+			   // 1.删除$dir的字符(./folder/file.txt删除./folder/)
+			   // 2.如果存在/就删除(/file.txt删除/)
+			   $file = substr($file, strlen($dir));
+			   if(substr($file, 0, 1) == "\\" || substr($file, 0, 1) == "/")
+			   {
+		   	   	$file = substr($file, 1); }
+				self::addFile($content, $file);
+			   }
+				$out = self::file();
+				@header('Content-Encoding: none');
+				@header('Content-Type: application/zip');
+				@header('Content-Disposition: attachment ; filename=Farticle'.date("YmdHis", time()).'.zip');
+				@header('Pragma: no-cache');
+				@header('Expires: 0');
+				print($out);
+	   }
+
+    /*********************************************************** 解压部分 **********************************************************/
+    // ------------------------------------------------------ //
+    // ReadCentralDir($zip, $zipfile)
+    // $zip是经过@fopen($zipfile, 'rb')打开的
+    // $zipfile是zip文件的路径
+    // ------------------------------------------------------ //
+	private function ReadCentralDir($zip, $zipfile)
+	{
+		$size     = filesize($zipfile);
+		$max_size = ($size < 277) ? $size : 277;
+		@fseek($zip, $size - $max_size);
+		$pos   = ftell($zip);
+		$bytes = 0x00000000;
+		while($pos < $size){
+			$byte  = @fread($zip, 1);
+			$bytes = ($bytes << 8) | Ord($byte);
+			$pos++;
+			if($bytes == 0x504b0506){ break; }
+		}
+		$data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size',
+		fread($zip, 18));
+		$centd['comment']      = ($data['comment_size'] != 0) ? fread($zip, $data['comment_size']) : '';  // 注释
+		$centd['entries']      = $data['entries'];
+		$centd['disk_entries'] = $data['disk_entries'];
+		$centd['offset']       = $data['offset'];
+		$centd['disk_start']   = $data['disk_start'];
+		$centd['size']         = $data['size'];
+		$centd['disk']         = $data['disk'];
+		return $centd;
+	}
+
+
+   private function ReadCentralFileHeaders($zip)
+   {
+	    $binary_data = fread($zip, 46);
+	    $header      = unpack('vchkid/vid/vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $binary_data);
+	    $header['filename'] = ($header['filename_len'] != 0) ? fread($zip, $header['filename_len']) : '';
+	    $header['extra']    = ($header['extra_len']    != 0) ? fread($zip, $header['extra_len'])    : '';
+	    $header['comment']  = ($header['comment_len']  != 0) ? fread($zip, $header['comment_len'])  : '';
+
+	    if($header['mdate'] && $header['mtime'])
+	    {
+		    $hour    = ($header['mtime']  & 0xF800) >> 11;
+		    $minute  = ($header['mtime']  & 0x07E0) >> 5;
+		    $seconde = ($header['mtime']  & 0x001F) * 2;
+		    $year    = (($header['mdate'] & 0xFE00) >> 9) + 1980;
+		    $month   = ($header['mdate']  & 0x01E0) >> 5;
+		    $day     = $header['mdate']   & 0x001F;
+		    $header['mtime'] = mktime($hour, $minute, $seconde, $month, $day, $year);
+	    } else {
+	    $header['mtime'] = time();            }
+	    $header['stored_filename'] = $header['filename'];
+	    $header['status'] = 'ok';
+
+	    if(substr($header['filename'], -1) == '/'){
+	    	$header['external'] = 0x41FF0010;
+	    }  // 判断是否文件夹
+	    return $header;
+    }
+
+	private function ReadFileHeader($zip)
+	{
+		$binary_data = fread($zip, 30);
+		$data        = unpack('vchk/vid/vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $binary_data);
+		$header['filename']        = fread($zip, $data['filename_len']);
+		$header['extra']           = ($data['extra_len'] != 0) ? fread($zip, $data['extra_len']) : '';
+		$header['compression']     = $data['compression'];
+		$header['size']            = $data['size'];
+		$header['compressed_size'] = $data['compressed_size'];
+		$header['crc']             = $data['crc'];
+		$header['flag']            = $data['flag'];
+		$header['mdate']           = $data['mdate'];
+		$header['mtime']           = $data['mtime'];
+
+		if($header['mdate'] && $header['mtime']){
+			$hour    = ($header['mtime']  & 0xF800) >> 11;
+			$minute  = ($header['mtime']  & 0x07E0) >> 5;
+			$seconde = ($header['mtime']  & 0x001F) * 2;
+			$year    = (($header['mdate'] & 0xFE00) >> 9) + 1980;
+			$month   = ($header['mdate']  & 0x01E0) >> 5;
+			$day     = $header['mdate']   & 0x001F;
+			$header['mtime'] = mktime($hour, $minute, $seconde, $month, $day, $year);
+		}else{
+			$header['mtime'] = time();
+		}
+		$header['stored_filename'] = $header['filename'];
+		$header['status']          = "ok";
+		return $header;
+	}
+
+
+	private function ExtractFile($header, $to, $zip)
+	{
+		$header = self::readfileheader($zip);
+		if(substr($to, -1) != "/"){ $to .= "/"; }
+		if(!@is_dir($to)){ @mkdir($to, 0777); }
+		$pth = explode("/", dirname($header['filename']));
+		for($i=0; isset($pth[$i]); $i++){
+			if(!$pth[$i]){ continue; }
+			$pthss .= $pth[$i]."/";
+			if(!is_dir($to.$pthss)){ @mkdir($to.$pthss, 0777); }
+		}
+
+		if(!($header['external'] == 0x41FF0010) && !($header['external'] == 16))
+		{
+			if($header['compression'] == 0)
+			{
+			$fp = @fopen($to.$header['filename'], 'wb');
+			if(!$fp){ return(-1); }
+			$size = $header['compressed_size'];
+			while($size != 0)
+			{
+				$read_size   = ($size < 2048 ? $size : 2048);
+				$buffer      = fread($zip, $read_size);
+				$binary_data = pack('a'.$read_size, $buffer);
+				@fwrite($fp, $binary_data, $read_size);
+				$size       -= $read_size;
+			}
+
+				fclose($fp);
+				touch($to.$header['filename'], $header['mtime']);
+			}else{
+				$fp = @fopen($to.$header['filename'].'.gz', 'wb');
+				if(!$fp)
+				{
+					return(-1);
+				}
+
+				$binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($header['compression']), Chr(0x00), time(), Chr(0x00), Chr(3));
+				fwrite($fp, $binary_data, 10);
+				$size = $header['compressed_size'];
+				while($size != 0)
+				{
+					$read_size   = ($size < 1024 ? $size : 1024);
+					$buffer      = fread($zip, $read_size);
+					$binary_data = pack('a'.$read_size, $buffer);
+					@fwrite($fp, $binary_data, $read_size);
+					$size       -= $read_size;
+				}
+				$binary_data = pack('VV', $header['crc'], $header['size']);
+				fwrite($fp, $binary_data, 8);
+				fclose($fp);
+				$gzp = @gzopen($to.$header['filename'].'.gz', 'rb') or die("Cette archive est compress!");
+				if(!$gzp){ return(-2); }
+					$fp = @fopen($to.$header['filename'], 'wb');
+				if(!$fp)
+				{
+					return(-1);
+				}
+
+				$size = $header['size'];
+				while($size != 0)
+				 {
+				 	$read_size   = ($size < 2048 ? $size : 2048);
+				 	$buffer      = gzread($gzp, $read_size);
+				 	$binary_data = pack('a'.$read_size, $buffer);
+				 	@fwrite($fp, $binary_data, $read_size);
+				 	$size       -= $read_size;
+				 }
+			 	fclose($fp); gzclose($gzp);
+			 	touch($to.$header['filename'], $header['mtime']);
+			 	@unlink($to.$header['filename'].'.gz');
+			}
+		}
+
+		return true;
+	}
+
+		// ------------------------------------------------------ //
+		// #解压文件        //
+		// $archive   = new PHPZip();
+		// $zipfile   = "ZIP压缩文件名";
+		// $savepath  = "解压缩目录名";
+		// $zipfile   = $unzipfile;
+		// $savepath  = $unziptarget;
+		// $array     = $archive->GetZipInnerFilesInfo($zipfile);
+		// $filecount = 0;
+		// $dircount  = 0;
+		// $failfiles = array();
+		// set_time_limit(0);
+		// 修改为不限制超时时间(默认为30秒)
+		//
+		// for($i=0; $i<count($array); $i++) {
+		//     if($array[$i][folder] == 0){
+		//         if($archive->unZip($zipfile, $savepath, $i) > 0){
+		//             $filecount++;
+		//         }else{
+		//             $failfiles[] = $array[$i][filename];
+		//         }
+		//     }else{
+		//         $dircount++;
+		//     }
+		// }
+		// set_time_limit(30);
+		//printf("文件夹:%d&nbsp;&nbsp;&nbsp;&nbsp;解压文件:%d&nbsp;&nbsp;&nbsp;&nbsp;失败:%d<br>\r\n", $dircount, $filecount, count($failfiles));
+		//if(count($failfiles) > 0){
+		//    foreach($failfiles as $file){
+		//        printf("&middot;%s<br>\r\n", $file);
+		//    }
+		//}
+		    // ------------------------------------------------------ //
+
+		    public function unZip($zipfile, $to, $index = Array(-1))
+		    {
+		    	$ok  = 0;
+		    	$zip = @fopen($zipfile, 'rb');
+		    	if(!$zip){ return(-1); }
+		    	$cdir      = self::ReadCentralDir($zip, $zipfile);
+		    	$pos_entry = $cdir['offset'];
+		    	if(!is_array($index)){ $index = array($index); }
+		    	for($i=0; $index[$i]; $i++)
+		    	{
+		    		if(intval($index[$i]) != $index[$i] || $index[$i] > $cdir['entries'])
+		    		{
+		    			return(-1);
+		    		}
+		    	}
+		    	for($i=0; $i<$cdir['entries']; $i++)
+		    	{
+		    		@fseek($zip, $pos_entry);
+		    		$header          = self::ReadCentralFileHeaders($zip);
+		    		$header['index'] = $i;
+		    		$pos_entry       = ftell($zip);
+		    		@rewind($zip);
+		    		fseek($zip, $header['offset']);
+		    		if(in_array("-1", $index) || in_array($i, $index))
+		    		{
+		    			$stat[$header['filename']] = self::ExtractFile($header, $to, $zip);
+		    		}
+		    	}
+		    	fclose($zip);
+		    	return $stat;
+		    }
+
+		     /**********************************************************         * 其它部分         **********************************************************/
+		    // ------------------------------------------------------ //
+		     // #获取被压缩文件的信息        //
+		     // $archive = new PHPZip();
+		     // $array = $archive->GetZipInnerFilesInfo(ZIP压缩文件名);
+		     // for($i=0; $i<count($array); $i++) {
+		     //     printf("<b>&middot;%s</b><br>\r\n", $array[$i][filename]);
+		      //     foreach($array[$i] as $key => $value)
+		      //         printf("%s => %s<br>\r\n", $key, $value);
+		      //     print "\r\n<p>------------------------------------<p>\r\n\r\n";
+		      // }
+		      // ------------------------------------------------------ //
+		      public function GetZipInnerFilesInfo($zipfile)
+		      {
+			      	$zip = @fopen($zipfile, 'rb');
+			      	if(!$zip){ return(0); }
+			      	$centd = self::ReadCentralDir($zip, $zipfile);
+			      	@rewind($zip);
+			      	@fseek($zip, $centd['offset']);
+			      	$ret = array();
+			      	for($i=0; $i<$centd['entries']; $i++)
+			      	{
+			      		$header          = self::ReadCentralFileHeaders($zip);
+			      		$header['index'] = $i;
+			      		$info = array(
+			      		'filename'        => $header['filename'], // 文件名
+			      		'stored_filename' => $header['stored_filename'],            // 压缩后文件名
+			      		'size'            => $header['size'],                       // 大小
+			      		'compressed_size' => $header['compressed_size'],            // 压缩后大小
+			      		'crc'             => strtoupper(dechex($header['crc'])),    // CRC32
+			      		'mtime'           => date("Y-m-d H:i:s",$header['mtime']),  // 文件修改时间
+			      		'comment'         => $header['comment'],                    // 注释
+			      		'folder'          => ($header['external'] == 0x41FF0010 || $header['external'] == 16) ? 1 : 0,  // 是否为文件夹
+			      		'index'           => $header['index'],                      // 文件索引
+			      		'status'          => $header['status']                      // 状态
+			      		 );
+			      		 $ret[] = $info;
+			      		 unset($header);
+			      	}
+			      	fclose($zip);
+			      	return $ret;
+		      }
+
+      // ------------------------------------------------------ //
+      // #获取压缩文件的注释        //
+      // $archive = new PHPZip();
+      // echo $archive->GetZipComment(ZIP压缩文件名);
+      // ------------------------------------------------------ //
+      public function GetZipComment($zipfile)
+      {
+	      $zip = @fopen($zipfile, 'rb');
+	      if(!$zip){ return(0); }
+	      $centd = self::ReadCentralDir($zip, $zipfile);
+	      fclose($zip);
+	      return $centd[comment];
+      }
+}
+?>

+ 240 - 0
Ainaphp/Lib/ORG/RBAC.class.php

@@ -0,0 +1,240 @@
+<?php
+
+/**
+ +------------------------------------------------------------------------------
+ * 基于角色的数据库方式验证类
+ +------------------------------------------------------------------------------
+ * @category   ORG
+ * @package  ORG
+ * @subpackage  Util
+ * @author    liu21st <liu21st@gmail.com>
+ * @version   $Id$
+ +------------------------------------------------------------------------------
+ */
+// 配置文件增加设置
+// USER_AUTH_ON 是否需要认证
+// USER_AUTH_TYPE 认证类型
+// USER_AUTH_KEY 认证识别号
+// REQUIRE_AUTH_MODULE  需要认证模块
+// NOT_AUTH_MODULE 无需认证模块
+// USER_AUTH_GATEWAY 认证网关
+
+class RBAC extends Think
+{
+    // 认证方法
+    static public function authenticate($map,$model='')
+    {
+        if(empty($model)) $model =  C('USER_AUTH_MODEL');
+        //使用给定的Map进行认证
+        return M($model)->where($map)->find();
+    }
+
+    //用于检测用户权限的方法,并保存到Session中
+    static function saveAccessList($authId=null)
+    {
+        if(null===$authId)   $authId = $_SESSION[C('USER_AUTH_KEY')];
+        // 如果使用普通权限模式,保存当前用户的访问权限列表
+        // 对管理员开发所有权限
+        if(C('USER_AUTH_TYPE') !=2 && !$_SESSION[C('ADMIN_AUTH_KEY')] )
+            $_SESSION['_ACCESS_LIST']	=	RBAC::getAccessList($authId);
+        return ;
+    }
+
+	// 取得模块的所属记录访问权限列表 返回有权限的记录ID数组
+	static function getRecordAccessList($authId=null,$module='') {
+        if(null===$authId)   $authId = $_SESSION[C('USER_AUTH_KEY')];
+        if(empty($module))  $module	=	MODULE_NAME;
+        //获取权限访问列表
+        $accessList = RBAC::getModuleAccessList($authId,$module);
+        return $accessList;
+	}
+
+    //检查当前操作是否需要认证
+    static function checkAccess()
+    {
+        //如果项目要求认证,并且当前模块需要认证,则进行权限认证
+        if( C('USER_AUTH_ON') ){
+			$_module	=	array();
+			$_action	=	array();
+            if("" != C('REQUIRE_AUTH_MODULE')) {
+                //需要认证的模块
+                $_module['yes'] = explode(',',strtoupper(C('REQUIRE_AUTH_MODULE')));
+            }else {
+                //无需认证的模块
+                $_module['no'] = explode(',',strtoupper(C('NOT_AUTH_MODULE')));
+            }
+            //检查当前模块是否需要认证
+            if((!empty($_module['no']) && !in_array(strtoupper(MODULE_NAME),$_module['no'])) || (!empty($_module['yes']) && in_array(strtoupper(MODULE_NAME),$_module['yes']))) {
+				if("" != C('REQUIRE_AUTH_ACTION')) {
+					//需要认证的操作
+					$_action['yes'] = explode(',',strtoupper(C('REQUIRE_AUTH_ACTION')));
+				}else {
+					//无需认证的操作
+					$_action['no'] = explode(',',strtoupper(C('NOT_AUTH_ACTION')));
+				}
+				//检查当前操作是否需要认证
+				if((!empty($_action['no']) && !in_array(strtoupper(ACTION_NAME),$_action['no'])) || (!empty($_action['yes']) && in_array(strtoupper(ACTION_NAME),$_action['yes']))) {
+					return true;
+				}else {
+					return false;
+				}
+            }else {
+                return false;
+            }
+        }
+        return false;
+    }
+
+	// 登录检查
+	static public function checkLogin() {
+        //检查当前操作是否需要认证
+        if(RBAC::checkAccess()) {
+            //检查认证识别号
+            if(!$_SESSION[C('USER_AUTH_KEY')]) {
+                if(C('GUEST_AUTH_ON')) {
+                    // 开启游客授权访问
+                    if(!isset($_SESSION['_ACCESS_LIST']))
+                        // 保存游客权限
+                        RBAC::saveAccessList(C('GUEST_AUTH_ID'));
+                }else{
+                    // 禁止游客访问跳转到认证网关
+                    redirect(PHP_FILE.C('USER_AUTH_GATEWAY'));
+                }
+            }
+        }
+        return true;
+	}
+
+    //权限认证的过滤器方法
+    static public function AccessDecision($appName=APP_NAME)
+    {
+        //检查是否需要认证
+        if(RBAC::checkAccess()) {
+            //存在认证识别号,则进行进一步的访问决策
+            $accessGuid   =   md5($appName.MODULE_NAME.ACTION_NAME);
+            if(empty($_SESSION[C('ADMIN_AUTH_KEY')])) {
+                if(C('USER_AUTH_TYPE')==2) {
+                    //加强验证和即时验证模式 更加安全 后台权限修改可以即时生效
+                    //通过数据库进行访问检查
+                    $accessList = RBAC::getAccessList($_SESSION[C('USER_AUTH_KEY')]);
+                }else {
+                    // 如果是管理员或者当前操作已经认证过,无需再次认证
+                    if( $_SESSION[$accessGuid]) {
+                        return true;
+                    }
+                    //登录验证模式,比较登录后保存的权限访问列表
+                    $accessList = $_SESSION['_ACCESS_LIST'];
+                }
+                //判断是否为组件化模式,如果是,验证其全模块名
+                $module = defined('P_MODULE_NAME')?  P_MODULE_NAME   :   MODULE_NAME;
+                if(!isset($accessList[strtoupper($appName)][strtoupper($module)][strtoupper(ACTION_NAME)])) {
+                    $_SESSION[$accessGuid]  =   false;
+                    return false;
+                }
+                else {
+                    $_SESSION[$accessGuid]	=	true;
+                }
+            }else{
+                //管理员无需认证
+				return true;
+			}
+        }
+        return true;
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 取得当前认证号的所有权限列表
+     +----------------------------------------------------------
+     * @param integer $authId 用户ID
+     +----------------------------------------------------------
+     * @access public
+     +----------------------------------------------------------
+     */
+    static public function getAccessList($authId)
+    {
+        // Db方式权限数据
+        $db     =   Db::getInstance();
+        $table = array('role'=>C('RBAC_ROLE_TABLE'),'user'=>C('RBAC_USER_TABLE'),'access'=>C('RBAC_ACCESS_TABLE'),'node'=>C('RBAC_NODE_TABLE'));
+        $sql    =   "select node.id,node.name from ".
+                    $table['role']." as role,".
+                    $table['user']." as user,".
+                    $table['access']." as access ,".
+                    $table['node']." as node ".
+                    "where user.user_id='{$authId}' and user.role_id=role.id and ( access.role_id=role.id  or (access.role_id=role.pid and role.pid!=0 ) ) and role.status=1 and access.node_id=node.id and node.level=1 and node.status=1";
+        $apps =   $db->query($sql);
+        $access =  array();
+        foreach($apps as $key=>$app) {
+            $appId	=	$app['id'];
+            $appName	 =	 $app['name'];
+            // 读取项目的模块权限
+            $access[strtoupper($appName)]   =  array();
+            $sql    =   "select node.id,node.name from ".
+                    $table['role']." as role,".
+                    $table['user']." as user,".
+                    $table['access']." as access ,".
+                    $table['node']." as node ".
+                    "where user.user_id='{$authId}' and user.role_id=role.id and ( access.role_id=role.id  or (access.role_id=role.pid and role.pid!=0 ) ) and role.status=1 and access.node_id=node.id and node.level=2 and node.pid={$appId} and node.status=1";
+            $modules =   $db->query($sql);
+            // 判断是否存在公共模块的权限
+            $publicAction  = array();
+            foreach($modules as $key=>$module) {
+                $moduleId	 =	 $module['id'];
+                $moduleName = $module['name'];
+                if('PUBLIC'== strtoupper($moduleName)) {
+                $sql    =   "select node.id,node.name from ".
+                    $table['role']." as role,".
+                    $table['user']." as user,".
+                    $table['access']." as access ,".
+                    $table['node']." as node ".
+                    "where user.user_id='{$authId}' and user.role_id=role.id and ( access.role_id=role.id  or (access.role_id=role.pid and role.pid!=0 ) ) and role.status=1 and access.node_id=node.id and node.level=3 and node.pid={$moduleId} and node.status=1";
+                    $rs =   $db->query($sql);
+                    foreach ($rs as $a){
+                        $publicAction[$a['name']]	 =	 $a['id'];
+                    }
+                    unset($modules[$key]);
+                    break;
+                }
+            }
+            // 依次读取模块的操作权限
+            foreach($modules as $key=>$module) {
+                $moduleId	 =	 $module['id'];
+                $moduleName = $module['name'];
+                $sql    =   "select node.id,node.name from ".
+                    $table['role']." as role,".
+                    $table['user']." as user,".
+                    $table['access']." as access ,".
+                    $table['node']." as node ".
+                    "where user.user_id='{$authId}' and user.role_id=role.id and ( access.role_id=role.id  or (access.role_id=role.pid and role.pid!=0 ) ) and role.status=1 and access.node_id=node.id and node.level=3 and node.pid={$moduleId} and node.status=1";
+                $rs =   $db->query($sql);
+                $action = array();
+                foreach ($rs as $a){
+                    $action[$a['name']]	 =	 $a['id'];
+                }
+                // 和公共模块的操作权限合并
+                $action += $publicAction;
+                $access[strtoupper($appName)][strtoupper($moduleName)]   =  array_change_key_case($action,CASE_UPPER);
+            }
+        }
+        return $access;
+    }
+
+	// 读取模块所属的记录访问权限
+	static public function getModuleAccessList($authId,$module) {
+        // Db方式
+        $db     =   Db::getInstance();
+        $table = array('role'=>C('RBAC_ROLE_TABLE'),'user'=>C('RBAC_USER_TABLE'),'access'=>C('RBAC_ACCESS_TABLE'));
+        $sql    =   "select access.node_id from ".
+                    $table['role']." as role,".
+                    $table['user']." as user,".
+                    $table['access']." as access ".
+                    "where user.user_id='{$authId}' and user.role_id=role.id and ( access.role_id=role.id  or (access.role_id=role.pid and role.pid!=0 ) ) and role.status=1 and  access.module='{$module}' and access.status=1";
+        $rs =   $db->query($sql);
+        $access	=	array();
+        foreach ($rs as $node){
+            $access[]	=	$node['node_id'];
+        }
+		return $access;
+	}
+}//end class
+?>

Datei-Diff unterdrückt, da er zu groß ist
+ 123 - 0
Ainaphp/Lib/ORG/String.class.php


+ 68 - 0
Ainaphp/Lib/ORG/SysCrypt.class.php

@@ -0,0 +1,68 @@
+<?php
+/*===========================================================
+= 版权协议:
+= GPL (The GNU GENERAL PUBLIC LICENSE Version 2, June 1991)
+=------------------------------------------------------------
+= 文件名称:cls.sys_crypt.php
+= 摘    要:php加密解密处理类
+= 版    本:1.0
+= 参    考:Discuz论坛的passport相关函数
+=------------------------------------------------------------
+= Script Written By PHPWMS项目组
+= 最后更新:xinge
+= 最后日期:2007-12-09
+
+
+$sc = new SysCrypt('phpwms');
+$text = '110';
+print($sc -> php_encrypt($text));
+print('<br>');
+print($sc -> php_decrypt($sc -> php_encrypt($text)));
+============================================================*/
+class SysCrypt extends Think {
+
+	private $crypt_key;
+
+	// 构造函数
+	public function __construct($crypt_key) {
+	   $this -> crypt_key = $crypt_key;
+	}
+
+	public function php_encrypt($txt) {
+	   srand((double)microtime() * 1000000);
+	   $encrypt_key = md5(rand(0,32000));
+	   $ctr = 0;
+	   $tmp = '';
+	   for($i = 0;$i<strlen($txt);$i++) {
+		$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
+		$tmp .= $encrypt_key[$ctr].($txt[$i]^$encrypt_key[$ctr++]);
+	   }
+	   return base64_encode(self::__key($tmp,$this -> crypt_key));
+	}
+
+	public function php_decrypt($txt) {
+	   $txt = self::__key(base64_decode($txt),$this -> crypt_key);
+	   $tmp = '';
+	   for($i = 0;$i < strlen($txt); $i++) {
+		$md5 = $txt[$i];
+		$tmp .= $txt[++$i] ^ $md5;
+	   }
+	   return $tmp;
+	}
+
+	private function __key($txt,$encrypt_key) {
+	   $encrypt_key = md5($encrypt_key);
+	   $ctr = 0;
+	   $tmp = '';
+	   for($i = 0; $i < strlen($txt); $i++) {
+		$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
+		$tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
+	   }
+	   return $tmp;
+	}
+
+	public function __destruct() {
+	   $this -> crypt_key = null;
+	}
+}
+?>

+ 93 - 0
Ainaphp/Lib/ORG/Tree.class.php

@@ -0,0 +1,93 @@
+<?php
+class Tree extends Think {
+
+	public $arr = array();
+	public $icon = array('│','├','└');
+	public $nbsp = "&nbsp;";
+	public $ret = '';
+	public $level = 0;
+
+    public function __construct($arr=array()) {
+         $this->arr = $arr;
+	     $this->ret = '';
+	     return is_array($arr);
+    }
+
+	public function getchild($bid){
+		$a = $newarr = array();
+		if(is_array($this->arr)){
+			foreach($this->arr as $id => $a){
+				if($a['parentid'] == $bid) $newarr[$id] = $a;
+			}
+		}
+		return $newarr ? $newarr : false;
+	}
+
+	function get_tree($bid, $str, $sid = 0, $adds = '', $strgroup = ''){
+		$number=1;
+		$child = $this->getchild($bid);
+		if(is_array($child)){
+		    $total = count($child);
+			foreach($child as $id=>$a){
+				$j=$k='';
+				if($number==$total){
+					$j .= $this->icon[2];
+				}else{
+					$j .= $this->icon[1];
+					$k = $adds ? $this->icon[0] : '';
+				}
+				$spacer = $adds ? $adds.$j : '';
+
+				@extract($a);
+				if(empty($a['selected'])){$selected = $id==$sid ? 'selected' : '';}
+				$parentid == 0 && $strgroup ? eval("\$newstr = \"$strgroup\";") : eval("\$newstr = \"$str\";");
+				$this->ret .= $newstr;
+				$nbsp = $this->nbsp;
+				$this->get_tree($id, $str, $sid, $adds.$k.$nbsp,$strgroup);
+				$number++;
+			}
+		}
+		return $this->ret;
+	}
+
+	function get_nav($bid,$maxlevel,$effected_id='navlist',$style='filetree ' ,$homefont='',$recursion=FALSE ,$child='',$enhomefont='',$lang='') {
+
+		if($enhomefont) $indexen =  '<em>'.$enhomefont.'</em>';
+		if($homefont) $homefont='<li id="nav_0"><span class="fl_ico"></span><a href="'.URL().'" title="'.L(HOME_FONT).'"><span class="fl">'.L(HOME_FONT).'</span>'.$indexen.'</a></li>';
+
+		$number=1;
+		if(!$child) $child = $this->getchild($bid);
+		$total = count($child);
+		$effected = $effected_id ?  ' id="'.$effected_id.'_box"' : '';
+		$class=  $style? ' class="'.$style.'"' : '';
+        if(!$recursion)	$this->ret .='<ul'.$effected.$class.'>'.$homefont;
+        foreach($child as $id=>$a) {
+        	@extract($a);
+			if(!$this->level){
+				$this->level= $level ? $level+$maxlevel-1 : $maxlevel;
+			}
+
+			$ischild =$this->getchild($id);
+			$foldertype =  $ischild ? 'folder' : 'file';
+        	$floder_status = ' id="'.$effected_id.'_'.$id.'"';
+			$first = $number==1 ?   'first ' : '';
+			$floder_status .=  $number==$total ?  ' class="foot '.$foldertype.'"' :  ' class="'.$first.$foldertype.'"';
+			$this->ret .= $recursion ? '<ul><li'.$floder_status.'>' : '<li'.$floder_status.'>';
+            $recursion = FALSE;
+			if($enhomefont){
+				$enzm = $enname ? '<em>'.$enname.'</em>' :  '<em>'.$catdir.'</em>';
+			}
+            if($ischild && $level < $this->level){
+				$this->ret .= '<span class="fd_ico"></span><a href="'.$url.'" title="'.$catname.'"><span class="fd">'.$catname.'</span>'.$enzm.'</a>';
+                $this->get_nav($id,$maxlevel,$effected_id,$style,'',TRUE,$ischild,$enhomefont,$lang);
+            } else {
+			   $this->ret .= '<span class="fl_ico"></span><a href="'.$url.'" title="'.$catname.'"><span class="fl">'.$catname.'</span>'.$enzm.'</a>';
+            }
+           $this->ret .=$recursion ? '</li></ul>': '</li>';
+		   $number++;
+        }
+        if(!$recursion)  $this->ret .='</ul>';
+        return $this->ret;
+    }
+}
+?>

+ 631 - 0
Ainaphp/Lib/ORG/UploadFile.class.php

@@ -0,0 +1,631 @@
+<?php
+/**
+ +------------------------------------------------------------------------------
+ * 文件上传类
+ +------------------------------------------------------------------------------
+ * @category   ORG
+ * @package  ORG
+ * @subpackage  Net
+ * @author    liu21st <liu21st@gmail.com>
+ * @version   $Id$
+ +------------------------------------------------------------------------------
+ */
+class UploadFile extends Think
+{//类定义开始
+
+    // 上传文件的最大值
+    public $maxSize = -1;
+
+    // 是否支持多文件上传
+    public $supportMulti = true;
+
+    // 允许上传的文件后缀
+    //  留空不作后缀检查
+    public $allowExts = array();
+
+    // 允许上传的文件类型
+    // 留空不做检查
+    public $allowTypes = array();
+
+    // 使用对上传图片进行缩略图处理
+    public $thumb   =  false;
+    // 图库类包路径
+    public $imageClassPath = 'ORG.Util.Image';
+    // 缩略图最大宽度
+    public $thumbMaxWidth;
+    // 缩略图最大高度
+    public $thumbMaxHeight;
+    // 缩略图前缀
+    public $thumbPrefix   =  'thumb_';
+    public $thumbSuffix  =  '';
+    // 缩略图保存路径
+    public $thumbPath = '';
+    // 缩略图文件名
+    public $thumbFile		=	'';
+    // 是否移除原图
+    public $thumbRemoveOrigin = false;
+    // 压缩图片文件上传
+    public $zipImages = false;
+    // 启用子目录保存文件
+    public $autoSub   =  false;
+    // 子目录创建方式 可以使用hash date
+    public $subType   = 'hash';
+    public $dateFormat = 'Ymd';
+    public $hashLevel =  1; // hash的目录层次
+    // 上传文件保存路径
+    public $savePath = '';
+    public $autoCheck = true; // 是否自动检查附件
+    // 存在同名是否覆盖
+    public $uploadReplace = false;
+
+    // 上传文件命名规则
+    // 例如可以是 time uniqid com_create_guid 等
+    // 必须是一个无需任何参数的函数名 可以使用自定义函数
+    public $saveRule = '';
+
+    // 上传文件Hash规则函数名
+    // 例如可以是 md5_file sha1_file 等
+    public $hashType = 'md5_file';
+
+    // 错误信息
+    private $error = '';
+
+    // 上传成功的文件信息
+    private $uploadFileInfo ;
+
+    /**
+     +----------------------------------------------------------
+     * 架构函数
+     +----------------------------------------------------------
+     * @access public
+     +----------------------------------------------------------
+     */
+    public function __construct($maxSize='',$allowExts='',$allowTypes='',$savePath='',$saveRule='')
+    {
+        if(!empty($maxSize) && is_numeric($maxSize)) {
+            $this->maxSize = $maxSize;
+        }
+        if(!empty($allowExts)) {
+            if(is_array($allowExts)) {
+                $this->allowExts = array_map('strtolower',$allowExts);
+            }else {
+                $this->allowExts = explode(',',strtolower($allowExts));
+            }
+        }
+        if(!empty($allowTypes)) {
+            if(is_array($allowTypes)) {
+                $this->allowTypes = array_map('strtolower',$allowTypes);
+            }else {
+                $this->allowTypes = explode(',',strtolower($allowTypes));
+            }
+        }
+        if(!empty($saveRule)) {
+            $this->saveRule = $saveRule;
+        }else{
+            $this->saveRule	=	C('UPLOAD_FILE_RULE');
+        }
+        $this->savePath = $savePath;
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 上传一个文件
+     +----------------------------------------------------------
+     * @access public
+     +----------------------------------------------------------
+     * @param mixed $name 数据
+     * @param string $value  数据表名
+     +----------------------------------------------------------
+     * @return string
+     +----------------------------------------------------------
+     * @throws ThinkExecption
+     +----------------------------------------------------------
+     */
+
+
+    private function save($file)
+    {
+        $filename = $file['savepath'].$file['savename'];
+        if(!$this->uploadReplace && is_file($filename)) {
+            // 不覆盖同名文件
+            $this->error	=	'文件已经存在!'.$filename;
+            return false;
+        }
+        // 如果是图像文件 检测文件格式
+        if( in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png','swf')) && false === getimagesize($file['tmp_name'])) {
+            $this->error = '非法图像文件';
+            return false;
+        }
+
+		if(in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png')) && getimagesize($file['tmp_name'])) {
+			$tmp_imagesize = @getimagesize($file['tmp_name']);
+			list($tmp_width, $tmp_height, $tmp_type) = (array)$tmp_imagesize;
+			$tmp_size = $tmp_width * $tmp_height;
+			if($tmp_size > 16777216 || $tmp_size < 4 || empty($tmp_type) || strpos($tmp_imagesize['mime'], 'flash') > 0) {
+				@unlink($file['tmp_name']);
+				$this->error = '非法图像文件';
+				return false;
+			}
+		}
+
+
+        if(!move_uploaded_file($file['tmp_name'], auto_charset($filename,'utf-8','gbk'))) {
+            $this->error = '文件上传保存错误!';
+            return false;
+        }
+        if($this->thumb && in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png'))) {
+            $image =  getimagesize($filename);
+            if(false !== $image) {
+                //是图像文件生成缩略图
+                $thumbWidth		=	explode(',',$this->thumbMaxWidth);
+                $thumbHeight		=	explode(',',$this->thumbMaxHeight);
+                $thumbPrefix		=	explode(',',$this->thumbPrefix);
+                $thumbSuffix = explode(',',$this->thumbSuffix);
+                $thumbFile			=	explode(',',$this->thumbFile);
+                $thumbPath    =  $this->thumbPath?$this->thumbPath:$file['savepath'];
+                // 生成图像缩略图
+                import($this->imageClassPath);
+                $realFilename  =  $this->autoSub?basename($file['savename']):$file['savename'];
+                for($i=0,$len=count($thumbWidth); $i<$len; $i++) {
+                    $thumbname	=	$thumbPath.$thumbPrefix[$i].substr($realFilename,0,strrpos($realFilename, '.')).$thumbSuffix[$i].'.'.$file['extension'];
+                    Image::thumb($filename,$thumbname,'',$thumbWidth[$i],$thumbHeight[$i],true);
+                }
+                if($this->thumbRemoveOrigin) {
+                    // 生成缩略图之后删除原图
+                    unlink($filename);
+                }
+            }
+        }
+        if($this->zipImags) {
+            // TODO 对图片压缩包在线解压
+
+        }
+        return true;
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 上传所有文件
+     +----------------------------------------------------------
+     * @access public
+     +----------------------------------------------------------
+     * @param string $savePath  上传文件保存路径
+     +----------------------------------------------------------
+     * @return string
+     +----------------------------------------------------------
+     * @throws ThinkExecption
+     +----------------------------------------------------------
+     */
+    public function upload($savePath ='')
+    {
+        //如果不指定保存文件名,则由系统默认
+        if(empty($savePath))
+            $savePath = $this->savePath;
+        // 检查上传目录
+        if(!is_dir($savePath)) {
+            // 检查目录是否编码后的
+            if(is_dir(base64_decode($savePath))) {
+                $savePath	=	base64_decode($savePath);
+            }else{
+                // 尝试创建目录
+                if(!mkdir($savePath)){
+                    $this->error  =  '上传目录'.$savePath.'不存在';
+                    return false;
+                }
+            }
+        }else {
+            if(!is_writeable($savePath)) {
+                $this->error  =  '上传目录'.$savePath.'不可写';
+                return false;
+            }
+        }
+        $fileInfo = array();
+        $isUpload   = false;
+
+        // 获取上传的文件信息
+        // 对$_FILES数组信息处理
+        $files	 =	 $this->dealFiles($_FILES);
+        foreach($files as $key => $file) {
+            //过滤无效的上传
+            if(!empty($file['name'])) {
+                //登记上传文件的扩展信息
+                $file['key']          =  $key;
+                $file['extension']  = strtolower($this->getExt($file['name']));
+                $file['savepath']   = $savePath;
+                $file['savename']   = strtolower($this->getSaveName($file));
+
+                // 自动检查附件
+                if($this->autoCheck) {
+                    if(!$this->check($file))
+                        return false;
+                }
+
+                //保存上传文件
+                if(!$this->save($file)) return false;
+                if(function_exists($this->hashType)) {
+                    $fun =  $this->hashType;
+                    $file['hash']   =  $fun(auto_charset($file['savepath'].$file['savename'],'utf-8','gbk'));
+                }
+                //上传成功后保存文件信息,供其他地方调用
+                unset($file['tmp_name'],$file['error']);
+                $fileInfo[] = $file;
+                $isUpload   = true;
+            }
+        }
+        if($isUpload) {
+            $this->uploadFileInfo = $fileInfo;
+            return true;
+        }else {
+            $this->error  =  '没有选择上传文件';
+            return false;
+        }
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 上传单个上传字段中的文件 支持多附件
+     +----------------------------------------------------------
+     * @access public
+     +----------------------------------------------------------
+     * @param array $file  上传文件信息
+     * @param string $savePath  上传文件保存路径
+     +----------------------------------------------------------
+     * @return string
+     +----------------------------------------------------------
+     * @throws ThinkExecption
+     +----------------------------------------------------------
+     */
+    public function uploadOne($file,$savePath=''){
+        //如果不指定保存文件名,则由系统默认
+        if(empty($savePath))
+            $savePath = $this->savePath;
+        // 检查上传目录
+        if(!is_dir($savePath)) {
+            // 尝试创建目录
+            if(!mk_dir($savePath)){
+                $this->error  =  '上传目录'.$savePath.'不存在';
+                return false;
+            }
+        }else {
+            if(!is_writeable($savePath)) {
+                $this->error  =  '上传目录'.$savePath.'不可写';
+                return false;
+            }
+        }
+        //过滤无效的上传
+        if(!empty($file['name'])) {
+            $fileArray = array();
+            if(is_array($file['name'])) {
+               $keys = array_keys($file);
+               $count	 =	 count($file['name']);
+               for ($i=0; $i<$count; $i++) {
+                   foreach ($keys as $key)
+                       $fileArray[$i][$key] = $file[$key][$i];
+               }
+            }else{
+                $fileArray[] =  $file;
+            }
+            $info =  array();
+            foreach ($fileArray as $key=>$file){
+                //登记上传文件的扩展信息
+                $file['extension']  = $this->getExt($file['name']);
+                $file['savepath']   = $savePath;
+                $file['savename']   = $this->getSaveName($file);
+                // 自动检查附件
+                if($this->autoCheck) {
+                    if(!$this->check($file))
+                        return false;
+                }
+                //保存上传文件
+                if(!$this->save($file)) return false;
+                if(function_exists($this->hashType)) {
+                    $fun =  $this->hashType;
+                    $file['hash']   =  $fun(auto_charset($file['savepath'].$file['savename'],'utf-8','gbk'));
+                }
+                unset($file['tmp_name'],$file['error']);
+                $info[] = $file;
+            }
+            // 返回上传的文件信息
+            return $info;
+        }else {
+            $this->error  =  '没有选择上传文件';
+            return false;
+        }
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 转换上传文件数组变量为正确的方式
+     +----------------------------------------------------------
+     * @access private
+     +----------------------------------------------------------
+     * @param array $files  上传的文件变量
+     +----------------------------------------------------------
+     * @return array
+     +----------------------------------------------------------
+     */
+    private function dealFiles($files) {
+       $fileArray = array();
+       $n = 0;
+       foreach ($files as $file){
+           if(is_array($file['name'])) {
+               $keys = array_keys($file);
+               $count	 =	 count($file['name']);
+               for ($i=0; $i<$count; $i++) {
+                   foreach ($keys as $key)
+                       $fileArray[$n][$key] = $file[$key][$i];
+                   $n++;
+               }
+           }else{
+               $fileArray[$n] = $file;
+               $n++;
+           }
+       }
+       return $fileArray;
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 获取错误代码信息
+     +----------------------------------------------------------
+     * @access public
+     +----------------------------------------------------------
+     * @param string $errorNo  错误号码
+     +----------------------------------------------------------
+     * @return void
+     +----------------------------------------------------------
+     * @throws ThinkExecption
+     +----------------------------------------------------------
+     */
+    protected function error($errorNo)
+    {
+         switch($errorNo) {
+            case 1:
+                $this->error = '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值';
+                break;
+            case 2:
+                $this->error = '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值';
+                break;
+            case 3:
+                $this->error = '文件只有部分被上传';
+                break;
+            case 4:
+                $this->error = '没有文件被上传';
+                break;
+            case 6:
+                $this->error = '找不到临时文件夹';
+                break;
+            case 7:
+                $this->error = '文件写入失败';
+                break;
+            default:
+                $this->error = '未知上传错误!';
+        }
+        return ;
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 根据上传文件命名规则取得保存文件名
+     +----------------------------------------------------------
+     * @access private
+     +----------------------------------------------------------
+     * @param string $filename 数据
+     +----------------------------------------------------------
+     * @return string
+     +----------------------------------------------------------
+     */
+    private function getSaveName($filename)
+    {
+        $rule = $this->saveRule;
+        if(empty($rule)) {//没有定义命名规则,则保持文件名不变
+            $saveName = $filename['name'];
+        }else {
+            if(function_exists($rule)) {
+                //使用函数生成一个唯一文件标识号
+                $saveName = $rule().".".$filename['extension'];
+            }else {
+                //使用给定的文件名作为标识号
+                $saveName = $rule.".".$filename['extension'];
+            }
+        }
+        if($this->autoSub) {
+            // 使用子目录保存文件
+            $filename['savename'] = $saveName;
+            $saveName = $this->getSubName($filename).'/'.$saveName;
+        }
+        return $saveName;
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 获取子目录的名称
+     +----------------------------------------------------------
+     * @access private
+     +----------------------------------------------------------
+     * @param array $file  上传的文件信息
+     +----------------------------------------------------------
+     * @return string
+     +----------------------------------------------------------
+     */
+    private function getSubName($file)
+    {
+        switch($this->subType) {
+            case 'date':
+                $dir   =  date($this->dateFormat,time());
+                break;
+            case 'hash':
+            default:
+                $name = md5($file['savename']);
+                $dir   =  '';
+                for($i=0;$i<$this->hashLevel;$i++) {
+                    $dir   .=  $name{$i}.'/';
+                }
+                break;
+        }
+        if(!is_dir($file['savepath'].$dir)) {
+            mk_dir($file['savepath'].$dir);
+        }
+        return $dir;
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 检查上传的文件
+     +----------------------------------------------------------
+     * @access private
+     +----------------------------------------------------------
+     * @param array $file 文件信息
+     +----------------------------------------------------------
+     * @return boolean
+     +----------------------------------------------------------
+     */
+    private function check($file) {
+        if($file['error']!== 0) {
+            //文件上传失败
+            //捕获错误代码
+            $this->error($file['error']);
+            return false;
+        }
+        //文件上传成功,进行自定义规则检查
+        //检查文件大小
+        if(!$this->checkSize($file['size'])) {
+            $this->error = '上传文件大小不符!';
+            return false;
+        }
+
+        //检查文件Mime类型
+        if(!$this->checkType($file['type'])) {
+            $this->error = '上传文件MIME类型不允许!';
+            return false;
+        }
+        //检查文件类型
+        if(!$this->checkExt($file['extension'])) {
+            $this->error ='上传文件类型不允许';
+            return false;
+        }
+
+        //检查是否合法上传
+        if(!$this->checkUpload($file['tmp_name'])) {
+            $this->error = '非法上传文件!';
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 检查上传的文件类型是否合法
+     +----------------------------------------------------------
+     * @access private
+     +----------------------------------------------------------
+     * @param string $type 数据
+     +----------------------------------------------------------
+     * @return boolean
+     +----------------------------------------------------------
+     */
+    private function checkType($type)
+    {
+        if(!empty($this->allowTypes))
+            return in_array(strtolower($type),$this->allowTypes);
+        return true;
+    }
+
+
+    /**
+     +----------------------------------------------------------
+     * 检查上传的文件后缀是否合法
+     +----------------------------------------------------------
+     * @access private
+     +----------------------------------------------------------
+     * @param string $ext 后缀名
+     +----------------------------------------------------------
+     * @return boolean
+     +----------------------------------------------------------
+     */
+    private function checkExt($ext)
+    {
+        if(!empty($this->allowExts))
+            return in_array(strtolower($ext),$this->allowExts,true);
+        return true;
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 检查文件大小是否合法
+     +----------------------------------------------------------
+     * @access private
+     +----------------------------------------------------------
+     * @param integer $size 数据
+     +----------------------------------------------------------
+     * @return boolean
+     +----------------------------------------------------------
+     */
+    private function checkSize($size)
+    {
+        return !($size > $this->maxSize) || (-1 == $this->maxSize);
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 检查文件是否非法提交
+     +----------------------------------------------------------
+     * @access private
+     +----------------------------------------------------------
+     * @param string $filename 文件名
+     +----------------------------------------------------------
+     * @return boolean
+     +----------------------------------------------------------
+     */
+    private function checkUpload($filename)
+    {
+        return is_uploaded_file($filename);
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 取得上传文件的后缀
+     +----------------------------------------------------------
+     * @access private
+     +----------------------------------------------------------
+     * @param string $filename 文件名
+     +----------------------------------------------------------
+     * @return boolean
+     +----------------------------------------------------------
+     */
+    private function getExt($filename)
+    {
+        $pathinfo = pathinfo($filename);
+        return $pathinfo['extension'];
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 取得上传文件的信息
+     +----------------------------------------------------------
+     * @access public
+     +----------------------------------------------------------
+     * @return array
+     +----------------------------------------------------------
+     */
+    public function getUploadFileInfo()
+    {
+        return $this->uploadFileInfo;
+    }
+
+    /**
+     +----------------------------------------------------------
+     * 取得最后一次错误信息
+     +----------------------------------------------------------
+     * @access public
+     +----------------------------------------------------------
+     * @return string
+     +----------------------------------------------------------
+     */
+    public function getErrorMsg()
+    {
+        return $this->error;
+    }
+
+}//类定义结束
+?>

+ 412 - 0
Ainaphp/Lib/ORG/class.pop3.php

@@ -0,0 +1,412 @@
+<?php
+/*~ class.pop3.php
+.---------------------------------------------------------------------------.
+|  Software: PHPMailer - PHP email class                                    |
+|   Version: 5.2.2                                                          |
+|      Site: https://code.google.com/a/apache-extras.org/p/phpmailer/       |
+| ------------------------------------------------------------------------- |
+|     Admin: Jim Jagielski (project admininistrator)                        |
+|   Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
+|          : Marcus Bointon (coolbru) coolbru@users.sourceforge.net         |
+|          : Jim Jagielski (jimjag) jimjag@gmail.com                        |
+|   Founder: Brent R. Matzelle (original founder)                           |
+| Copyright (c) 2010-2012, Jim Jagielski. All Rights Reserved.              |
+| Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved.               |
+| Copyright (c) 2001-2003, Brent R. Matzelle                                |
+| ------------------------------------------------------------------------- |
+|   License: Distributed under the Lesser General Public License (LGPL)     |
+|            http://www.gnu.org/copyleft/lesser.html                        |
+| This program is distributed in the hope that it will be useful - WITHOUT  |
+| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or     |
+| FITNESS FOR A PARTICULAR PURPOSE.                                         |
+'---------------------------------------------------------------------------'
+*/
+
+/**
+ * PHPMailer - PHP POP Before SMTP Authentication Class
+ * NOTE: Designed for use with PHP version 5 and up
+ * @package PHPMailer
+ * @author Andy Prevost
+ * @author Marcus Bointon
+ * @author Jim Jagielski
+ * @copyright 2010 - 2012 Jim Jagielski
+ * @copyright 2004 - 2009 Andy Prevost
+ * @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
+ */
+
+/**
+ * POP Before SMTP Authentication Class
+ * Version 5.2.2
+ *
+ * Orig Author: Richard Davey (rich@corephp.co.uk)
+ * Modifications: Andy Prevost
+ * Modifications: Jim Jagielski
+ * License: LGPL, see PHPMailer License
+ *
+ * Specifically for PHPMailer to allow POP before SMTP authentication.
+ * Does not yet work with APOP - if you have an APOP account, contact Jim Jagielski
+ * and we can test changes to this script.
+ *
+ * This class is based on the structure of the SMTP class originally authored by Chris Ryan
+ *
+ * This class is rfc 1939 compliant and implements all the commands
+ * required for POP3 connection, authentication and disconnection.
+ *
+ * @package PHPMailer
+ * @author Richard Davey (orig)
+ * @author Andy Prevost
+ * @author Jim Jagielski
+ */
+
+class POP3 {
+  /**
+   * Default POP3 port
+   * @var int
+   */
+  public $POP3_PORT = 110;
+
+  /**
+   * Default Timeout
+   * @var int
+   */
+  public $POP3_TIMEOUT = 30;
+
+  /**
+   * POP3 Carriage Return + Line Feed
+   * @var string
+   */
+  public $CRLF = "\r\n";
+
+  /**
+   * Displaying Debug warnings? (0 = now, 1+ = yes)
+   * @var int
+   */
+  public $do_debug = 2;
+
+  /**
+   * POP3 Mail Server
+   * @var string
+   */
+  public $host;
+
+  /**
+   * POP3 Port
+   * @var int
+   */
+  public $port;
+
+  /**
+   * POP3 Timeout Value
+   * @var int
+   */
+  public $tval;
+
+  /**
+   * POP3 Username
+   * @var string
+   */
+  public $username;
+
+  /**
+   * POP3 Password
+   * @var string
+   */
+  public $password;
+
+  /**
+   * Sets the POP3 PHPMailer Version number
+   * @var string
+   */
+  public $Version         = '5.2.2-rc1';
+
+  /////////////////////////////////////////////////
+  // PROPERTIES, PRIVATE AND PROTECTED
+  /////////////////////////////////////////////////
+
+  private $pop_conn;
+  private $connected;
+  private $error;     //  Error log array
+
+  /**
+   * Constructor, sets the initial values
+   * @access public
+   * @return POP3
+   */
+  public function __construct() {
+    $this->pop_conn  = 0;
+    $this->connected = false;
+    $this->error     = null;
+  }
+
+  /**
+   * Combination of public events - connect, login, disconnect
+   * @access public
+   * @param string $host
+   * @param integer $port
+   * @param integer $tval
+   * @param string $username
+   * @param string $password
+   */
+  public function Authorise ($host, $port = false, $tval = false, $username, $password, $debug_level = 0) {
+    $this->host = $host;
+
+    //  If no port value is passed, retrieve it
+    if ($port == false) {
+      $this->port = $this->POP3_PORT;
+    } else {
+      $this->port = $port;
+    }
+
+    //  If no port value is passed, retrieve it
+    if ($tval == false) {
+      $this->tval = $this->POP3_TIMEOUT;
+    } else {
+      $this->tval = $tval;
+    }
+
+    $this->do_debug = $debug_level;
+    $this->username = $username;
+    $this->password = $password;
+
+    //  Refresh the error log
+    $this->error = null;
+
+    //  Connect
+    $result = $this->Connect($this->host, $this->port, $this->tval);
+
+    if ($result) {
+      $login_result = $this->Login($this->username, $this->password);
+
+      if ($login_result) {
+        $this->Disconnect();
+
+        return true;
+      }
+
+    }
+
+    //  We need to disconnect regardless if the login succeeded
+    $this->Disconnect();
+
+    return false;
+  }
+
+  /**
+   * Connect to the POP3 server
+   * @access public
+   * @param string $host
+   * @param integer $port
+   * @param integer $tval
+   * @return boolean
+   */
+  public function Connect ($host, $port = false, $tval = 30) {
+    //  Are we already connected?
+    if ($this->connected) {
+      return true;
+    }
+
+    /*
+    On Windows this will raise a PHP Warning error if the hostname doesn't exist.
+    Rather than supress it with @fsockopen, let's capture it cleanly instead
+    */
+
+    set_error_handler(array(&$this, 'catchWarning'));
+
+    //  Connect to the POP3 server
+    $this->pop_conn = fsockopen($host,    //  POP3 Host
+                  $port,    //  Port #
+                  $errno,   //  Error Number
+                  $errstr,  //  Error Message
+                  $tval);   //  Timeout (seconds)
+
+    //  Restore the error handler
+    restore_error_handler();
+
+    //  Does the Error Log now contain anything?
+    if ($this->error && $this->do_debug >= 1) {
+      $this->displayErrors();
+    }
+
+    //  Did we connect?
+    if ($this->pop_conn == false) {
+      //  It would appear not...
+      $this->error = array(
+        'error' => "Failed to connect to server $host on port $port",
+        'errno' => $errno,
+        'errstr' => $errstr
+      );
+
+      if ($this->do_debug >= 1) {
+        $this->displayErrors();
+      }
+
+      return false;
+    }
+
+    //  Increase the stream time-out
+
+    //  Check for PHP 4.3.0 or later
+    if (version_compare(phpversion(), '5.0.0', 'ge')) {
+      stream_set_timeout($this->pop_conn, $tval, 0);
+    } else {
+      //  Does not work on Windows
+      if (substr(PHP_OS, 0, 3) !== 'WIN') {
+        socket_set_timeout($this->pop_conn, $tval, 0);
+      }
+    }
+
+    //  Get the POP3 server response
+    $pop3_response = $this->getResponse();
+
+    //  Check for the +OK
+    if ($this->checkResponse($pop3_response)) {
+    //  The connection is established and the POP3 server is talking
+    $this->connected = true;
+      return true;
+    }
+
+  }
+
+  /**
+   * Login to the POP3 server (does not support APOP yet)
+   * @access public
+   * @param string $username
+   * @param string $password
+   * @return boolean
+   */
+  public function Login ($username = '', $password = '') {
+    if ($this->connected == false) {
+      $this->error = 'Not connected to POP3 server';
+
+      if ($this->do_debug >= 1) {
+        $this->displayErrors();
+      }
+    }
+
+    if (empty($username)) {
+      $username = $this->username;
+    }
+
+    if (empty($password)) {
+      $password = $this->password;
+    }
+
+    $pop_username = "USER $username" . $this->CRLF;
+    $pop_password = "PASS $password" . $this->CRLF;
+
+    //  Send the Username
+    $this->sendString($pop_username);
+    $pop3_response = $this->getResponse();
+
+    if ($this->checkResponse($pop3_response)) {
+      //  Send the Password
+      $this->sendString($pop_password);
+      $pop3_response = $this->getResponse();
+
+      if ($this->checkResponse($pop3_response)) {
+        return true;
+      } else {
+        return false;
+      }
+    } else {
+      return false;
+    }
+  }
+
+  /**
+   * Disconnect from the POP3 server
+   * @access public
+   */
+  public function Disconnect () {
+    $this->sendString('QUIT');
+
+    fclose($this->pop_conn);
+  }
+
+  /////////////////////////////////////////////////
+  //  Private Methods
+  /////////////////////////////////////////////////
+
+  /**
+   * Get the socket response back.
+   * $size is the maximum number of bytes to retrieve
+   * @access private
+   * @param integer $size
+   * @return string
+   */
+  private function getResponse ($size = 128) {
+    $pop3_response = fgets($this->pop_conn, $size);
+
+    return $pop3_response;
+  }
+
+  /**
+   * Send a string down the open socket connection to the POP3 server
+   * @access private
+   * @param string $string
+   * @return integer
+   */
+  private function sendString ($string) {
+    $bytes_sent = fwrite($this->pop_conn, $string, strlen($string));
+
+    return $bytes_sent;
+  }
+
+  /**
+   * Checks the POP3 server response for +OK or -ERR
+   * @access private
+   * @param string $string
+   * @return boolean
+   */
+  private function checkResponse ($string) {
+    if (substr($string, 0, 3) !== '+OK') {
+      $this->error = array(
+        'error' => "Server reported an error: $string",
+        'errno' => 0,
+        'errstr' => ''
+      );
+
+      if ($this->do_debug >= 1) {
+        $this->displayErrors();
+      }
+
+      return false;
+    } else {
+      return true;
+    }
+
+  }
+
+  /**
+   * If debug is enabled, display the error message array
+   * @access private
+   */
+  private function displayErrors () {
+    echo '<pre>';
+
+    foreach ($this->error as $single_error) {
+      print_r($single_error);
+    }
+
+    echo '</pre>';
+  }
+
+  /**
+   * Takes over from PHP for the socket warning handler
+   * @access private
+   * @param integer $errno
+   * @param string $errstr
+   * @param string $errfile
+   * @param integer $errline
+   */
+  private function catchWarning ($errno, $errstr, $errfile, $errline) {
+    $this->error[] = array(
+      'error' => "Connecting to the POP3 server raised a PHP warning: ",
+      'errno' => $errno,
+      'errstr' => $errstr
+    );
+  }
+
+  //  End of class
+}
+?>

+ 957 - 0
Ainaphp/Lib/ORG/class.smtp.php

@@ -0,0 +1,957 @@
+<?php
+//邮件发送
+/**
+ * PHPMailer - PHP SMTP email transport class
+ * NOTE: Designed for use with PHP version 5 and up
+ * @package PHPMailer
+ * @author Andy Prevost
+ * @author Marcus Bointon
+ * @copyright 2004 - 2008 Andy Prevost
+ * @author Jim Jagielski
+ * @copyright 2010 - 2012 Jim Jagielski
+ * @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
+ */
+
+/**
+ * SMTP is rfc 821 compliant and implements all the rfc 821 SMTP
+ * commands except TURN which will always return a not implemented
+ * error. SMTP also provides some utility methods for sending mail
+ * to an SMTP server.
+ * original author: Chris Ryan
+ */
+
+class SMTP {
+  /**
+   *  SMTP server port
+   *  @var int
+   */
+  public $SMTP_PORT = 25;
+
+  /**
+   *  SMTP reply line ending (don't change)
+   *  @var string
+   */
+  public $CRLF = "\r\n";
+
+  /**
+   *  Sets whether debugging is turned on
+   *  @var bool
+   */
+  public $do_debug;       // the level of debug to perform
+
+  /**
+   * Sets the function/method to use for debugging output.
+   * Right now we only honor "echo" or "error_log"
+   * @var string
+   */
+  public $Debugoutput     = "echo";
+
+  /**
+   *  Sets VERP use on/off (default is off)
+   *  @var bool
+   */
+  public $do_verp = false;
+
+  /**
+   * Sets the SMTP timeout value for reads, in seconds
+   * @var int
+   */
+  public $Timeout         = 15;
+
+  /**
+   * Sets the SMTP timelimit value for reads, in seconds
+   * @var int
+   */
+  public $Timelimit       = 30;
+
+  /**
+   * Sets the SMTP PHPMailer Version number
+   * @var string
+   */
+  public $Version         = '5.2.2-rc1';
+
+  /////////////////////////////////////////////////
+  // PROPERTIES, PRIVATE AND PROTECTED
+  /////////////////////////////////////////////////
+
+  private $smtp_conn; // the socket to the server
+  private $error;     // error if any on the last call
+  private $helo_rply; // the reply the server sent to us for HELO
+
+  /**
+   * Outputs debugging info via user-defined method
+   * @param string $str
+   */
+  private function edebug($str) {
+    if ($this->Debugoutput == "error_log") {
+        error_log($str);
+    } else {
+        echo $str;
+    }
+  }
+
+  /**
+   * Initialize the class so that the data is in a known state.
+   * @access public
+   * @return void
+   */
+  public function __construct() {
+    $this->smtp_conn = 0;
+    $this->error = null;
+    $this->helo_rply = null;
+
+    $this->do_debug = 0;
+  }
+
+  /////////////////////////////////////////////////
+  // CONNECTION FUNCTIONS
+  /////////////////////////////////////////////////
+
+  /**
+   * Connect to the server specified on the port specified.
+   * If the port is not specified use the default SMTP_PORT.
+   * If tval is specified then a connection will try and be
+   * established with the server for that number of seconds.
+   * If tval is not specified the default is 30 seconds to
+   * try on the connection.
+   *
+   * SMTP CODE SUCCESS: 220
+   * SMTP CODE FAILURE: 421
+   * @access public
+   * @return bool
+   */
+  public function Connect($host, $port = 0, $tval = 30) {
+    // set the error val to null so there is no confusion
+    $this->error = null;
+
+    // make sure we are __not__ connected
+    if($this->connected()) {
+      // already connected, generate error
+      $this->error = array("error" => "Already connected to a server");
+      return false;
+    }
+
+    if(empty($port)) {
+      $port = $this->SMTP_PORT;
+    }
+
+    // connect to the smtp server
+    $this->smtp_conn = @fsockopen($host,    // the host of the server
+                                 $port,    // the port to use
+                                 $errno,   // error number if any
+                                 $errstr,  // error message if any
+                                 $tval);   // give up after ? secs
+    // verify we connected properly
+    if(empty($this->smtp_conn)) {
+      $this->error = array("error" => "Failed to connect to server",
+                           "errno" => $errno,
+                           "errstr" => $errstr);
+      if($this->do_debug >= 1) {
+        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": $errstr ($errno)" . $this->CRLF . '<br />');
+      }
+      return false;
+    }
+
+    // SMTP server can take longer to respond, give longer timeout for first read
+    // Windows does not have support for this timeout function
+    if(substr(PHP_OS, 0, 3) != "WIN") {
+     $max = ini_get('max_execution_time');
+     if ($max != 0 && $tval > $max) { // don't bother if unlimited
+      @set_time_limit($tval);
+     }
+     stream_set_timeout($this->smtp_conn, $tval, 0);
+    }
+
+    // get any announcement
+    $announce = $this->get_lines();
+
+    if($this->do_debug >= 2) {
+      $this->edebug("SMTP -> FROM SERVER:" . $announce . $this->CRLF . '<br />');
+    }
+
+    return true;
+  }
+
+  /**
+   * Initiate a TLS communication with the server.
+   *
+   * SMTP CODE 220 Ready to start TLS
+   * SMTP CODE 501 Syntax error (no parameters allowed)
+   * SMTP CODE 454 TLS not available due to temporary reason
+   * @access public
+   * @return bool success
+   */
+  public function StartTLS() {
+    $this->error = null; # to avoid confusion
+
+    if(!$this->connected()) {
+      $this->error = array("error" => "Called StartTLS() without being connected");
+      return false;
+    }
+
+    fputs($this->smtp_conn,"STARTTLS" . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      $this->edebug("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />');
+    }
+
+    if($code != 220) {
+      $this->error =
+         array("error"     => "STARTTLS not accepted from server",
+               "smtp_code" => $code,
+               "smtp_msg"  => substr($rply,4));
+      if($this->do_debug >= 1) {
+        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
+      }
+      return false;
+    }
+
+    // Begin encrypted connection
+    if(!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
+      return false;
+    }
+
+    return true;
+  }
+
+  /**
+   * Performs SMTP authentication.  Must be run after running the
+   * Hello() method.  Returns true if successfully authenticated.
+   * @access public
+   * @return bool
+   */
+  public function Authenticate($username, $password, $authtype='LOGIN', $realm='',
+                               $workstation='') {
+    if (empty($authtype)) {
+      $authtype = 'LOGIN';
+    }
+
+    switch ($authtype) {
+      case 'PLAIN':
+        // Start authentication
+        fputs($this->smtp_conn,"AUTH PLAIN" . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($code != 334) {
+          $this->error =
+            array("error" => "AUTH not accepted from server",
+                  "smtp_code" => $code,
+                  "smtp_msg" => substr($rply,4));
+          if($this->do_debug >= 1) {
+            $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
+          }
+          return false;
+        }
+        // Send encoded username and password
+        fputs($this->smtp_conn, base64_encode("\0".$username."\0".$password) . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($code != 235) {
+          $this->error =
+            array("error" => "Authentication not accepted from server",
+                  "smtp_code" => $code,
+                  "smtp_msg" => substr($rply,4));
+          if($this->do_debug >= 1) {
+            $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
+          }
+          return false;
+        }
+        break;
+      case 'LOGIN':
+        // Start authentication
+        fputs($this->smtp_conn,"AUTH LOGIN" . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($code != 334) {
+          $this->error =
+            array("error" => "AUTH not accepted from server",
+                  "smtp_code" => $code,
+                  "smtp_msg" => substr($rply,4));
+          if($this->do_debug >= 1) {
+            $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
+          }
+          return false;
+        }
+
+        // Send encoded username
+        fputs($this->smtp_conn, base64_encode($username) . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($code != 334) {
+          $this->error =
+            array("error" => "Username not accepted from server",
+                  "smtp_code" => $code,
+                  "smtp_msg" => substr($rply,4));
+          if($this->do_debug >= 1) {
+            $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
+          }
+          return false;
+        }
+
+        // Send encoded password
+        fputs($this->smtp_conn, base64_encode($password) . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($code != 235) {
+          $this->error =
+            array("error" => "Password not accepted from server",
+                  "smtp_code" => $code,
+                  "smtp_msg" => substr($rply,4));
+          if($this->do_debug >= 1) {
+            $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
+          }
+          return false;
+        }
+        break;
+      case 'NTLM':
+        /*
+         * ntlm_sasl_client.php
+         ** Bundled with Permission
+         **
+         ** How to telnet in windows: http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx
+         ** PROTOCOL Documentation http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication
+         */
+        require_once('ntlm_sasl_client.php');
+        $temp = new stdClass();
+        $ntlm_client = new ntlm_sasl_client_class;
+        if(! $ntlm_client->Initialize($temp)){//let's test if every function its available
+            $this->error = array("error" => $temp->error);
+            if($this->do_debug >= 1) {
+                $this->edebug("You need to enable some modules in your php.ini file: " . $this->error["error"] . $this->CRLF);
+            }
+            return false;
+        }
+        $msg1 = $ntlm_client->TypeMsg1($realm, $workstation);//msg1
+
+        fputs($this->smtp_conn,"AUTH NTLM " . base64_encode($msg1) . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+
+        if($code != 334) {
+            $this->error =
+                array("error" => "AUTH not accepted from server",
+                      "smtp_code" => $code,
+                      "smtp_msg" => substr($rply,4));
+            if($this->do_debug >= 1) {
+                $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF);
+            }
+            return false;
+        }
+
+        $challange = substr($rply,3);//though 0 based, there is a white space after the 3 digit number....//msg2
+        $challange = base64_decode($challange);
+        $ntlm_res = $ntlm_client->NTLMResponse(substr($challange,24,8),$password);
+        $msg3 = $ntlm_client->TypeMsg3($ntlm_res,$username,$realm,$workstation);//msg3
+        // Send encoded username
+        fputs($this->smtp_conn, base64_encode($msg3) . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($code != 235) {
+            $this->error =
+                array("error" => "Could not authenticate",
+                      "smtp_code" => $code,
+                      "smtp_msg" => substr($rply,4));
+            if($this->do_debug >= 1) {
+                $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF);
+            }
+            return false;
+        }
+        break;
+    }
+    return true;
+  }
+
+  /**
+   * Returns true if connected to a server otherwise false
+   * @access public
+   * @return bool
+   */
+  public function Connected() {
+    if(!empty($this->smtp_conn)) {
+      $sock_status = socket_get_status($this->smtp_conn);
+      if($sock_status["eof"]) {
+        // the socket is valid but we are not connected
+        if($this->do_debug >= 1) {
+            $this->edebug("SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected");
+        }
+        $this->Close();
+        return false;
+      }
+      return true; // everything looks good
+    }
+    return false;
+  }
+
+  /**
+   * Closes the socket and cleans up the state of the class.
+   * It is not considered good to use this function without
+   * first trying to use QUIT.
+   * @access public
+   * @return void
+   */
+  public function Close() {
+    $this->error = null; // so there is no confusion
+    $this->helo_rply = null;
+    if(!empty($this->smtp_conn)) {
+      // close the connection and cleanup
+      fclose($this->smtp_conn);
+      $this->smtp_conn = 0;
+    }
+  }
+
+  /////////////////////////////////////////////////
+  // SMTP COMMANDS
+  /////////////////////////////////////////////////
+
+  /**
+   * Issues a data command and sends the msg_data to the server
+   * finializing the mail transaction. $msg_data is the message
+   * that is to be send with the headers. Each header needs to be
+   * on a single line followed by a <CRLF> with the message headers
+   * and the message body being seperated by and additional <CRLF>.
+   *
+   * Implements rfc 821: DATA <CRLF>
+   *
+   * SMTP CODE INTERMEDIATE: 354
+   *     [data]
+   *     <CRLF>.<CRLF>
+   *     SMTP CODE SUCCESS: 250
+   *     SMTP CODE FAILURE: 552,554,451,452
+   * SMTP CODE FAILURE: 451,554
+   * SMTP CODE ERROR  : 500,501,503,421
+   * @access public
+   * @return bool
+   */
+  public function Data($msg_data) {
+    $this->error = null; // so no confusion is caused
+
+    if(!$this->connected()) {
+      $this->error = array(
+              "error" => "Called Data() without being connected");
+      return false;
+    }
+
+    fputs($this->smtp_conn,"DATA" . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      $this->edebug("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />');
+    }
+
+    if($code != 354) {
+      $this->error =
+        array("error" => "DATA command not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
+      }
+      return false;
+    }
+
+    /* the server is ready to accept data!
+     * according to rfc 821 we should not send more than 1000
+     * including the CRLF
+     * characters on a single line so we will break the data up
+     * into lines by \r and/or \n then if needed we will break
+     * each of those into smaller lines to fit within the limit.
+     * in addition we will be looking for lines that start with
+     * a period '.' and append and additional period '.' to that
+     * line. NOTE: this does not count towards limit.
+     */
+
+    // normalize the line breaks so we know the explode works
+    $msg_data = str_replace("\r\n","\n",$msg_data);
+    $msg_data = str_replace("\r","\n",$msg_data);
+    $lines = explode("\n",$msg_data);
+
+    /* we need to find a good way to determine is headers are
+     * in the msg_data or if it is a straight msg body
+     * currently I am assuming rfc 822 definitions of msg headers
+     * and if the first field of the first line (':' sperated)
+     * does not contain a space then it _should_ be a header
+     * and we can process all lines before a blank "" line as
+     * headers.
+     */
+
+    $field = substr($lines[0],0,strpos($lines[0],":"));
+    $in_headers = false;
+    if(!empty($field) && !strstr($field," ")) {
+      $in_headers = true;
+    }
+
+    $max_line_length = 998; // used below; set here for ease in change
+
+    while(list(,$line) = @each($lines)) {
+      $lines_out = null;
+      if($line == "" && $in_headers) {
+        $in_headers = false;
+      }
+      // ok we need to break this line up into several smaller lines
+      while(strlen($line) > $max_line_length) {
+        $pos = strrpos(substr($line,0,$max_line_length)," ");
+
+        // Patch to fix DOS attack
+        if(!$pos) {
+          $pos = $max_line_length - 1;
+          $lines_out[] = substr($line,0,$pos);
+          $line = substr($line,$pos);
+        } else {
+          $lines_out[] = substr($line,0,$pos);
+          $line = substr($line,$pos + 1);
+        }
+
+        /* if processing headers add a LWSP-char to the front of new line
+         * rfc 822 on long msg headers
+         */
+        if($in_headers) {
+          $line = "\t" . $line;
+        }
+      }
+      $lines_out[] = $line;
+
+      // send the lines to the server
+      while(list(,$line_out) = @each($lines_out)) {
+        if(strlen($line_out) > 0)
+        {
+          if(substr($line_out, 0, 1) == ".") {
+            $line_out = "." . $line_out;
+          }
+        }
+        fputs($this->smtp_conn,$line_out . $this->CRLF);
+      }
+    }
+
+    // message data has been sent
+    fputs($this->smtp_conn, $this->CRLF . "." . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      $this->edebug("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />');
+    }
+
+    if($code != 250) {
+      $this->error =
+        array("error" => "DATA not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
+      }
+      return false;
+    }
+    return true;
+  }
+
+  /**
+   * Sends the HELO command to the smtp server.
+   * This makes sure that we and the server are in
+   * the same known state.
+   *
+   * Implements from rfc 821: HELO <SP> <domain> <CRLF>
+   *
+   * SMTP CODE SUCCESS: 250
+   * SMTP CODE ERROR  : 500, 501, 504, 421
+   * @access public
+   * @return bool
+   */
+  public function Hello($host = '') {
+    $this->error = null; // so no confusion is caused
+
+    if(!$this->connected()) {
+      $this->error = array(
+            "error" => "Called Hello() without being connected");
+      return false;
+    }
+
+    // if hostname for HELO was not specified send default
+    if(empty($host)) {
+      // determine appropriate default to send to server
+      $host = "localhost";
+    }
+
+    // Send extended hello first (RFC 2821)
+    if(!$this->SendHello("EHLO", $host)) {
+      if(!$this->SendHello("HELO", $host)) {
+        return false;
+      }
+    }
+
+    return true;
+  }
+
+  /**
+   * Sends a HELO/EHLO command.
+   * @access private
+   * @return bool
+   */
+  private function SendHello($hello, $host) {
+    fputs($this->smtp_conn, $hello . " " . $host . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      $this->edebug("SMTP -> FROM SERVER: " . $rply . $this->CRLF . '<br />');
+    }
+
+    if($code != 250) {
+      $this->error =
+        array("error" => $hello . " not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
+      }
+      return false;
+    }
+
+    $this->helo_rply = $rply;
+
+    return true;
+  }
+
+  /**
+   * Starts a mail transaction from the email address specified in
+   * $from. Returns true if successful or false otherwise. If True
+   * the mail transaction is started and then one or more Recipient
+   * commands may be called followed by a Data command.
+   *
+   * Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
+   *
+   * SMTP CODE SUCCESS: 250
+   * SMTP CODE SUCCESS: 552,451,452
+   * SMTP CODE SUCCESS: 500,501,421
+   * @access public
+   * @return bool
+   */
+  public function Mail($from) {
+    $this->error = null; // so no confusion is caused
+
+    if(!$this->connected()) {
+      $this->error = array(
+              "error" => "Called Mail() without being connected");
+      return false;
+    }
+
+    $useVerp = ($this->do_verp ? " XVERP" : "");
+    fputs($this->smtp_conn,"MAIL FROM:<" . $from . ">" . $useVerp . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      $this->edebug("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />');
+    }
+
+    if($code != 250) {
+      $this->error =
+        array("error" => "MAIL not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
+      }
+      return false;
+    }
+    return true;
+  }
+
+  /**
+   * Sends the quit command to the server and then closes the socket
+   * if there is no error or the $close_on_error argument is true.
+   *
+   * Implements from rfc 821: QUIT <CRLF>
+   *
+   * SMTP CODE SUCCESS: 221
+   * SMTP CODE ERROR  : 500
+   * @access public
+   * @return bool
+   */
+  public function Quit($close_on_error = true) {
+    $this->error = null; // so there is no confusion
+
+    if(!$this->connected()) {
+      $this->error = array(
+              "error" => "Called Quit() without being connected");
+      return false;
+    }
+
+    // send the quit command to the server
+    fputs($this->smtp_conn,"quit" . $this->CRLF);
+
+    // get any good-bye messages
+    $byemsg = $this->get_lines();
+
+    if($this->do_debug >= 2) {
+      $this->edebug("SMTP -> FROM SERVER:" . $byemsg . $this->CRLF . '<br />');
+    }
+
+    $rval = true;
+    $e = null;
+
+    $code = substr($byemsg,0,3);
+    if($code != 221) {
+      // use e as a tmp var cause Close will overwrite $this->error
+      $e = array("error" => "SMTP server rejected quit command",
+                 "smtp_code" => $code,
+                 "smtp_rply" => substr($byemsg,4));
+      $rval = false;
+      if($this->do_debug >= 1) {
+        $this->edebug("SMTP -> ERROR: " . $e["error"] . ": " . $byemsg . $this->CRLF . '<br />');
+      }
+    }
+
+    if(empty($e) || $close_on_error) {
+      $this->Close();
+    }
+
+    return $rval;
+  }
+
+  /**
+   * Sends the command RCPT to the SMTP server with the TO: argument of $to.
+   * Returns true if the recipient was accepted false if it was rejected.
+   *
+   * Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
+   *
+   * SMTP CODE SUCCESS: 250,251
+   * SMTP CODE FAILURE: 550,551,552,553,450,451,452
+   * SMTP CODE ERROR  : 500,501,503,421
+   * @access public
+   * @return bool
+   */
+  public function Recipient($to) {
+    $this->error = null; // so no confusion is caused
+
+    if(!$this->connected()) {
+      $this->error = array(
+              "error" => "Called Recipient() without being connected");
+      return false;
+    }
+
+    fputs($this->smtp_conn,"RCPT TO:<" . $to . ">" . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      $this->edebug("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />');
+    }
+
+    if($code != 250 && $code != 251) {
+      $this->error =
+        array("error" => "RCPT not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
+      }
+      return false;
+    }
+    return true;
+  }
+
+  /**
+   * Sends the RSET command to abort and transaction that is
+   * currently in progress. Returns true if successful false
+   * otherwise.
+   *
+   * Implements rfc 821: RSET <CRLF>
+   *
+   * SMTP CODE SUCCESS: 250
+   * SMTP CODE ERROR  : 500,501,504,421
+   * @access public
+   * @return bool
+   */
+  public function Reset() {
+    $this->error = null; // so no confusion is caused
+
+    if(!$this->connected()) {
+      $this->error = array(
+              "error" => "Called Reset() without being connected");
+      return false;
+    }
+
+    fputs($this->smtp_conn,"RSET" . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      $this->edebug("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />');
+    }
+
+    if($code != 250) {
+      $this->error =
+        array("error" => "RSET failed",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
+      }
+      return false;
+    }
+
+    return true;
+  }
+
+  /**
+   * Starts a mail transaction from the email address specified in
+   * $from. Returns true if successful or false otherwise. If True
+   * the mail transaction is started and then one or more Recipient
+   * commands may be called followed by a Data command. This command
+   * will send the message to the users terminal if they are logged
+   * in and send them an email.
+   *
+   * Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
+   *
+   * SMTP CODE SUCCESS: 250
+   * SMTP CODE SUCCESS: 552,451,452
+   * SMTP CODE SUCCESS: 500,501,502,421
+   * @access public
+   * @return bool
+   */
+  public function SendAndMail($from) {
+    $this->error = null; // so no confusion is caused
+
+    if(!$this->connected()) {
+      $this->error = array(
+          "error" => "Called SendAndMail() without being connected");
+      return false;
+    }
+
+    fputs($this->smtp_conn,"SAML FROM:" . $from . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      $this->edebug("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />');
+    }
+
+    if($code != 250) {
+      $this->error =
+        array("error" => "SAML not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
+      }
+      return false;
+    }
+    return true;
+  }
+
+  /**
+   * This is an optional command for SMTP that this class does not
+   * support. This method is here to make the RFC821 Definition
+   * complete for this class and __may__ be implimented in the future
+   *
+   * Implements from rfc 821: TURN <CRLF>
+   *
+   * SMTP CODE SUCCESS: 250
+   * SMTP CODE FAILURE: 502
+   * SMTP CODE ERROR  : 500, 503
+   * @access public
+   * @return bool
+   */
+  public function Turn() {
+    $this->error = array("error" => "This method, TURN, of the SMTP ".
+                                    "is not implemented");
+    if($this->do_debug >= 1) {
+      $this->edebug("SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF . '<br />');
+    }
+    return false;
+  }
+
+  /**
+  * Get the current error
+  * @access public
+  * @return array
+  */
+  public function getError() {
+    return $this->error;
+  }
+
+  /////////////////////////////////////////////////
+  // INTERNAL FUNCTIONS
+  /////////////////////////////////////////////////
+
+  /**
+   * Read in as many lines as possible
+   * either before eof or socket timeout occurs on the operation.
+   * With SMTP we can tell if we have more lines to read if the
+   * 4th character is '-' symbol. If it is a space then we don't
+   * need to read anything else.
+   * @access private
+   * @return string
+   */
+  private function get_lines() {
+    $data = "";
+    $endtime = 0;
+    /* If for some reason the fp is bad, don't inf loop */
+    if (!is_resource($this->smtp_conn)) {
+      return $data;
+    }
+    stream_set_timeout($this->smtp_conn, $this->Timeout);
+    if ($this->Timelimit > 0) {
+      $endtime = time() + $this->Timelimit;
+    }
+    while(is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
+      $str = @fgets($this->smtp_conn,515);
+      if($this->do_debug >= 4) {
+        $this->edebug("SMTP -> get_lines(): \$data was \"$data\"" . $this->CRLF . '<br />');
+        $this->edebug("SMTP -> get_lines(): \$str is \"$str\"" . $this->CRLF . '<br />');
+      }
+      $data .= $str;
+      if($this->do_debug >= 4) {
+        $this->edebug("SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF . '<br />');
+      }
+      // if 4th character is a space, we are done reading, break the loop
+      if(substr($str,3,1) == " ") { break; }
+      // Timed-out? Log and break
+      $info = stream_get_meta_data($this->smtp_conn);
+      if ($info['timed_out']) {
+        if($this->do_debug >= 4) {
+          $this->edebug("SMTP -> get_lines(): timed-out (" . $this->Timeout . " seconds) <br />");
+        }
+        break;
+      }
+      // Now check if reads took too long
+      if ($endtime) {
+        if (time() > $endtime) {
+          if($this->do_debug >= 4) {
+            $this->edebug("SMTP -> get_lines(): timelimit reached (" . $this->Timelimit . " seconds) <br />");
+          }
+          break;
+        }
+      }
+    }
+    return $data;
+  }
+
+}
+
+?>

+ 154 - 0
Ainaphp/Lib/Pay/Alipay.class.php

@@ -0,0 +1,154 @@
+<?php
+/**
+ *
+ * Alipay.php (支付宝支付模块)
+ *
+ */
+if(!defined("Yourphp")) exit("Access Denied");
+class Alipay extends Think {
+	public $config = array()  ;
+
+    public function __construct($config=array()) {
+         $this->config = $config;
+
+		if ($this->config['alipay_pay_type']==1) $this->config['service'] = 'create_partner_trade_by_buyer'; //担保
+		elseif($this->config['alipay_pay_type']==3) $this->config['service'] = 'create_direct_pay_by_user'; //即时
+        else $this->config['service'] = 'trade_create_by_buyer';	//标准
+
+		$this->config['gateway_url'] = 'https://www.alipay.com/cooperate/gateway.do?';
+		$this->config['gateway_method'] = 'POST';
+		$this->config['notify_url'] =  return_url('alipay',1);
+		$this->config['return_url'] =  return_url('alipay');
+    }
+	public function setup(){
+
+		$modules['pay_name']    = L('Alipay_pay_name');
+		$modules['pay_code']    = 'Alipay';
+		$modules['pay_desc']    = L('Alipay_pay_desc');
+		$modules['is_cod']  = '0';
+		$modules['is_online']  = '1';
+		$modules['author']  = 'Ainaphp';
+		$modules['website'] = 'http://www.alipay.com';
+		$modules['version'] = '1.0.0';
+		$modules['config']  = array(
+			array('name' => 'alipay_account',           'type' => 'text',   'value' => ''),
+			array('name' => 'alipay_key',               'type' => 'text',   'value' => ''),
+			array('name' => 'alipay_partner',           'type' => 'text',   'value' => ''),
+			array('name' => 'alipay_pay_type',        'type' => 'select', 'value' => '' ,'option' =>
+			array('1'=>L('alipay_pay_type_option1'),'2'=>L('alipay_pay_type_option2'),'3'=>L('alipay_pay_type_option3')))
+		);
+
+		return $modules;
+	}
+
+	public function get_code(){
+
+
+		$parameter = array(
+            'service'           => $this->config['service'],
+            'partner'           =>  trim($this->config['alipay_partner']),
+            '_input_charset'    =>  'utf-8',
+            'notify_url'        =>  trim($this->config['notify_url']),
+            'return_url'        =>  trim($this->config['return_url']),
+            /* 商品信息 */
+            'subject'           => $this->config['order_sn'],
+            'out_trade_no'      => $this->config['order_sn'],
+            'price'             => $this->config['order_amount'],
+			'body'				=> $this->config['body'],
+            'quantity'          => 1,
+            'payment_type'      => 1,
+            /* 物流参数 */
+            'logistics_type'    => 'EXPRESS',
+            'logistics_fee'     => 0,
+            'logistics_payment' => 'BUYER_PAY_AFTER_RECEIVE',
+			//'agent'             => $this->config['agent'],
+
+            /* 买卖双方信息 */
+            'seller_email'      =>  trim($this->config['alipay_account'])
+        );
+        ksort($parameter);
+        reset($parameter);
+        $param = '';
+        $sign  = '';
+
+        foreach ($parameter AS $key => $val)
+        {
+            $param .= "$key=" .urlencode($val). "&";
+            $sign  .= "$key=$val&";
+        }
+
+        $param = substr($param, 0, -1);
+        $sign  = substr($sign, 0, -1). $this->config['alipay_key'];
+        //$sign  = substr($sign, 0, -1). ALIPAY_AUTH;
+
+        $button = '<span><input type="button"  class="button" onclick="window.open(\''.$this->config['gateway_url'].$param. '&sign='.MD5($sign).'&sign_type=MD5\')" value="'.L('PAY_NOW').'" /></span>';
+
+
+		return $button;
+	}
+
+	public function respond()
+    {
+		if (!empty($_POST))
+        {
+            foreach($_POST as $key => $data)
+            {
+                $_GET[$key] = $data;
+            }
+        }
+
+        $seller_email = rawurldecode($_GET['seller_email']);
+        //$order_sn = str_replace($_GET['subject'], '', $_GET['out_trade_no']);
+        $order_sn = trim($_GET['out_trade_no']);
+
+
+
+
+        /* 检查数字签名是否正确 */
+        ksort($_GET);
+        reset($_GET);
+
+        $sign = '';
+        foreach ($_GET AS $key=>$val)
+        {
+            if ($key != 'sign' && $key != 'sign_type' && $key != 'code' && $key != 'g' && $key != 'm' && $key != 'a')
+            {
+                $sign .= "$key=$val&";
+            }
+        }
+
+        $sign = substr($sign, 0, -1) . $this->config['alipay_key'];
+        //$sign = substr($sign, 0, -1) . ALIPAY_AUTH;
+        if (md5($sign) != $_GET['sign'])
+        {
+            return false;
+        }
+
+        if ($_GET['trade_status'] == 'WAIT_SELLER_SEND_GOODS' || $_GET['trade_status'] =='WAIT_BUYER_CONFIRM_GOODS' ||  $_GET['trade_status'] =='WAIT_BUYER_PAY')
+        {
+            /* 改变订单状态 进行中*/
+			order_pay_status($order_sn,'1');
+            return true;
+        }
+        elseif ($_GET['trade_status'] == 'TRADE_FINISHED')
+        {
+            /* 改变订单状态 */
+			order_pay_status($order_sn,'2');
+            return true;
+        }
+        elseif ($_GET['trade_status'] == 'TRADE_SUCCESS')
+        {
+            /* 改变订单状态 即时交易成功*/
+			order_pay_status($order_sn,'2');
+            return true;
+        }
+        else
+        {
+            return false;
+        }
+	}
+
+
+
+}
+?>

+ 34 - 0
Ainaphp/Lib/Pay/Balance.class.php

@@ -0,0 +1,34 @@
+<?php
+/**
+ *
+ * Balance.php (余额支付模块)
+ *
+ */
+class Balance extends Think {
+	public $config = array()  ;
+    public function __construct($config=array()) {
+         $this->config = $config;
+    }
+	public function setup(){
+
+		$modules['pay_name']    = L('Balance_pay_name');
+		$modules['pay_code']    = 'Balance';
+		$modules['pay_desc']    = L('Balance_pay_desc');
+		$modules['is_cod']  = '0';
+		$modules['is_online']  = '1';
+		$modules['author']  = 'Ainaphp';
+		$modules['website'] = 'http://www.bangju.com';
+		$modules['version'] = '1.0.0';
+		$modules['config']  = array();
+		return $modules;
+	}
+
+	public function get_code(){
+		return;
+	}
+	public function respond()
+    {
+		return;
+	}
+}
+?>

+ 35 - 0
Ainaphp/Lib/Pay/Bank.class.php

@@ -0,0 +1,35 @@
+<?php
+/**
+ *
+ * Bank.php (银行汇款支付模块)
+ *
+ */
+class Bank extends Think {
+	public $config = array()  ;
+    public function __construct($config=array()) {
+         $this->config = $config;
+    }
+	public function setup(){
+
+		$modules['pay_name']    = L('Bank_pay_name');
+		$modules['pay_code']    = 'Bank';
+		$modules['pay_desc']    = L('Bank_pay_desc');
+		$modules['is_cod']  = '0';
+		$modules['is_online']  = '1';
+		$modules['author']  = 'Ainaphp';
+		$modules['website'] = '';
+		$modules['version'] = '1.0.0';
+		$modules['config']  = array();
+
+		return $modules;
+	}
+
+	public function get_code(){
+		return;
+	}
+	public function respond()
+    {
+		return;
+	}
+}
+?>

+ 101 - 0
Ainaphp/Lib/Pay/Chinabank.class.php

@@ -0,0 +1,101 @@
+<?php
+/**
+ *
+ * Alipay.php (模型表单生成)
+ *
+ */
+class Chinabank extends Think {
+	public $config = array()  ;
+
+    public function __construct($config=array()) {
+         $this->config = $config;
+
+		$this->config['gateway_url'] = 'https://www.alipay.com/cooperate/gateway.do?';
+		$this->config['gateway_method'] = 'POST';
+		$this->config['notify_url'] = return_url('chinabank',1);
+		$this->config['return_url'] = return_url('chinabank');
+
+    }
+	public function setup(){
+
+		$modules['pay_name']    =  L('Chinabank_pay_name');
+		$modules['pay_code']    = 'Chinabank';
+		$modules['pay_desc']    =  L('Chinabank_pay_desc');
+		$modules['is_cod']  = '0';
+		$modules['is_online']  = '1';
+		$modules['author']  = 'Ainaphp';
+		$modules['website'] = 'http://www.chinabank.com.cn';
+		$modules['version'] = '1.0.0';
+		$modules['config']  = array(
+			 array('name' => 'chinabank_account', 'type' => 'text', 'value' => ''),
+			 array('name' => 'chinabank_key',     'type' => 'text', 'value' => ''),
+		);
+		return $modules;
+	}
+
+	public function get_code($info,$value){
+
+
+		$data_vid           = trim($this->config['chinabank_account']);
+        $data_orderid       = $this->config['order_sn'];
+        $data_vamount       = $this->config['order_amount'];
+        $data_vmoneytype    = 'CNY';
+        $data_vpaykey       = trim($this->config['chinabank_key']);
+
+        $data_vreturnurl    = $this->config['return_url'];
+		$remark1			= $this->config['body'];
+
+
+        $MD5KEY =$data_vamount.$data_vmoneytype.$data_orderid.$data_vid.$data_vreturnurl.$data_vpaykey;
+        $MD5KEY = strtoupper(md5($MD5KEY));
+
+        $def_url  = '<span style="clean:both;"><form  method=post action="https://pay3.chinabank.com.cn/PayGate" target="_blank">';
+        $def_url .= "<input type=HIDDEN name='v_mid' value='".$data_vid."'>";
+        $def_url .= "<input type=HIDDEN name='v_oid' value='".$data_orderid."'>";
+        $def_url .= "<input type=HIDDEN name='v_amount' value='".$data_vamount."'>";
+        $def_url .= "<input type=HIDDEN name='v_moneytype'  value='".$data_vmoneytype."'>";
+        $def_url .= "<input type=HIDDEN name='v_url'  value='".$data_vreturnurl."'>";
+        $def_url .= "<input type=HIDDEN name='v_md5info' value='".$MD5KEY."'>";
+        $def_url .= "<input type=HIDDEN name='remark1' value='".$remark1."'>";
+        $def_url .= "<input type=submit class='button' value='" .L('PAY_NOW'). "'>";
+        $def_url .= "</form></span>";
+
+        return $def_url;
+
+	}
+
+	public function respond()
+    {
+        $v_oid          = trim($_POST['v_oid']); //订单编号
+        $v_pmode        = trim($_POST['v_pmode']); //支付方式
+        $v_pstatus      = trim($_POST['v_pstatus']); //支付状态 20(表示支付成功)30(表示支付失败)
+        $v_pstring      = trim($_POST['v_pstring']); //支付结果信息
+        $v_amount       = trim($_POST['v_amount']); //订单总金额
+        $v_moneytype    = trim($_POST['v_moneytype']); //币种
+        $remark1        = trim($_POST['remark1' ]); //备注字段1
+        $remark2        = trim($_POST['remark2' ]); //备注字段2
+        $v_md5str       = trim($_POST['v_md5str' ]); //订单MD5校验码
+
+        /**
+         * 重新计算md5的值
+         */
+        $key            = $this->config['chinabank_key'];
+
+        $md5string=strtoupper(md5($v_oid.$v_pstatus.$v_amount.$v_moneytype.$key));
+
+        /* 检查秘钥是否正确 */
+        if ($v_md5str==$md5string)
+        {
+            if ($v_pstatus == '20')
+            {
+				order_pay_status($v_oid,'2');
+                return true;
+            }
+        }
+        else
+        {
+            return false;
+        }
+	}
+}
+?>

+ 78 - 0
Ainaphp/Tpl/Admin/Default/Access_index.html

@@ -0,0 +1,78 @@
+
+<script type="text/javascript">
+
+  function checknode(obj)
+  {
+      var chk = $("input[type='checkbox']");
+      var count = chk.length;
+      var num = chk.index(obj);
+      var level_top = level_bottom =  chk.eq(num).attr('level');
+      for (var i=num; i>=0; i--)
+      {
+              var le = chk.eq(i).attr('level');
+              if(eval(le) < eval(level_top))
+              {
+                  chk.eq(i).attr("checked",true);
+                  var level_top = level_top-1;
+              }
+      }
+      for (var j=num+1; j<count; j++)
+      {
+              var le = chk.eq(j).attr('level');
+              if(chk.eq(num).attr("checked")=='checked') {
+
+                  if(eval(le) > eval(level_bottom)) chk.eq(j).attr("checked",true);
+                  else if(eval(le) == eval(level_bottom)) break;
+              }
+              else {
+                  if(eval(le) > eval(level_bottom)) chk.eq(j).attr("checked",false);
+                  else if(eval(le) == eval(level_bottom)) break;
+              }
+      }
+  }
+</script>
+<style>.mainnav_title{display:none;}span.w1{float:left;width:89px}</style>
+<form id="myform" name="myform" action="{:U('Access/insert')}" method="post">
+<input type="hidden" id="rid" name="rid" value="{$rid}" />
+<div class="pad-lr-10">
+<div class="table-list">
+    <table width="100%" cellspacing="0"  style="border:1px solid #ccc;" id="dnd-example">
+	<tbody>
+	<tr>
+		<td width=100 bgcolor="#CBE0F6">
+		<input type='checkbox' name='nid[1]' value='1'  level='0' {if array_key_exists(1,$alist)}checked{/if}  onclick='javascript:checknode(this);' />{$topnode[0][title]}
+		</td>
+		<td bgcolor="#CBE0F6"></td>
+	</tr>
+	<volist name="node" id="r" >
+
+		<tr>
+		<td  colspan="2" bgcolor="#F0F5FB" align="center" height="40"><b>{$r[groupinfo][name]}</b></td>
+		</tr>
+			<volist name="r[data]" id="rr">
+
+			<if condition="$rr[level]==2">
+			<tr>
+			<td style='padding-left:15px;' bgcolor="#F8FAFC"><input type='checkbox' name='nid[{$rr.id}]' value='{$rr.id}'  level='{$rr.level}' {$rr.selected}  onclick='javascript:checknode(this);' />&nbsp;{$rr.title}
+			</td>
+
+			<td><volist name="node[$rr[groupid]][data]" id="rrr" >
+						<if condition="$rrr[pid]==$rr[id]">
+						<span class="w1"><input type='checkbox' name='nid[{$rrr.id}]' value='{$rrr.id}'  level='{$rrr.level}' {$rrr.selected}  onclick='javascript:checknode(this);' /> {$rrr.title} &nbsp;</span>
+
+						</if>
+						</volist></td>
+
+			</tr>
+
+			</if>
+			</volist>
+
+	</volist>
+	<input type="hidden" name="isajax" value="1" />
+	<input name="dosubmit" type="submit" value="1" class="hidden" id="dosubmit">
+	</tbody>
+    </table>
+</div>
+</div>
+</form></div>

+ 78 - 0
Ainaphp/Tpl/Admin/Default/Admin_header.html

@@ -0,0 +1,78 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset={:C('DEFAULT_CHARSET')}" />
+<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
+<title>{:L('welcome')}{:L('system_name')}bangju.com</title>
+<link rel="stylesheet" type="text/css" href="__ROOT__/Public/Css/style.css" />
+<script type="text/javascript" src="__ROOT__/Public/Js/jquery.min.js"></script>
+<script type="text/javascript" src="__ROOT__/Public/Js/jquery.artDialog.js?skin=default"></script>
+<script type="text/javascript" src="__ROOT__/Public/Js/iframeTools.js"></script>
+<script type="text/javascript" src="__ROOT__/Public/Js/jquery.form.js"></script>
+<script type="text/javascript" src="__ROOT__/Public/Js/jquery.validate.js"></script>
+<script type="text/javascript" src="__ROOT__/Public/Js/MyDate/WdatePicker.js"></script>
+<script type="text/javascript" src="__ROOT__/Public/Js/jquery.colorpicker.js"></script>
+<script type="text/javascript" src="__ROOT__/Public/Js/my.js"></script>
+<script type="text/javascript" src="__ROOT__/Public/Js/swfupload.js"></script>
+
+<script language="JavaScript">
+<!--
+var ROOT =	 '__ROOT__';
+var URL = '__URL__';
+var APP	 =	 '__APP__';
+var PUBLIC = '__PUBLIC__';
+function confirm_delete(url){
+	art.dialog.confirm("{:L('real_delete')}", function(){location.href = url;});
+}
+$(window.parent.$("#main_loading").hide());
+//-->
+</script>
+</head>
+<body width="100%">
+<div id="result" class="result none"></div>
+<div class="mainbox">
+
+<if condition="empty($_GET['isajax'])">
+
+	<div id="nav" class="mainnav_title">
+
+	<div id="lang">
+	<if condition="APP_LANG">
+		<?php
+		parse_str($_SERVER['QUERY_STRING'],$urlarr);
+		unset($urlarr[l]);
+		$url='index.php?'.http_build_query($urlarr);
+		?>
+		<volist name="Lang" id="langvo">
+			<a href="{$url}&l={$langvo.mark}" <if condition="$langvo[mark]==$_SESSION['YP_lang']"> class="on"</if>>{$langvo.name}</a>
+		</volist>
+	</if>
+	</div>
+	<ul><a href="{:U($nav[bnav][model].'/'.$nav[bnav][action],$nav[bnav][data])}">{$nav.bnav.name}</a>|
+	<volist name="nav.nav" id="vonav" key="n">
+
+	<if condition="$vonav[data][isajax]">
+        {if $n>1}|{/if}<a href="javascript:void(0);" onclick="openwin('{$vonav[action]}','{:U($vonav[model].'/'.$vonav[action],$vonav[data])}','{$vonav.name}',600,440)">{$vonav.name}</a>
+	<else />
+	    {if $n>1}|{/if}<a href="{:U($vonav[model].'/'.$vonav[action],$vonav[data])}">{$vonav.name}</a>
+	</if>
+	</volist></ul>
+	</div>
+    <script>
+	var onurl ='?{$_SERVER["QUERY_STRING"]}';
+	jQuery(document).ready(function(){
+		$('#nav ul a ').each(function(i){
+		if($('#nav ul a').length>1){
+			var thisurl= $(this).attr('href');
+			thisurl = thisurl.replace('&menuid={:cookie("menuid")}','');
+			if(onurl.indexOf(thisurl) == 0 ) $(this).addClass('on').siblings().removeClass('on');
+		}else{
+			$('#nav').hide();
+		}
+		});
+		if($('#nav ul a ').hasClass('on')==false){
+		$('#nav ul a ').eq(0).addClass('on');
+		}
+	});
+	</script>
+</if>

+ 6 - 0
Ainaphp/Tpl/Admin/Default/Attachment_filelist.html

@@ -0,0 +1,6 @@
+{__NOLAYOUT__}<div id="thumbnails1" ><ul class="attachment-list" style="padding:0;margin:0;">
+<volist name="list" id="vo" key="k">
+    <li><div id="attachment_{$vo[aid]}" class="img"><a href="javascript:void(0);" id="on_{$vo[aid]}" onclick="javascript:add_file(this,{$vo['aid']},{$vo['status']})"><div class="icon"></div><img src="{$vo['thumb']}" path="{$vo['filepath']}" alt="{$vo['filename']}" imgid="{$vo[aid]}" imgsize="{$vo[filesize]}" style="max-width:80px;_width:80px;max-height:80px;_height:80px;"></a></div></li>
+</volist>
+</ul></div>
+<div id="pages" class="page">{$page}</div>

+ 161 - 0
Ainaphp/Tpl/Admin/Default/Attachment_index.html

@@ -0,0 +1,161 @@
+
+<style>
+	html{_overflow-y:scroll}
+	.swfupload {position: absolute;z-index: 1;}
+	.mainnav_title {display:none;}
+	</style>
+	<link href="__ROOT__/Public/Js/swfupload/swfupload.css" rel="stylesheet" type="text/css" />
+	<link rel="stylesheet" href="/js/layui/css/layui.css">
+    <script src="/js/layui/layui.js"></script>
+	<script type="text/javascript" src="__ROOT__/Public/Js/swfupload/swfupload.js"></script>
+	<script type="text/javascript" src="__ROOT__/Public/Js/swfupload/fileprogress.js"></script>
+	<script type="text/javascript" src="__ROOT__/Public/Js/swfupload/handlers.js"></script>
+	<script type="text/javascript">
+			$.ajaxSetup ({ cache: false });
+	
+			var file_limit = {$file_limit};
+			var swfu;
+	function ajaxload(typeid,page,inputid,isadmin)
+	{
+		var data = '';
+		var url =  "{:U('Attachment/filelist')}&typeid="+typeid+"&p="+page+"&inputid="+inputid+"&isadmin="+isadmin;
+		$.ajax({
+			 type: "POST",
+			 url: url,
+			 data: data,
+			 success: function(msg){
+				$('#'+inputid).html(msg);
+				for(var i=0;i<ids.length;i++){
+					$('#on_'+ids[i]).addClass("on");
+				}
+			 }
+		});
+	}
+	
+	</script>
+	<div id="content">
+	<div id="tabs">
+		<div class="title"><ul><li class="on"><a href="javascript:void(0);">{:L('upload_file')}</a></li>
+		<li><a href="javascript:void(0);">{:L('upload_url')}</a></li>
+		<if condition="!empty($more)">
+		<li><a href="javascript:void(0);" onclick="ajaxload(1,1,'filelist',<?php echo $isadmin;?>);">{:L('upload_list_file')}</a></li>
+		<li><a href="javascript:void(0);"  onclick="ajaxload(0,1,'nouselist',<?php echo $isadmin;?>);">{:L('upload_unuse_file')}</a></li>
+		</if>
+		<if condition="!empty($no_use_files)">
+		<li style="border:0;background:none;"><a href="{:U('Attachment/cleanfile?isadmin='.$isadmin)}" style="color:#FB0000;">{:L('no_use_files')}</a></li>
+		</if>
+		</ul></div>
+	
+		<div class="content_1">
+			<div class="tabbox" style="display:block;">
+					<div id="divMovieContainer">
+						<!-- <div class="selectbut"><span id="spanButtonPlaceHolder"></span></div>
+						<input type="button" value="{:L('start_upload')}" id="uploadbut" onclick="swfu.startUpload();"/> -->
+						<div style="display: inline-block;float:left;">
+							<button type="button" class="layui-btn layui-btn-sm" id="upload">
+								<i class="layui-icon">&#xe67c;</i>上传图片
+							</button>
+						</div>
+						<div style="color:#959595;line-height:24px;height:24px;background:url() no-repeat;padding-left:20px;"><input type="checkbox" id="addwater" name="addwater" value="1" onclick="addwater_enable();" <if condition="$watermark_enable==1"> checked</if>/> <font color="green">{:L('upload_add_water')}</font> , {:L('upload_say4')} <font color="red">{$file_types}</font> {:L('upload_say5')}</div><br>
+						<div style="color:#454545;clear:both;line-height:24px;height:24px;"> {:L('upload_say1')} <font color="red">{$file_limit}</font> {:L('upload_say2')} <font color="red">{$file_size}</font>	{:L('upload_say3')}</div>
+					</div>
+	
+	
+					<!-- <div id="divStatus">{:L('upload_say6')}<span id="tdFilesQueued">0</span>{:L('upload_say7')}<span id="tdErrors">0</span> {:L('upload_say8')}<span id="tdFilesUploaded">0</span> {:L('upload_say9')}</div> -->
+					<fieldset  id="swfupload-box">
+						<legend>{:L('file_list')}</legend>
+						<ul id="fsUploadProgress"></ul>
+						<ul class="attachment-list"  id="thumbnails"></ul>
+					</fieldset>
+	
+			</div>
+			<div class="tabbox">
+			 <br>
+				{:L('upload_fileurl')}: <input type="text" id="fileurl" name="fileurl" class="input-text" value=""  style="width:350px;"  onblur="addfileurl(this)">
+				<br><br><br>
+	
+			</div>
+			<div class="tabbox">
+				<div id="filelist"></div>
+			</div>
+			<div class="tabbox">
+				<div id="nouselist"></div>
+			</div>
+		</div>
+	</div>
+	
+	<div  id="myuploadform" style="display:none;" ></div>
+	<script>
+	new Tabs("#tabs",".title ul li",".content_1",".tabbox","on",1);
+	function addfileurl(obj) {
+		var strs = $(obj).val() ?  $(obj).val() : '';
+	
+		if(strs){
+			var datas='<div id="uplist_1"><input type="hidden" id="aids" name="aids"  value="0"  /><input type="text"  id="filedata" name="filedata" value="'+strs+'"  /><input type="text"  id="namedata" name="namedata" value=""  /> &nbsp;<a href="javascript:remove_this(\'uplist_1\');">{:L('remove')}</a> </div>';
+			$('#myuploadform').html(datas);
+			$('#thumbnails   a ').removeClass("on");
+			$('.img a ').removeClass("on");
+		}else{
+	
+			$('#myuploadform').html('');
+		}
+	}
+	
+	var insert2Xheditor =  insert2Xheditor || function(){
+			<if condition="$_GET[immediate]==1">var immediate='!';</if>
+			var arrMsg=[],img = '',data = '',i=0;
+			var num = $('#myuploadform > div').length;
+			if(num){
+					$('#myuploadform   div').each(function(){
+						var status =  $(this).find('#status').val();
+						var aid = $(this).find('#aids').val();
+						var src = $(this).find('#filedata').val();
+						var name = $(this).find('#namedata').val();
+						if(status!=0) aid=0;
+						arrMsg[i]= { "url":immediate+src,"localfile":name,"id":aid,"editorid":"{$_GET[editorid]}" };
+						i++;
+				   });
+				  // $('#{$_GET[editorid]}_aid_box').append(data);
+			}
+			//arrMsg.push({"name":"","url":"!200906030521128703.gif","id":});
+			callback(arrMsg);
+	}
+
+	layui.use('upload', function () {
+		var upload = layui.upload;
+		//执行实例
+		var uploadInst = upload.render({
+			elem: '#upload' //绑定元素
+			, url: '{:U('Attachment/upload')}' //上传接口
+			, data:{ "PHPSESSID": "<?php echo  $sessid;?>", "isadmin": "<?php echo $isadmin;?>", "userid": "<?php echo $userid?>", "swf_auth_key": "<?php echo $swf_auth_key;?>", "isthumb": "<?php echo $isthumb;?>", "moduleid": "<?php echo $moduleid?>", "addwater": "<?php echo intval($watermark_enable);?>", "lang": "<?php echo $lang;?>" }
+			,multiple :true
+			,number:file_limit
+			, done: function (res) {
+				if (res.status == 1) {
+					file_limit--;
+					if(file_limit <= 0){
+						$('#divMovieContainer').hide();
+					}
+					add_uploadok(res.data);
+				}
+			}
+			, error: function () {
+			}
+	    });
+		$('#addwater').on('click', function () {
+			if ($(this).attr('checked')) {
+				uploadInst.config.data.addwater = "1"
+			} else {
+				uploadInst.config.data.addwater = ""
+			}
+		})
+	})
+	</script>
+	<if condition="!empty($_GET[editorid])">
+	<div id="bootline"></div>
+	<div id="btnbox" class="btn" style="padding-left:450px;">
+			<INPUT TYPE="submit" onclick="insert2Xheditor();" value="{:L(dosubmit)}" class="button " >
+	<input TYPE="reset" onclick="unloadme();" value="{:L(cancel)}" class="button">
+	</div>
+	</if>
+	

+ 30 - 0
Ainaphp/Tpl/Admin/Default/Block_edit.html

@@ -0,0 +1,30 @@
+
+<form method='post' name="myform" id="myform" action="<if condition="$action_name=='add'">{:U($module_name.'/insert')}<else />{:U($module_name.'/update')}</if>">
+	<table cellpadding=0 cellspacing=0 class="table_form" width="100%">
+	<tr>
+		<td width="140">{:L('name')}:</td>
+		<td><input type="text" class="input-text"  name="name" id="name" value="{$vo.name}"  ></td>
+	</tr>
+	<tr>
+		<td>{:L('pos')}:</td>
+		<td><input type="text" class="input-text"  name="pos" id="pos" value="{$vo.pos}"  validate="required:true,en_num:true, minlength:2, maxlength:20"></td>
+	</tr>
+	<tr>
+		<td>图片上传:</td>
+		<td>{: $Form->image(array('field'=>'file','moduleid'=>'234','setup'=>array('upload_maxsize'=>'1','upload_allowext'=>'jpg,jepg,gif,png,','more'=>'0')),$vo[file])}</td>
+	</tr>
+	<tr>
+		<td>{:L('content')}:</td>
+		<td>{: $Form->editor(array('field'=>'content','moduleid'=>'231','setup'=>array('toolbar'=>'full','flashupload'=>'1')),$vo[content])}</td>
+	</tr>
+	</table>
+	<div class="btn">
+	<if condition="$vo[id]!=''"><input TYPE="hidden" name="id" value="{$vo.id}"></if>
+	<INPUT TYPE="submit"  value="{:L('dosubmit')}" class="button buttonBtn" >
+	<input type="hidden" name="forward" value="{$_SERVER['HTTP_REFERER']}" />
+	<input TYPE="reset"  value="{:L('reset')}" class="button">
+	</div>
+</form>
+</div>
+
+</body></html>

+ 32 - 0
Ainaphp/Tpl/Admin/Default/Block_index.html

@@ -0,0 +1,32 @@
+
+
+<form  id="myform" name="myform" action="{:U('Type/listorder')}" method="post">
+<div class="table-list">
+    <table width="100%" cellspacing="0">
+        <thead>
+      		<tr>
+            <th width="20">ID</th>
+            <th align="left">{:L('name')}</th>
+			<th width="40">{:L('pos')}</th>
+			<th width="270">{:L('manage')}</th>
+            </tr>
+      	</thead>
+      	<tbody>
+      		<volist name="list" id="vo" key="k">
+      		<tr>
+			<td align='center'>{$vo['id']}</td>
+			<td >{$vo['name']}</td>
+			<td>{$vo['pos']}</td>
+      		<td align="center">
+			<a href="{:U($module_name.'/edit',array(id=>$vo['id'],pos=>$vo['pos']))}">{:L('edit')}</a> |
+			<a href="javascript:confirm_delete('{:U($module_name.'/delete',array(id=>$vo['id']))}')">{:L('delete')}</a>
+      		</td>
+      		</tr>
+      		</volist>
+      	</tbody>
+      	</table>
+</div>
+
+
+</form></div>
+</body></html>

+ 199 - 0
Ainaphp/Tpl/Admin/Default/Category_edit.html

@@ -0,0 +1,199 @@
+<script type="text/javascript" src="__ROOT__/Public/Js/jQuery.Hz2Py-min.min.js"></script>
+<form name="myform"  id="myform"  action="<if condition="$action_name=='add'">{:U('Category/insert')}<else />{:U('Category/update')}</if>&iscreatehtml=1" method="post">
+
+
+<div id="tabs" style="margin-top:10px;">
+	<div class="title"><ul class="clearfix" style="margin-left:30px;"><li class="on"><a href="javascript:void(0);">{:L(base_setup)}</a></li>
+	<li style="margin-left:10px;"><a href="javascript:void(0);">{:L(seo_setup)}</a></li>
+</ul></div>
+
+<div class="content_2">
+	<div class="tabbox" style="display:block;">
+		<table cellpadding=0 cellspacing=0 class="table_form"width="100%"><tr>
+		<td width="15%">{:L('chose_module')}</td>
+        <td width="85%" class="box_thumb">
+
+		<load href="./Public/Js/swfupload.js"/>
+		<div class="thumb_box" style ="margin-top:-7px;left:340px;"><div id="image_aid_box"></div>
+		<a href="javascript:swfupload('image_uploadfile','image','{:L(uploadfiles)}',1,1,0,1,'jpeg,jpg,png,gif',3,0,'{$yourphp_auth}',yesdo,nodo)"><img src="<if condition="!empty($vo['image'])">{$vo['image']}<else/>./Public/Images/admin_upload_thumb.png</if>"  id="image_pic" ></a><br> <input type="button" value="{:L('clean_thumb')}" onclick="javascript:clean_thumb('image');" class="button" /><input type="hidden"  id="image" name="image"  value="{$vo['image']}" /><span class="thumb_tips"></span></div>
+		{:Form::select(array('field'=>'moduleid','options'=>$module+array('0'=>array('id'=>0,'title'=>L('Module_url'))),'options_key'=>'id,title','setup'=>array('onchange'=>'changetemplate(this.value)')),$vo['moduleid'])}
+		</td>
+      </tr>
+      <tr>
+        <td>{:L('chose_parentid')}</td>
+        <td>
+
+		<select name="parentid">
+		<option value="">{:L('select_parentid')}</option>
+		{$select_categorys}
+		</select>
+		</td>
+      </tr>
+
+      	<tr>
+		<td>* {:L('catname')}</td>
+		<td><input type="text" name="catname" class="input-text  required"  id="catname" value="{$vo['catname']}"  minlength="1"  maxlength="30"  /></td>
+		</tr>
+
+	    <tr>
+		<td>* {:L('catdir')}</td>
+		<td><input type="text" id="catdir" name="catdir" class="input-text  required" value="{$vo['catdir']}" validate="required:true, english:true,minlength:1, maxlength:30"/><span class="catdirBtn" onclick="catdir.value=($('#catname').toPinyin());">{:L('pinyin')}</span></td>
+		</tr>
+
+
+
+
+		<tr id="module_url" style="display:none;">
+		<td>{:L('cat_link_url')}</td>
+		<td><input type="text" name="url" class="input-text"  value="<if condition="$vo['type']==1">{$vo['url']}</if>" size='50'  /><input type="hidden" id="type" name="type" value="0" /></td>
+		</tr>
+
+
+<!--
+		<tr style="background:#EFEFEF;">
+		<td>{:L('chage_is')}: </td>
+		<td><input type="checkbox"  class="input_checkbox "  id="chage_all" name="chage_all" value="1" /><font color="red"> {:L('chage_all')}</font>
+		</td>
+		</tr>
+-->
+
+
+		<tr id="urlrule">
+		<td>{:L('urlrule')}</td>
+		<td>{:Form::select(array('field'=>'urlruleid','options'=>$Urlrule,'options_key'=>'key,listexample'),$vo['urlruleid'])}</td>
+		</tr>
+
+
+		<tr>
+		<td>{:L('pagesize')}</td>
+		<td><input type="text" name="pagesize" class="input-text" value="<if condition="!empty($vo['pagesize'])">{$vo['pagesize']}</if>" size="3" /> <font color="red">{:L('pagesize_desc')}</font></td>
+		</tr>
+
+		<tr>
+		<td>{:L('template_list')}</td>
+		<td>
+		<select id="template_list" name="template_list"></select>
+			</td>
+		</tr>
+
+		<tr>
+		<td>{:L('template_show')}</td>
+		<td><select id="template_show" name="template_show"></select>
+		</td>
+		</tr>
+		</table>
+
+
+
+	</div>
+
+	<div class="tabbox" style="display:none;">
+		<table cellpadding=0 cellspacing=0 class="table_form"width="100%">
+		 <tr>
+		  <td>{:L('seo_title')}</td>
+		  <td><input name='title' type='text' id='meta_title' value="{$vo['title']}" class="input-text"  size='60' maxlength='150'></td>
+		</tr>
+		<tr>
+		  <td>{:L('seo_keywords')}</td>
+		  <td><input name='keywords' type='text' id='meta_keywords' value="{$vo['keywords']}" class="input-text"  size='60' maxlength='150'></td>
+		</tr>
+		<tr>
+		  <td>{:L('seo_description')}</td>
+		  <td><textarea name='description' id='meta_description'  rows="5" cols="60" >{$vo['description']}</textarea></td>
+		</tr>
+		</table>
+	</div>
+</div>
+
+
+
+		<div class="btn">
+		<if condition="$vo['id']!=''"><input TYPE="hidden" name="id" value="{$vo.id}"></if>
+		<INPUT TYPE="submit"  value="{:L('dosubmit')}" class="button buttonBtn" >
+		<input TYPE="reset"  value="{:L('cancel')}" class="button">
+		</div>
+
+</form></div>
+
+<script>
+
+var modulearr = new Array();
+<volist name="module" id="mdate">
+modulearr[{$mdate['id']}] = "{$mdate['name']}";
+</volist>
+var templatearr = new Array();
+<volist name="templates" id="tem">
+templatearr[{$i}] = "{$tem['name']},{$tem['value']},{$tem['filename']}";
+</volist>
+
+
+var datas = "<option value=''>{:L('please_chose')}</option>";
+var moduleid =  $('#moduleid').val();
+
+
+showtemplist(moduleid,<if condition="empty($vo[listtype])">0<else />{$vo.listtype}</if>);
+function showtemplist(m,t){
+	var type='_list';
+	if(t){type='_index';}
+	var mtlist = modulearr[m]+type;
+	var mtshow = modulearr[m]+'_show';
+	if(modulearr[m]=='Page') mtlist=mtshow ='Page';
+	$('#template_list').html(datas);
+	$('#template_show').html(datas);
+	listdatas = showdatas ='';
+	for(i=1;i<templatearr.length;i++){
+		data = templatearr[i].split(',');
+		if(data[0].indexOf(mtlist)  >= 0){
+			listdatas  ="<option value='"+data[1]+"'>"+data[2]+"</option>";
+			$('#template_list').append(listdatas);
+		}
+		if(data[0].indexOf(mtshow)  >= 0){
+			showdatas ="<option value='"+data[1]+"'>"+data[2]+"</option>";
+			$('#template_show').append(showdatas);
+		}
+	}
+	$("#template_list").attr("value",'{$vo.template_list}');
+	$("#template_show").attr("value",'{$vo.template_show}');
+}
+function changetemplate(m){
+	if(m==0){
+		$('#module_url').show();
+		$('#type').val('1');
+		$('#catdir').removeClass('required');
+	}else{
+		$('#module_url').hide();
+		$('#type').val('0');
+		$('#catdir').addClass('required');
+	}
+	showtemplist(m,0);
+	$("#listtype").removeAttr("checked");
+}
+function templatetype(){
+	var moduleid = $('#moduleid').val();
+	if($("#listtype").attr('checked')=='checked'){
+		showtemplist(moduleid,1);
+	}else{
+		showtemplist(moduleid,0);
+	}
+}
+new Tabs("#tabs",".title ul li",".content_2",".tabbox","on",1);
+
+
+function urlrule(m){
+
+	if(m==1){
+		$('#urlrule').show();
+	}else{
+		$('#urlrule').hide();
+	}
+}
+urlrule({$vo['ishtml']});
+
+
+<if condition="!empty($_GET['type'])">
+$('#moduleid').val(0);
+changetemplate(0);
+</if>
+
+
+</script>

Einige Dateien werden nicht angezeigt, da zu viele Dateien in diesem Diff geändert wurden.