<?php
if ( !defined( "SAXUE_CORE_INCLUDE" ) ) {
		include "../../core.php";
} 
saxue_checkpower( 'artadd' );
$aid = intval( $_REQUEST['aid'] );
$cid = intval( $_REQUEST['cid'] );
saxue_getconfigs( "cate", "article" );
if ( empty( $aid ) && !isset( $saxueCate['article'][$cid] ) ) {
		saxue_jumppage( 'addarticle_cate.php' );
} 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( "文章不存在" );
		} 
		$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_once( SAXUE_ROOT_PATH . "/common/funpost.php" );
if ( isset( $_POST['dosubmit'] ) ) {
		@set_time_limit( 0 );
		include_once( SAXUE_ROOT_PATH . "/common/funarticle.php" );
		// 标题检查
		$check = saxue_checkbadwords( $_POST['title'] );
		if ( $check ) {
				exit( json_encode( array( 'flag' => 0, 'msg' => '文章标题包含非法关键词：' . $check ) ) );
		}
		// 分类检查
		$_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'];
		}
		// 内容检查
		$_POST['ischapter'] = intval( $_POST['ischapter'] );
		if ( !empty( $_POST['pic'] ) && !empty( $_POST['content'] ) ) {
				$_POST['isslide'] = 2;
		} elseif ( !empty( $_POST['pic'] ) ) {
				$_POST['isslide'] = 1;
		} elseif ( !empty( $_POST['content'] ) ) {
				$_POST['isslide'] = 0;
		} else {
				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;
						}
				}
		}
		// 格式化内容
		if ( isset( $_POST['auto_format'] ) ) {
				$_POST['content'] = saxue_setcontent( $_POST['content'] ); 
		} else {
				$_POST['content'] = '<!--Saxue Copy From-->' . str_replace( '<!--Saxue Copy From-->', '', $_POST['content'] );
		}
		// 清除非本站链接
		if ( isset( $_POST['auto_link'] ) ) {
				$_POST['content'] = clear_link( $_POST['content'] );
		} 
		// 处理简介
		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( '<!--Saxue Copy From-->', '{saxue_gallery}', '{saxue_pagebreak}', '{saxue_innerad}', "\r\n", "\r", "\n" ), "", strip_tags( $_POST['content'] ) ) ), 0, $_POST['intro_length'], 'utf-8' );
		} 
		// 下载图片
		$timeline = intval( $_POST['timeline'] );
		if ( isset( $_POST['auto_remote'] ) ) {
				$temp = $_POST['content'] . '{saxue_picbreak}' . $_POST['pic'];
				$temp = save_remote( $temp, $timeline );
				$temp = explode( '{saxue_picbreak}', $temp );
				$_POST['content'] = $temp[0];
				$_POST['pic'] = $temp[1];
		} 
		// 处理标题图片
		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']];
				} 
		} 
		// 图集处理
		$_album = array();
		$_albumnum = 0;
		$_POST['slide'] = array();
		if ( !empty( $_POST['pic'] ) ) {
				$_pics = explode( '|', $_POST['pic'] );
				$_tags = explode( '|', $_POST['pictag'] );
				foreach ( $_pics as $k => $_pic ) {
						if ( empty( $_POST['thumb'] ) ) $_POST['thumb'] = $_pic;
						$_POST['slide'][$k]['url'] = $_pic;
						$_POST['slide'][$k]['tag'] = $_tags[$k];
						$_POST['slide'][$k]['desc'] = strip_tags( trim( $_POST['picdesc' . $k] ) );
						if ( $_albumnum < 6 ) {
								$_album[] = $_pic;
								++$_albumnum;
						}
				} 
		} 
		if ( $_albumnum > 0 ) {
				$_POST['album'] = implode( '|', $_album );
		} else {
				$_POST['album'] = '';
		}
		if ( empty( $_POST['thumb'] ) ) {
				$_POST['isthumb'] = 0;
		} else {
				$_POST['isthumb'] = 1;
		}
		// 其他变量处理
		$_POST['intro'] = saxue_safestr( trim( $_POST['intro'] ) );
		$_POST['title'] = saxue_safestr( trim( $_POST['title'] ) );
		$_POST['ftitle'] = saxue_safestr( trim( $_POST['ftitle'] ) ); 
		$_POST['author'] = saxue_safestr( trim( $_POST['author'] ) );
		$_POST['copyfrom'] = saxue_safestr( trim( $_POST['copyfrom'] ) );
		$_POST['fromurl'] = saxue_safestr( trim( $_POST['fromurl'] ) );
		$_POST['views'] = intval( $_POST['views'] );
		$_POST['tops'] = intval( $_POST['tops'] );
		$_POST['favs'] = intval( $_POST['favs'] );
		$_POST['downs'] = intval( $_POST['downs'] );
		$_POST['status'] = intval( $_POST['status'] );
		// 入库
		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['surl'] = saxue_geturl( 'slide_show', $_POST['aid'], $_POST['cid'], $row['addtime'], $_POST['isslide'] );
				if ( $_POST['ischapter'] || $_POST['isslide'] != 1  ) {
						$_POST['url'] = saxue_geturl( 'article_show', $_POST['aid'], $_POST['cid'], $row['addtime'], $_POST['ischapter'] );
				} else {
						$_POST['url'] = $_POST['surl'];
				}
				$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['surl'] = $_POST['surl'] = saxue_geturl( 'slide_show', $_POST['aid'], $_POST['cid'], $_POST['addtime'], $_POST['isslide'] );
				if ( $_POST['ischapter'] || $_POST['isslide'] != 1  ) {
						$article['url'] = $_POST['url'] = saxue_geturl( 'article_show', $_POST['aid'], $_POST['cid'], $_POST['addtime'], $_POST['ischapter'] );
				} else {
						$article['url'] = $_POST['url'] = $_POST['surl'];
				}
				$data_handler -> updatefields( array( 'url' => $_POST['url'], 'surl' => $_POST['surl'] ), 'aid=' . $_POST['aid'] );
		} 
		// TXT处理
		$txtpath = $saxueConfigs['article']['txtdir'] . saxue_getsubdir( $_POST['aid'] );
		saxue_checkdir( $txtpath, true );
		// 内容TXT保存
		$article['content'] = '';
		if ( !empty( $_POST['content'] ) ) {
				$article['content'] = $_POST['content'];
				saxue_writefile( $txtpath. '/' . $_POST['aid'] . '.txt', $_POST['content'] );
		}
		// 图集Slide.TXT保存
		$article['slide'] = '';
		if ( $_POST['isslide'] ) {
				$article['slide'] = json_encode( $_POST['slide'] );
				saxue_writefile( $txtpath . '/' . $_POST['aid'] . '.slide', $article['slide'] );
		}
		// 扩展属性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_once( SAXUE_ROOT_PATH . "/model/tag.php" );
				$tag_handler = saxuetaghandler :: getinstance( "saxuetaghandler" );
				include_once( 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 );
						}
				}
		}
		// 上下篇
		$_prenext = array();
		if ( $_POST['status'] != $row['status'] ) {
				$_preid = $_nextid = 0;
				if ( $_POST['status'] == 1 ) {
						$_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'];
		}
		// 生成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['ischapter'] && $_POST['status'] == 1 && $row['status'] != 1 ) {
						RepackArticle( $article['aid'], array( 'makechapter' => 1 ), true );
				}
		}
		if ( $_POST['status'] == 1 && $row['status'] != 1 ) {
				// 奖励处理
				include SAXUE_ROOT_PATH . "/model/member_users.php";
				$users_handler = &saxuememberusershandler :: getinstance( "saxuememberusershandler" );
				$score = intval( $_POST['postscore'] ) + intval( $saxueConfigs['article']['postscore'] );
				if ( !empty( $row['uid'] ) && $score > 0 ) {
						if ( $_POST['postscore'] > 0 ) {
								$stype = 101;
						} else {
								$stype = 100;
						}
						$users_handler -> changescore( $row['uid'], $score, $stype, $_POST['aid'] );
				}
				$money = $_POST['postmoney'] + $saxueConfigs['article']['postmoney'];
				if ( !empty( $row['uid'] ) && $money > 0 ) {
						if ( $_POST['postmoney'] > 0 ) {
								$mtype = 101;
						} else {
								$mtype = 100;
						}
						$users_handler -> changemoney( $row['uid'], $money, $mtype, $_POST['aid'] );
				}
				// 动态处理
				if ( !empty( $row['uid'] ) ) {
						$article_handler -> db -> query( 'INSERT INTO ' . saxue_dbprefix( 'member_doing' ) . '(uid, aid, dotime, doing) VALUES (' . $row['uid'] . ', ' . $_POST['aid'] . ', ' . $row['addtime'] . ', 1)' );
				}
				// 百度主动推送
				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'] );
		exit( json_encode( array( 'flag' => 1 ) ) );
} 
$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	
		$txtfile = $saxueConfigs['article']['txtdir'] . saxue_getsubdir( $aid ) . '/' . $aid . '.slide';
		if ( is_file( $txtfile ) ) {
				$row['slide'] = saxue_readfile( $txtfile );
				$row['slide'] = json_decode( $row['slide'], true );
		}
		// 扩展属性	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_once( SAXUE_ADMIN_PATH . "/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_by_ref( "configs", $saxueConfigs['article'] );
$saxueTset['saxue_contents_template'] = SAXUE_WEB_PATH . "/article/templates/addarticle.html";
include_once( SAXUE_ADMIN_PATH . "/footer.php" );
