<?php
include "../../core.php";
saxue_checklogin();
$aid = intval( $_REQUEST['aid'] );
$cid = intval( $_REQUEST['cid'] );
saxue_getconfigs( "cate", "article" );
if ( empty( $aid ) && !isset( $saxueCate['article'][$cid] ) ) {
		saxue_jumppage( 'contribute_cate.php?menuid=' . $_REQUEST['menuid'] );
} elseif ( $saxueCate['article'][$cid]['child'] ) {
		saxue_printfail( "请选择终极分类" );
}
saxue_getconfigs( "configs", "article" );
saxue_getconfigs( "expand", "article" );
include SAXUE_ROOT_PATH . "/model/article.php";
$article_handler = saxuearticlehandler :: getinstance( "saxuearticlehandler" );
include SAXUE_ROOT_PATH . "/model/article_data.php";
$data_handler = saxuearticledatahandler :: getinstance( "saxuearticledatahandler" );
$row = array();
if ( $aid ) {
		// 文章主表
		$article = $article_handler -> get( $aid );
		if ( !is_object( $article ) ) {
				saxue_printfail( "文章不存在" );
		} 
		if ( $article -> getvar( "status" ) == 1 ) {
				saxue_printfail( "文章已发布，不能编辑" );
		}
		if ( $article -> getvar( "uid" ) != $_SESSION['saxueUserId'] ) {
				saxue_printfail( "你没有权限编辑该文章" );
		} 
		$row = $article -> getvars( 'n' );
		// 文章数据表
		$data_handler -> setdatatable( $row['tbnum'] );
		$data = $data_handler -> get( $aid );
		$row = $row + ( $data -> getvars( 'n' ) );
		$_isnew = false;
} else {
		$row['cid'] = $cid;
		$row['tbnum'] = $saxueConfigs['article']['tbnum'];
		$data_handler -> setdatatable( $row['tbnum'] );
		$_isnew = true;
}
if ( isset( $saxueExpand['cate'][$row['cid']] ) ) {
		$isexpand = 1;
} else {
		$isexpand = 0;
}
include SAXUE_ROOT_PATH . "/common/funpost.php";
if ( isset( $_POST['dosubmit'] ) ) {
		@set_time_limit( 0 );
		@session_write_close();
		// 分类检查
		$_POST['cid'] = intval( $_POST['cid'] );
		if ( $saxueCate['article'][$_POST['cid']]['child'] ) {
				exit( json_encode( array( 'flag' => 0, 'msg' => '请选择子分类' ) ) );
		} 
		if ( $saxueCate['article'][$_POST['cid']]['pid'] ) {
				$_POST['pid'] = $saxueCate['article'][$_POST['cid']]['pid'];
		} else {
				$_POST['pid'] = $_POST['cid'];
		}
		// 标题检查
		if ( strlen( $_POST['title'] ) == 0 ) {
				exit( json_encode( array( 'flag' => 0, 'msg' => '文章标题不能为空' ) ) );
		} 
		$check = saxue_checkbadwords( $_POST['title'] );
		if ( $check ) {
				exit( json_encode( array( 'flag' => 0, 'msg' => '文章标题包含非法关键词：' . $check ) ) );
		}
		// 内容检查
		if ( strlen( $_POST['content'] ) == 0 ) {
				exit( json_encode( array( 'flag' => 0, 'msg' => '文章内容不能为空' ) ) );
		} 
		// 扩展属性检查
		if ( $isexpand ) {
				foreach ( $saxueExpand['cate'][$row['cid']] as $name ) {
						switch ( $saxueExpand['info'][$name]['type'] ) {
								case 8 :
								case 10 :
										if ( $saxueExpand['info'][$name]['required'] && ( !is_array( $_POST['expand'][$name] ) || count( $_POST['expand'][$name] ) == 0 ) ) {
												exit( json_encode( array( 'flag' => 0, 'msg' => $saxueExpand['info'][$name]['title'] . '不能为空' ) ) );
										}
										break;
								default :
										$_POST['expand'][$name] = trim( $_POST['expand'][$name] );
										if ( $saxueExpand['info'][$name]['required'] && strlen( $_POST['expand'][$name] ) == 0 ) {
												exit( json_encode( array( 'flag' => 0, 'msg' => $saxueExpand['info'][$name]['title'] . '不能为空' ) ) );
										}
										break;
						}
				}
		}
		// 格式化内容
		$_POST['content'] = saxue_setcontent( $_POST['content'] ); 
		// 清除非本站链接
		$_POST['content'] = clear_link( $_POST['content'] ); 
		// 下载图片
		$timeline = intval( $_POST['timeline'] );
		$_POST['content'] = save_remote( $_POST['content'], $timeline ); 
		// 处理标题图片
		if ( isset( $_POST['auto_thumb'] ) && empty( $_POST['thumb'] ) ) {
				$_POST['thumb_no'] = intval( $_POST['thumb_no'] ) - 1;
				if ( $_POST['thumb_no'] < 0 ) $_POST['thumb_no'] = 0;
				if ( preg_match_all( "/src=([\"|']?)([^ \"'>]+\.(jpg|jpeg|gif|png|bmp))\\1/i", $_POST['content'], $matches ) && !empty( $matches[2][$_POST['thumb_no']] ) && is_image( $matches[2][$_POST['thumb_no']] ) ) {
						$_POST['thumb'] = $matches[2][$_POST['thumb_no']];
				} 
		} 
		if ( empty( $_POST['thumb'] ) ) {
				$_POST['isthumb'] = 0;
		} else {
				$_POST['isthumb'] = 1;
		}
		// 处理简介
		if ( isset( $_POST['auto_intro'] ) && empty( $_POST['intro'] ) ) {
				if ( empty( $_POST['intro_length'] ) || !is_numeric( $_POST['intro_length'] ) || $_POST['intro_length'] > 200 || $_POST['intro_length'] < 30 ) $_POST['introduce_length'] = 200;
				$_POST['intro'] = mb_substr( trim( str_replace( array( "/r/n", "/r", "/n" ), "", strip_tags( $_POST['content'] ) ) ), 0, $_POST['intro_length'], 'utf-8' );
		} 
		// 其他变量处理
		$_POST['intro'] = saxue_safestr( trim( $_POST['intro'] ) );
		$_POST['title'] = saxue_safestr( trim( $_POST['title'] ) ); 
		$_POST['author'] = saxue_safestr( trim( $_POST['author'] ) );
		$_POST['copyfrom'] = saxue_safestr( trim( $_POST['copyfrom'] ) );
		$_POST['fromurl'] = saxue_safestr( trim( $_POST['fromurl'] ) );
		$_POST['status'] = $saxueConfigs['article']['pending'];
		$_POST['uid'] = $_SESSION['saxueUserId'];
		$_POST['uname'] = $_SESSION['saxueUserName'];
		$_POST['ischapter'] = 0;
		// 入库
		if ( $_isnew ) {
				$_POST['addtime'] = SAXUE_NOW_TIME;
				$_POST['tbnum'] = intval( $saxueConfigs['article']['tbnum'] );
				$newarticle = $article_handler -> create();
		} else {
				$newarticle = $article_handler -> create( false );
		} 
		if ( !$article_handler -> insert( $newarticle ) ) {
				exit( json_encode( array( 'flag' => 0, 'msg' => '文章主表保存失败' ) ) );
		} 
		if ( $_isnew ) {
				$_POST['aid'] = $newarticle -> getvar( 'aid' );
				$newdata = $data_handler -> create();
		} else {
				$_POST['url'] = saxue_geturl( 'article_show', $_POST['aid'], $_POST['cid'], $row['addtime'], $_POST['ischapter'] );
				$newdata = $data_handler -> create( false );
		} 
		if ( !$data_handler -> insert( $newdata ) ) {
				if ( $_isnew ) {
						$article_handler -> delete( $_POST['aid'] );
				}
				exit( json_encode( array( 'flag' => 0, 'msg' => '文章数据表保存失败' ) ) );
		} 
		$article = ( $newarticle -> getvars( 'n' ) ) + ( $newdata -> getvars( 'n' ) );
		// Attachs处理
		if ( !empty( $timeline ) ) {
				include_once SAXUE_ROOT_PATH . "/model/attachs.php";
				$attachs_handler = saxueattachshandler :: getinstance( "saxueattachshandler" );
				$attachs_handler -> updateattachs( $_POST['aid'], $timeline );
		}
		// URL处理
		if ( $_isnew ) {
				$article['url'] = $_POST['url'] = saxue_geturl( 'article_show', $_POST['aid'], $_POST['cid'], $_POST['addtime'], $_POST['ischapter'] );
				$data_handler -> updatefields( array( 'url' => $_POST['url'] ), 'aid=' . $_POST['aid'] );
		} 
		// TXT处理
		$txtpath = $saxueConfigs['article']['txtdir'] . saxue_getsubdir( $_POST['aid'] );
		saxue_checkdir( $txtpath, true );
		// 内容TXT保存
		saxue_writefile( $txtpath. '/' . $_POST['aid'] . '.txt', $_POST['content'] );
		$article['content'] = $_POST['content'];
		// 扩展属性Expand.TXT保存
		$article['expand'] = array();
		if ( $isexpand ) {
				$article['expand'] = $_POST['expand'];
				saxue_writefile( $txtpath . '/' . $_POST['aid'] . '.expand', json_encode( $_POST['expand'] ) );
		}
		// TAG处理
		if ( $_POST['tagids'] != $row['tagids'] ) {
				include SAXUE_ROOT_PATH . "/model/tag.php";
				$tag_handler = saxuetaghandler :: getinstance( "saxuetaghandler" );
				include SAXUE_ROOT_PATH . "/model/tag_article.php";
				$tagarticle_handler = saxuetagarticlehandler :: getinstance( "saxuetagarticlehandler" );
				$_tagids = explode( ',', trim( $_POST['tagids'], ',' ) );
				$_oldtagids = array();
				if ( !empty( $row['tagids'] ) ) {
						$_oldtagids = explode( ',', trim( $row['tagids'], ',' ) );
				} 
				// 新增TAG文章入库
				$_addids = array_diff( $_tagids, $_oldtagids );
				if ( count( $_addids ) > 0 ) {
						foreach ( $_addids as $tagid ) {
								$_POST['tagid'] = $tagid;
								$newtag = $tagarticle_handler -> create();
								if ( $tagarticle_handler -> insert( $newtag ) ) {
										$tag_handler -> updatefields( 'counts=counts+1', 'tagid=' . $tagid );
								}
						}
				}
				// 删除旧的TAG文章
				$_delids = array_diff( $_oldtagids, $_tagids );
				if ( count( $_delids ) > 0 ) {
						foreach ( $_delids as $tagid ) {
								$tagarticle_handler -> db -> query( "DELETE FROM " . saxue_dbprefix( "tag_article" ) . " WHERE tagid=" . $tagid . " AND aid=" .$_POST['aid'] );
								$tag_handler -> updatefields( 'counts=counts-1', 'tagid=' . $tagid );
						}
				}
		}
		// 上下篇
		if ( $_POST['status'] == 1 ) {
				$_prenext = array();
				$_preid = $_nextid = 0;
				$_res = $article_handler -> db -> query( "SELECT aid FROM " . saxue_dbprefix( "article" ) . " WHERE aid<" . $_POST['aid'] . " AND status=1 AND tbnum=" . $row['tbnum'] . " ORDER BY aid DESC LIMIT 1" );
				$_row = $article_handler -> db -> fetcharray( $_res ); 
				$_preid = intval( $_row['aid'] );
				if ( !$_isnew ) {
						$_res = $article_handler -> db -> query( "SELECT aid FROM " . saxue_dbprefix( "article" ) . " WHERE aid>" . $_POST['aid'] . " AND status=1 AND tbnum=" . $row['tbnum'] . " ORDER BY aid ASC LIMIT 1" );
						$_row = $article_handler -> db -> fetcharray( $_res ); 
						$_nextid = intval( $_row['aid'] );
				}
				if ( $_preid != $row['preid'] || $_nextid != $row['nextid'] ) {
						$data_handler -> updatefields( array( 'preid' => $_preid, 'nextid' => $_nextid ), 'aid=' . $_POST['aid'] );
						if ( $_preid != $row['preid'] ) {
								$_prenext[] = $_preid;
								$_prenext[] = $row['preid'];
						}
						if ( $_nextid != $row['nextid'] ) {
								$_prenext[] = $_nextid;
								$_prenext[] = $row['nextid'];
						}
						$article['preid'] = $_preid;
						$article['nextid'] = $_nextid;
				}
		}
		if ( $_POST['url'] != $row['url'] ) {
				$_prenext[] = $row['preid'];
				$_prenext[] = $row['nextid'];
		}
		include SAXUE_ROOT_PATH . "/common/funarticle.php";
		// 生成HTML
		if ( $_POST['status'] == 1 && $saxueConfigs['article']['url_detail'] > 2 ) {
				if ( $_isnew ) {
						$packarticle = new saxuepackarticle( $article );
				} else {
						$packarticle = new saxuepackarticle( $article['aid'] );
				}
				$packarticle -> makearticle();
		}
		if ( $_POST['status'] == 1 ) {
				// 动态处理
				$sql = 'INSERT INTO ' . saxue_dbprefix( 'member_doing' ) . '(uid, aid, dotime, doing) VALUES (' . $_SESSION['saxueUserId'] . ', ' . $_POST['aid'] . ', ' . SAXUE_NOW_TIME . ', 1)';
				$article_handler -> db -> query( $sql );
				// 奖励处理
				include SAXUE_ROOT_PATH . "/model/member_users.php";
				$users_handler = &saxuememberusershandler :: getinstance( "saxuememberusershandler" );
				$score = intval( $saxueConfigs['article']['postscore'] );
				if ( $score > 0 ) {
						$users_handler -> changescore( $row['uid'], $score, 101, $_POST['aid'] );
				}
				$money = $saxueConfigs['article']['postmoney'];
				if ( $money > 0 ) {
						$users_handler -> changemoney( $row['uid'], $money, 101, $_POST['aid'] );
				}
				// 百度主动推送
				if ( $saxueConfigs['article']['baidupush'] == 1 ) {
						$urls = array();
						$urls[] = SAXUE_URL . $_POST['url'];
						if ( SAXUE_MOBILE_OPEN == 1 ) $urls[] = SAXUE_MURL . $_POST['url'];
						BaiduPush( $urls );
				}
		}
		$_prenext = array_unique( $_prenext );
		PreNextArticle( $_prenext, $row['tbnum'] );
		$flag = $_POST['status'] + 1;
		exit( json_encode( array( 'flag' => $flag ) ) );
} 
$expand = array();
if ( !$_isnew ) {
		// 内容	TXT	
		$txtfile = $saxueConfigs['article']['txtdir'] . saxue_getsubdir( $aid ) . '/' . $aid . '.txt';
		if ( is_file( $txtfile ) ) {
				$row['content'] = saxue_readfile( $txtfile );
				$row['content'] = str_replace( array( "{saxue_innerad}\r\n", '{saxue_innerad}' ), '', $row['content'] );
		}
		// 扩展属性	TXT	
		if ( $isexpand ) {
				$txtfile = $saxueConfigs['article']['txtdir'] . saxue_getsubdir( $aid ) . '/' . $aid . '.expand';
				if ( is_file( $txtfile ) ) {
						$_expand = saxue_readfile( $txtfile );
						$_expand = json_decode( $_expand, true );
						if ( is_array( $_expand ) && count( $_expand ) > 0 ) {
								foreach ( $_expand as $name => $val ) {
										switch ( $saxueExpand['info'][$name]['type'] ) {
												case 8 :
														foreach ( $val as $v ) {
																$expand[$name][$v]['selected'] = 'selected';
														}
														break;
												case 10 :
														foreach ( $val as $v ) {
																$expand[$name][$v]['checked'] = 'checked';
														}
														break;
												default :
														$expand[$name] = $val;
														break;
										}
								}
						}
				}
		}
}
// 父分类定位
$catepos = array();
$pid = $saxueCate['article'][$row['cid']]['pid'];
if ( $pid ) {
		$catepos[] = $saxueCate['article'][$pid];
}
$catepos[] = $saxueCate['article'][$row['cid']];
include SAXUE_WEB_PATH . "/member/header.php";
$saxueTpl -> assign( "isexpand", $isexpand );
$saxueTpl -> assign_by_ref( "row", $row );
$saxueTpl -> assign_by_ref( "catepos", $catepos );
$saxueTpl -> assign_by_ref( "expand", $expand );
$saxueTpl -> assign( "allowpost", $saxueConfigs['article']['allowpost'] );
$saxueTset['saxue_contents_template'] = SAXUE_THEME_PATH . "/article/member/contribute.html";
include SAXUE_WEB_PATH . "/member/footer.php";
