<?php
// 检测服务器软件类型
function software_type() {
    $server_software = isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : '';
    if (strpos($server_software, 'IIS') !== false) {
        return 'iis';
    } elseif (strpos($server_software, 'nginx') !== false) {
        return 'nginx';
    } elseif (strpos($server_software, 'Apache') !== false) {
        return 'apache';
    } else {
        return 'unknown';
    }
}

$title='文章列表';
include __DIR__ . '/head.php';
if($_GET['my'] == 'active'){
	$id = $_GET['id'];
	$active = $_GET['active'];
	$row = $DB->getRow("SELECT * FROM `pre_article` where zid='1' AND id='{$id}'");
	if(!$row){
		exit("<script language='javascript'>alert('没有该文章信息');window.location.href='./article.php';</script>");
	}
	$sql="UPDATE `pre_article` SET active='{$active}' WHERE id='{$id}' AND zid='1'";
	if($DB->exec($sql)){
		exit("<script language='javascript'>window.location.href='./article.php';</script>");
	}else{
		exit("<script language='javascript'>alert('失败".$DB->error()."');window.location.href='./article.php';</script>");
	}	
}
if($_GET['my'] == 'delete'){
	$id = $_GET['id'];
	$row = $DB->getRow("SELECT * FROM `pre_article` where zid='1' AND id='{$id}'");
	if(!$row){
		exit("<script language='javascript'>alert('没有该文章信息');window.location.href='./article.php';</script>");
	}
	$sql="DELETE FROM pre_article WHERE id='{$id}' AND zid='1'";
	if($DB->exec($sql)){
		exit("<script language='javascript'>window.location.href='./article.php';</script>");
	}else{
		exit("<script language='javascript'>alert('失败".$DB->error()."');window.location.href='./article.php';</script>");
	}
}
if($_GET['my'] == 'add_submit' || isset($_POST['submit'])){
	$title = $_POST['title'];	
	$keywords = $_POST['keywords'];	
	$skeywords = $_POST['skeywords'];	
	$description = $_POST['description'];		
	$content = $_POST['content'];	
	$cid = isset($_POST['articleClass'])?daddslashes($_POST['articleClass']):'0';	
	$top = isset($_POST['top'])?daddslashes($_POST['top']):'0';	
	$addtime = isset($_POST['addtime'])?daddslashes($_POST['addtime']).' '.date("H:i:s"):date("Y-m-d H:i:s");	
	$id = $_POST['articleid'];
	if($title==''||$content==''){

		exit("<script language='javascript'>alert('参数不完整');window.location.href='?my=add';</script>");

	}
	if($_POST['add'] == 'add'){
		$sql="INSERT INTO `pre_article` (`zid`,`cid`,`title`,`content`,`keywords`,`description`,`top`,`active`,`skeywords`,`addtime`) VALUES ('1','".$cid."','".$title."','".$content."','".$keywords."','".$description."','".$top."','1','".$skeywords."','".$addtime."')";
	}else{
		$sql="UPDATE `pre_article` SET cid='{$cid}', title='{$title}', content='{$content}', keywords='{$keywords}', description='{$description}', top='{$top}', skeywords='{$skeywords}' WHERE id='{$id}' AND zid='1'";
	}
	if($DB->exec($sql)){
		exit("<script language='javascript'>window.location.href='./article.php';</script>");
	}else{
		exit("<script language='javascript'>alert('失败".$DB->error()."');window.location.href='./article.php';</script>");
	}
}
?>
<div class="p-4 md:p-6">
<?php if($_GET['my']=='add'){
	$class = '<option value="0">不分类</option>';
	$rs=$DB->query("SELECT * FROM `pre_article_class` where zid='1'");
	while($res = $rs->fetch()){
		$class .= '<option value="'.$res['id'].'">'.$res['name'].'</option>';
	}
?>
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="p-4 md:p-6 border-b border-gray-200">
            <h2 class="text-base md:text-lg font-semibold text-gray-800">添加文章</h2>
        </div>
        <div class="p-4 md:p-6">
            <form action="?my=add_submit" method="post" role="form" class="space-y-6">
                <input type="hidden" name="add" value="add">
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                    <label class="text-xs md:text-sm font-medium text-gray-700">文章分类</label>
                    <div class="md:col-span-3">
                        <select class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" name="articleClass">
                            <?php echo $class?>
                        </select>
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                    <label class="text-xs md:text-sm font-medium text-gray-700">文章标题</label>
                    <div class="md:col-span-3">
                        <input type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" name="title">
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                    <label class="text-xs md:text-sm font-medium text-gray-700">SEO关键词</label>
                    <div class="md:col-span-3">
                        <input type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" name="keywords" value="<?php echo $conf['keywords']?>">
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-start">
                    <label class="text-xs md:text-sm font-medium text-gray-700">SEO描述</label>
                    <div class="md:col-span-3">
                        <textarea class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" name="description" rows="2" value="<?php echo $conf['description']?>"></textarea>
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-start">
                    <label class="text-xs md:text-sm font-medium text-gray-700">文章内容</label>
                    <div class="md:col-span-3">
                        <textarea class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" name="content" id="editor_msg" rows="10"></textarea>
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                    <label class="text-xs md:text-sm font-medium text-gray-700">文章底部关键字</label>
                    <div class="md:col-span-3">
                        <input type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" name="skeywords" value="<?php echo $conf['keywords']?>">
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-start">
                    <label class="text-xs md:text-sm font-medium text-gray-700">是否置顶</label>
                    <div class="md:col-span-3">
                        <select class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" name="top">
                            <option value="0">否</option>
                            <option value="1">是</option>
                        </select>
                    </div>
                </div>
                <div class="pt-4 border-t border-gray-200">
                    <button type="submit" class="w-full md:w-auto px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition text-sm">
                        添加
                    </button>
                </div>
            </form>
        </div>
    </div>
<?php }else if($_GET['my']=='edit'){
	$id = $_GET['id'];
	$row = $DB->getRow("SELECT * FROM `pre_article` where zid='1' AND id='{$id}'");
	$addtime = date('Y-m-d',strtotime($row['addtime']));
	$class = '<option value="0">不分类</option>';
	$rs=$DB->query("SELECT * FROM `pre_article_class` where zid='1'");
	while($res = $rs->fetch()){
		if($res['id'] == $row['cid']){
			$class .= '<option selected="selected" value="'.$res['id'].'">'.$res['name'].'</option>';
		}else{
			$class .= '<option value="'.$res['id'].'">'.$res['name'].'</option>';
		}
	}
?>
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="p-4 md:p-6 border-b border-gray-200">
            <h2 class="text-base md:text-lg font-semibold text-gray-800">修改文章</h2>
        </div>
        <div class="p-4 md:p-6">
            <form action="?my=add_submit" method="post" role="form" class="space-y-6">
                <input type="hidden" name="add" value="set">
                <input type="hidden" name="articleid" value="<?php echo $row['id']?>">
                <input type="hidden" name="addtime" value="<?php echo $row['addtime']?>">
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                    <label class="text-xs md:text-sm font-medium text-gray-700">文章分类</label>
                    <div class="md:col-span-3">
                        <select class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" name="articleClass">
                            <?php echo $class?>
                        </select>
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                    <label class="text-xs md:text-sm font-medium text-gray-700">文章标题</label>
                    <div class="md:col-span-3">
                        <input type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" name="title" value="<?php echo $row['title']?>">
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                    <label class="text-xs md:text-sm font-medium text-gray-700">SEO关键词</label>
                    <div class="md:col-span-3">
                        <input type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" name="keywords" value="<?php echo $row['keywords']?>">
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-start">
                    <label class="text-xs md:text-sm font-medium text-gray-700">SEO描述</label>
                    <div class="md:col-span-3">
                        <textarea class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" name="description" rows="2" value="<?php echo $row['description']?>"></textarea>
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-start">
                    <label class="text-xs md:text-sm font-medium text-gray-700">文章内容</label>
                    <div class="md:col-span-3">
                        <textarea class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" name="content" id="editor_msg" rows="10"><?php echo $row['content']?></textarea>
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                    <label class="text-xs md:text-sm font-medium text-gray-700">文章底部关键字</label>
                    <div class="md:col-span-3">
                        <input type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" name="skeywords" value="<?php echo $row['skeywords']?>">
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-start">
                    <label class="text-xs md:text-sm font-medium text-gray-700">是否置顶</label>
                    <div class="md:col-span-3">
                        <select class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" name="top" default="<?php echo $row['top']?>">
                            <option value="0">否</option>
                            <option value="1">是</option>
                        </select>
                    </div>
                </div>
                <div class="pt-4 border-t border-gray-200">
                    <button type="submit" class="w-full md:w-auto px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition text-sm">
                        修改
                    </button>
                </div>
            </form>
        </div>
    </div>
<?php }else if($_GET['my']=='rewrite'){
	$software_type = software_type();
?>
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="p-4 md:p-6 border-b border-gray-200">
            <h2 class="text-base md:text-lg font-semibold text-gray-800">伪静态配置</h2>
        </div>
        <div class="p-4 md:p-6">
            <form onsubmit="saveSetting(this);return false;" method="post" role="form" class="space-y-6">
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-start">
                    <label class="text-xs md:text-sm font-medium text-gray-700">伪静态开关</label>
                    <div class="md:col-span-3">
                        <select class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" name="article_rewrite" default="<?php echo $conf['article_rewrite']?>">
                            <option value="0">关闭</option>
                            <option value="1">开启</option>
                        </select>
                    </div>
                </div>
                <div class="pt-4 border-t border-gray-200">
                    <button type="submit" class="w-full md:w-auto px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition text-sm">
                        确定
                    </button>
                </div>
            </form>
            <div class="mt-6 p-4 bg-red-50 border border-red-200 rounded-lg">
                <h4 class="text-sm font-semibold text-red-600 mb-2">
                    <i class="fas fa-exclamation-triangle mr-2"></i>
                    注：不懂伪静态的别开启，否则文章页面会打不开
                </h4>
                <p class="text-xs text-gray-600 mb-2">当前服务器Web软件为：<?php echo $software_type?></p>
                <p class="text-xs text-gray-600 mb-2">请将以下内容添加到伪静态规则</p>
                <pre class="mt-3 p-3 bg-gray-50 border border-gray-200 rounded text-xs overflow-x-auto">
<?php
if($software_type == 'iis'){
	echo '&lt;rule name="payrule1_rewrite" stopProcessing="true">
	&lt;match url="^article-(.[0-9]*).html"/>
	&lt;conditions logicalGrouping="MatchAll">
		&lt;add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
		&lt;add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
	&lt;/conditions>
	&lt;action type="Rewrite" url="article/article.php?id={R:1}"/>
&lt;/rule>
&lt;rule name="payrule2_rewrite" stopProcessing="true">
	&lt;match url="^articlelist-(.[0-9]*).html"/>
	&lt;conditions logicalGrouping="MatchAll">
		&lt;add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
		&lt;add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
	&lt;/conditions>
	&lt;action type="Rewrite" url="article/articlelist.php?id={R:1}"/>
&lt;/rule>
&lt;rule name="payrule3_rewrite" stopProcessing="true">
	&lt;match url="^articlelist.html"/>
	&lt;conditions logicalGrouping="MatchAll">
		&lt;add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
		&lt;add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
	&lt;/conditions>
	&lt;action type="Rewrite" url="article/articlelist.php"/>
&lt;/rule>';
}elseif($software_type == 'nginx'){
echo 'if (!-e $request_filename) {
	rewrite ^/article-(.[0-9]*).html$ /article/article.php?id=$1 last;
	rewrite ^/articlelist-(.[0-9]*).html$ /article/articlelist.php?id=$1 last;
	rewrite ^/articlelist.html$ /article/articlelist.php last;
}';
}else{
	echo '抱歉！您的web服务器软件暂时不支持伪静态设置';
}
?>
</pre>
            </div>
        </div>
    </div>
<?php }else{?>
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="p-4 md:p-6 border-b border-gray-200">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
                <h2 class="text-base md:text-lg font-semibold text-gray-800">文章列表</h2>
                <div class="flex flex-wrap gap-2">
                    <a href="?my=add" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition text-sm">
                        <i class="fas fa-plus mr-2"></i>添加
                    </a>
                    <a href="?my=rewrite" class="px-4 py-2 bg-gray-800 hover:bg-gray-900 text-white font-medium rounded-lg transition text-sm">
                        <i class="fas fa-cog mr-2"></i>伪静态配置
                    </a>
                </div>
            </div>
        </div>
        <div class="p-3 md:p-6">
            <div class="overflow-x-auto">
                <table class="w-full min-w-[700px]">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">ID</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">分类</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">文章标题</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">发布时间</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">浏览量</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">状态</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">操作</th>
                        </tr>
                    </thead>
                    <tbody id="list" class="divide-y divide-gray-200">
                    </tbody>
                </table>
            </div>
            <div class="mt-4 flex items-center justify-between">
                <div class="text-sm text-gray-600">
                    共有 <span id="total" class="font-semibold text-gray-800">0</span> 条
                </div>
                <div class="flex items-center gap-2">
                    <span class="text-sm text-gray-600">现第</span>
                    <select class="px-3 py-2 border border-gray-300 rounded-lg text-sm" id="page">
                        <option value="1">1</option>
                    </select>
                    <span class="text-sm text-gray-600">页</span>
                </div>
            </div>
        </div>
    </div>
<?php }?>
</div>

<?php include 'foot.php'; ?>
<script src="../assets/kindeditor/kindeditor-all-min.js"></script>
<script src="../assets/kindeditor/zh-CN.js"></script>


<script type="text/javascript">
	var cid_arr;
	var pagesize = 30;
	var page = 1;
	$(document).ready(function() {
		get_list(page,pagesize);
		$('#page').change(function(){
			page = $('#page').val();
			get_list(page,pagesize);
		});
	});
	function get_list(page,pagesize){
		showLoading();
		$.ajax({
			type : 'POST',
			data : {pagesize:pagesize,page:page},
			url : 'ajax.php?act=get_article',
			dataType : 'json',
			success : function(data) {
				hideLoading();
				cid_arr = data.class;
				adddata(data.data);
				$('#total').html(data.total);
				if(data.end >= 1){
					$('#page').html('');
					var end = data.end;
					var page = data.page;
					var start=page-10>1?page-10:1;
					var end=page+10<end?page+10:end;
					for(var i = start; i <= page; i++){
					    $('#page').append('<option value="'+ i +'">' + i + '</option>');
					}
					for(var i = page+1; i <= end; i++){
					    $('#page').append('<option value="'+ i +'">' + i + '</option>');
					}
					$('#page').val(page);
				}
			},
			error:function(data){
				hideLoading();
				showToast('服务器错误', 'error');
				return false;
			}
		});
	}
	function adddata(data){
		$("#list").empty();
		$.each(data, function(i,v){
			var tmp = '<tr class="hover:bg-gray-50">\
		            <td class="px-4 py-3 text-sm text-gray-500 whitespace-nowrap">'+v.id+'</td>\
		            <td class="px-4 py-3 text-sm whitespace-nowrap">'+_class(v.cid)+'</td>\
		            <td class="px-4 py-3 text-sm font-medium text-gray-800 whitespace-nowrap">'+v.title+'</td>\
		            <td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">'+v.addtime+'</td>\
		            <td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">'+v.count+'</td>\
		            <td class="px-4 py-3 whitespace-nowrap">'+_active(v.active,v.id)+'</td>\
		            <td class="px-4 py-3 whitespace-nowrap">\
		                <div class="flex items-center gap-2">\
		                <a class="px-3 py-1 text-xs bg-blue-600 text-white rounded hover:bg-blue-700" href="../article/article.php?id='+v.id+'" target="_blank">查看</a>\
		                <a class="px-3 py-1 text-xs bg-gray-800 text-white rounded hover:bg-gray-900" href="?my=edit&id='+v.id+'">编辑</a>\
		                <a class="px-3 py-1 text-xs bg-red-600 text-white rounded hover:bg-red-700" href="?my=delete&id='+v.id+'">删除</a>\
		                </div>\
		            </td>\
		        </tr>';
		    $("#list").append(tmp);
		});
	}
	function _class(cid){
		if(cid != 0){
			return cid_arr[cid];
		}else{
			return '未分类';
		}
	}
	function _active(type,id){
		if(type == 1){
			return '<a href="?my=active&id='+id+'&active=0" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 transition">显示中</a>';
		}else{
			return '<a href="?my=active&id='+id+'&active=1" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 transition">隐藏中</a>';
		}
	}
	function saveSetting(obj){
		showLoading();
		$.ajax({
			type : 'POST',
			url : 'ajax.php?act=set',
			data : $(obj).serialize(),
			dataType : 'json',
			success : function(data) {
				hideLoading();
				showToast(data.msg, 'success');
			},
			error:function(data){
				hideLoading();
				showToast('服务器错误', 'error');
				return false;
			}
		});
	}
	var items = $("select[default]");
	for (i = 0; i < items.length; i++) {
		$(items[i]).val($(items[i]).attr("default")||0);
	}
	KindEditor.ready(function(K) {
		window.editor = K.create('#editor_msg', {
			resizeType : 1,
			allowUpload : false,
			allowPreviewEmoticons : false,
			uploadJson : './ajax.php?act=article_upload',
			items : [
				'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
				'removeformat','formatblock','hr', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
				'insertunorderedlist', '|', 'image', 'link','unlink', 'code', '|','fullscreen','source','preview']
		});
	});
</script>
