<?php
function saxue_getcolor( $name, $value = '' ) {
		global $saxue_color_style;
		$color = $html = '';
		if ( preg_match( "/^#[0-9a-zA-Z]{6}$/", $value ) ) $color = $value;
		if ( !$saxue_color_style ) {
				$saxue_color_style = 1;
				$html .= '<script type="text/javascript" src="' . SAXUE_SKIN_SERVER . '/color/color.js"></script>';
		} else {
				++$saxue_color_style;
		} 
		$html .= '<input type="hidden" name="' . $name . '" id="color_input_' . $saxue_color_style . '" value="' . $color . '"/><img src="' . SAXUE_SKIN_SERVER . '/color/color.gif" width="21" height="18" align="absmiddle" id="color_img_' . $saxue_color_style . '" style="cursor:pointer;background:' . $color . '" onclick="color_show(' . $saxue_color_style . ', $(\'#color_input_' . $saxue_color_style . '\').val(), this);"/>';
		return $html;
} 
function saxue_geteditor( $name = '', $width = '580', $height = '400', $tool = 'ubb', $timeline = 0, $allowFileManager = true, $forbidUpload = array(), $min = true ) {
		if ( empty( $name ) ) return;
		if ( $min && !defined( "SAXUE_EDITOR" ) ) {
				$editor = '<script charset="utf-8" src="' . SAXUE_SKIN_SERVER . '/editor/kindeditor-min.js"></script>';
				define( "SAXUE_EDITOR", 1 );
		} elseif ( !defined( "SAXUE_EDITOR" ) ) {
				$editor = '<script charset="utf-8" src="' . SAXUE_SKIN_SERVER . '/editor/kindeditor.js"></script>';
				define( "SAXUE_EDITOR", 1 );
		} 
		$tmp = '
					width : \'' . $width . 'px\',
					minWidth : \'' . $width . '\',
					height : \'' . $height . 'px\',
					minHeight : \'' . $height . '\',
					galleryManagerJson : \'' . SAXUE_URL . '/article/admin/changegallery.php\',
					//newlineTag : \'br\',';
		if ( !in_array( $tool, array( 'no', 'ubb' ) ) ) {
				$tmp .= '
					urlType : \'domain\',
					uploadJson : \'' . SAXUE_URL . '/api/upload_json.php?timeline=' . $timeline . '\',';
		} 
		if ( $allowFileManager && ( !empty( $_SESSION['saxueUserId'] ) || !empty( $_SESSION['saxueAdminId'] ) ) ) {
				$tmp .= '
					fileManagerJson : \'' . SAXUE_URL . '/api/file_manager_json.php\',
					extraFileUploadParams : {PHPSESSID : \'' . session_id() . '\'},
					allowFileManager : true,';
		} 
		if ( is_array( $forbidUpload ) && count( $forbidUpload ) > 0 ) {
				foreach( $forbidUpload as $v ) {
						$v = ucfirst( strtolower( trim( $v ) ) );
						if ( in_array( $v, array( 'Image', 'Flash', 'Media', 'File' ) ) ) {
								$tmp .= '
					allow' . $v . 'Upload : false,';
						} 
				} 
		} 
		$tmp .= '
					items : ' . saxue_gettools( $tool );
		$tmp .= ',
					afterBlur: function(){this.sync();}';
		if ( !is_array( $name ) ) {
				$editor .= '
				<script>
				var o_' . $name . ' = {' . $tmp . ' 
				};
				var e_' . $name . ';
				KindEditor.ready(function(K) {
					e_' . $name . ' = K.create(\'textarea[name="' . $name . '"]\', o_' . $name . ');
				});
				</script>';
		} else {
				$editor .= '
				<script>
				var options = {
					' . $tmp . ' 
				};
				var e_' . $name . ';
				KindEditor.ready(function(K) {';
				foreach( $name as $v ) {
						$v = trim( $v );
						if ( !empty( $v ) ) {
								$editor .= '
							e_' . $v . ' = K.create(\'textarea[name="' . $v . '"]\', options);';
						} 
				} 
				$editor .= '
				});
				</script>';
		} 
		return $editor;
} 

function saxue_gettools( $tool = 'user' ) {
		if ( !empty( $_SESSION['saxueAdminId'] ) ) $items = '[\'source\', \'|\', ';
		else $items = '[';
		switch ( $tool ) {
				case "no" :
						$items .= '\'undo\', \'redo\', \'clearhtml\']';
						break;
				case "pic" :
						$items .= '\'image\', \'|\', \'undo\', \'redo\', \'clearhtml\']';
						break;
				case "ubb" :
						$items .= '\'fontsize\', \'forecolor\', \'hilitecolor\', \'bold\', \'underline\', \'justifyleft\', \'justifycenter\', \'justifyright\', \'|\', \'undo\', \'redo\', \'clearhtml\']';
						break;
				case "ubbpic" :
						$items .= '\'fontsize\', \'forecolor\', \'hilitecolor\', \'bold\', \'underline\', \'justifyleft\', \'justifycenter\', \'justifyright\', \'image\', \'|\', \'undo\', \'redo\', \'clearhtml\']';
						break;
				case "basic" :
						$items .= '\'bold\', \'forecolor\', \'removeformat\', \'|\', \'justifyleft\', \'justifycenter\', \'justifyright\', \'|\', \'link\', \'unlink\', \'emoticons\', \'image\']';
						break;
				case "user" :
						$items .= '\'undo\', \'redo\', \'|\', \'preview\', \'code\', \'cut\', \'copy\', \'paste\',
								\'plainpaste\', \'wordpaste\', \'|\', \'justifyleft\', \'justifycenter\', \'justifyright\', \'clearhtml\', \'selectall\', \'|\', \'image\', \'fullscreen\']';
						break;
				case "simple" :
						$items .= '\'fontname\', \'fontsize\', \'|\', \'forecolor\', \'hilitecolor\', \'bold\', \'italic\', \'underline\',
						\'removeformat\', \'|\', \'justifyleft\', \'justifycenter\', \'justifyright\', \'insertorderedlist\',
						\'insertunorderedlist\', \'|\', \'link\', \'unlink\', \'emoticons\', \'image\']';
						break;
				default:
						$items .= '\'undo\', \'redo\', \'|\', \'preview\', \'print\', \'template\', \'code\', \'cut\', \'copy\', \'paste\',
								\'plainpaste\', \'wordpaste\', \'|\', \'justifyleft\', \'justifycenter\', \'justifyright\',
								\'justifyfull\', \'insertorderedlist\', \'insertunorderedlist\', \'indent\', \'outdent\', \'subscript\',
								\'superscript\', \'clearhtml\', \'quickformat\', \'selectall\', \'|\', \'fullscreen\', \'/\',
								\'formatblock\', \'fontname\', \'fontsize\', \'|\', \'forecolor\', \'hilitecolor\', \'bold\',
								\'italic\', \'underline\', \'strikethrough\', \'lineheight\', \'removeformat\', \'|\', \'image\', \'multiimage\',
								\'flash\', \'media\', \'insertfile\', \'table\', \'hr\', \'emoticons\', \'baidumap\',
								\'anchor\', \'link\', \'unlink\', \'|\', \'pagebreak\', \'gallery\']';
		} 
		return $items;
} 

function saxue_checkbadwords( $title ) {
		global $saxueConfigs;
		if ( !empty( $saxueConfigs['article']['badwords'] ) && preg_match( '/(' . $saxueConfigs['article']['badwords'] . ')/i', $title, $matches ) ) {
				return $matches[0];
		} 
		return false;
}

function saxue_safecontent( $content = '' ) {
		$content = trim( $content );
		return strip_tags( $content, "<div><p><a><br><img><u><span><strong>" );
}

function saxue_setcontent( $content = '' ) {
		$content = trim( $content );
		if ( empty( $content ) ) return $content; 
		$pagecontents = explode( '{saxue_pagebreak}', $content );
		$contary = array();
		foreach ( $pagecontents as $cont ) {
				$content = '';
				if ( preg_match( "~<pre[^>]*>.*?</pre>|<object[^>]*>.*?</object>|<center[^>]*>.*?</center>~is", $cont ) ) {
						$cont = preg_replace( array( "~(<pre[^>]*>|<object[^>]*>|<center[^>]*>)~i", "~(</pre>|</object>|</center>)~i" ), array( "♂$1", "$1♂" ), $cont ); 
						$conts = explode( '♂', $cont );
						$strlines = floor( count( $conts ) / 2 );
						$hazad = false;
						foreach ( $conts as $line => $str ) {
								if ( preg_match( "~<pre[^>]*>|</pre>|<object[^>]*>|</object>|<center[^>]*>|</center>~i", $str ) ) {
										$content .= $str . "\r\n";
								} elseif ( !$hazad && $line >= $strlines ) {
										$content .= saxue_formatcontent( $str, true );
								} else {
										$content .= saxue_formatcontent( $str );
								}
						}
				} else {
						$content = saxue_formatcontent( $cont, true );
				}
				$contary[] = $content;
		}
		return implode( '{saxue_pagebreak}', $contary );
}

function saxue_formatcontent( $content = '', $inad = false ) {
		$content = trim( $content );
		if ( empty( $content ) ) return $content; 
		// 清除多余回车换行
		$content = preg_replace( "~<p[^>]*>\s*<br[^>]*>\s*</p>~i", '', $content ); 
		$content = preg_replace( array( "~(<(p|a|strong|h\d)[^>]*>)(\s+|\n|\r|\t)~", "~(\s+|\n|\r|\t)</~" ), array( "$1", "</" ), $content );
		// 清除JS和空格
		$content = preg_replace( array( "~<script[^>]*>.*?</script>~is", "~&nbsp;~is" ), array( "", "" ), $content ); 
		$content = str_replace( array( chr( 13 ), "\r", "\t", '  ', '　' ), array( '', '', ' ', ' ', ' ' ), $content );
		// 清除HTML
		$content = strip_tags( $content, '<img><embed><br><p><a><strong><h1><h2><h3><h4><h5><h6>' ); 
		// 格式化内容
		$content = str_replace( array( '</p>', '</P>'), array( "", "" ), $content );
		$content = preg_replace( "~(<br[^>]*>)+~i", "\n", $content );
		$content = preg_replace( "~(<p[^>]*>)+~i", "\n", $content );
		$contents = explode( "\n", $content );
		$strlines = ceil( count( $contents ) / 2 );
		$hazad = false;
		$content = '';
		foreach ( $contents as $line => $str ) {
				$str = trim( $str );
				if ( $str != '' ) {
						if ( $inad && !$hazad && $line > $strlines ) {
								$content .= "{saxue_innerad}\r\n";
								$hazad = true;
						}
						$content .= '<p>' . $str . "</p>\r\n";
				}
		}
		$content = preg_replace( "~<p>(\{saxue_gallery[_\d]*\})</p>~i", "$1", $content );
		return $content;
}

function clear_link( $content ) {
		return preg_replace_callback( "/<a[^>]*>(.*?)<\/a>/is", "_clear_link", $content );
} 

function _clear_link( $matchs ) {
		if ( strpos( $matchs[0], SAXUE_COOKIE_DOMAIN ) !== false || strpos( $matchs[0], '://' ) === false ) return $matchs[0];
		return $matchs[1];
} 

function save_remote( $content, $timeline = 0, $ext = 'jpg|jpeg|gif|png|bmp' ) {
		if ( !$content ) return $content; 
		if ( !preg_match_all( "/src=([\"|']?)([^ \"'>]+\.($ext)[^ \"'>]*)\\1/i", $content, $matches ) ) return $content;
		// 文件保存目录
		$save_path = saxue_uploadpath();
		// 文件保存目录URL
		$save_url = saxue_uploadurl();
		// FTP保存目录
		if ( SAXUE_ATTACHS_PATH != '' && strpos( SAXUE_ATTACHS_PATH, "\\" ) === false && SAXUE_ATTACHS_FTPURL != '' ) {
				if ( substr( SAXUE_ATTACHS_PATH, 0, 1 ) === '/' ) {
						$ftp_path = SAXUE_ATTACHS_FTPURL . SAXUE_ATTACHS_PATH;
				} else {
						$ftp_path = SAXUE_ATTACHS_FTPURL . '/' . SAXUE_ATTACHS_PATH;
				}
		} else {
				$ftp_path = '';
		}
		// 文件路径和URL
		$_filepath = 'image';
		$_fileurl = '';
		// 用户文件夹
		$uid = intval( $_SESSION['saxueUserId'] );
		if ( !empty( $uid ) ) {
				$_filepath .= '/' . floor( intval( $uid ) / 1000 ) . '/' . $uid;
		}
		// 日期文件夹
		$_filepath .= '/' . date( "ym" );
		// 创建文件夹
		saxue_checkdir( $save_path . '/' . $_filepath, true );

		// 附件插入数据库
		$indata = false;
		if ( !empty( $timeline ) ) {
				include_once SAXUE_ROOT_PATH . "/model/attachs.php";
				$attachs_handler = saxueattachshandler :: getinstance( "saxueattachshandler" );
				$indata = true;
		}
		// 开启OSS
		if ( OSS_OPEN ) {
				include_once SAXUE_ROOT_PATH . '/aliyun/oss_php52/sdk.class.php';
		}
		$urls = $oldurls = $newurls = array();
		foreach( $matches[2] as $url ) {
				// 已下载图片、图片URL错误、本站图片则忽略
				if ( in_array( $url, $urls ) || strpos( $url, '://' ) === false || ( OSS_URL != '' && ( stripos( $url, OSS_URL ) !== false ) ) || ( SAXUE_COOKIE_DOMAIN != '' && ( stripos( $url, SAXUE_COOKIE_DOMAIN ) !== false ) ) ) continue;
				$urls[] = $url;
				$imgurl = check_imgurl( $url );
				$file_ext = file_ext( $imgurl );
				$filepath = $_filepath . '/' . date( "dHis" ) . mt_rand( 10000, 99999 ) . '.' . $file_ext;
				if ( file_remote_copy( $imgurl, $save_path . '/' . $filepath ) ) {
						// 保存到远程服务器
						$_fileurl = $save_url . '/' . $filepath;
						$_filein = $save_path . '/' . $filepath;
						$_savein = 'local';
						if ( OSS_OPEN ) {
								// 保存文件到OSS
								$ret = saxue_oss_upload( $filepath, $save_path . '/' . $filepath );
								if ( $ret['flag'] ) {
										$_fileurl = OSS_URL . '/' . $filepath;
										$_filein = $filepath;
										$_savein = 'oss';
										saxue_delfile( $save_path . '/' . $filepath );
								} else {
										error_log( date( 'H:i:s' ) . '| save_remote: ' . $ret['msg'] . "\r\n\r\n", 3, SAXUE_ROOT_PATH . '/aliyun/oss_php52/logs/' . date( 'Ymd' ) . '.txt' );
								} 
						} elseif ( SAXUE_ATTACHS_FTP && !empty( $ftp_path ) ) {
								// 开启FTP上传
								$ret = saxue_copyfile( $save_path . '/' . $filepath, $ftp_path . '/' . $filepath, 644, true );
								if ( $ret && $indata ) {
										$_savein = 'ftp';
										$_filein = $ftp_path . '/' . $filepath;
								}
						} 
						// 附件插入数据库
						if ( $indata ) {
								$attachs = $attachs_handler -> create();
								$attachs -> setvar( 'attachid', 0 );
								$attachs -> setvar( 'aid', 0 );
								$attachs -> setvar( 'timeline', $timeline );
								$attachs -> setvar( 'savein', $_savein );
								$attachs -> setvar( 'filepath', str_replace( '\\', '/', $_filein ) );
								$attachs -> setvar( 'fileurl', $_fileurl );
								$attachs_handler -> insert( $attachs );
						}
						// 结果加入替换数组
						$oldurls[] = $url;
						$newurls[] = $_fileurl;
				} 
		} 
		unset( $matches );
		if ( count( $oldurls ) > 0 ) {
				$content = str_replace( $oldurls, $newurls, $content );
		}
		return $content;
} 

function check_imgurl( $url, $ext = 'jpg|jpeg|gif|png|bmp' ) {
		// 针对使用动态缓存图片URL的提取真实图片地址
		if ( !preg_match( "/src=([\"|']?)([^ \"'>]+\.($ext))\\1/i", $url, $match ) ) return $url;
		if ( strpos( $match[2], '://' ) !== false ) return $match[2];
		$rs = parse_url( $url );
		return $rs["scheme"] . '://' . $rs["host"] . $match[2];
} 

function file_remote_copy( $from, $to ) {
		file_curlDownload( $from, $to );
		if ( is_file( $to ) ) {
				@chmod( $to, 0644 );
				return true;
		} else {
				return false;
		} 
} 

function file_ext( $filename ) {
		return strtolower( trim( substr( strrchr( $filename, '.' ), 1 ) ) );
} 

function file_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 );
} 

function is_image( $file ) {
		return preg_match( "/^(jpg|jpeg|gif|png|bmp)$/i", file_ext( $file ) );
} 

function saxue_safestr( $_str ) {
		$_str = str_replace( '%20', '', $_str );
		$_str = str_replace( '%27', '', $_str );
		$_str = str_replace( '%2527', '', $_str );
		$_str = str_replace( ';', '；', $_str );
		$_str = str_replace( '\\', '', $_str );
		$_str = htmlspecialchars( $_str, ENT_QUOTES );
		$_str = preg_replace( "/&amp;#(\\d+);/isU", "&#\\1;", $_str );
		return $_str;
} 

function saxue_filepath( $_path, $_root_path = "" ) {
		if ( strpos( $_path, "/" ) === false && strpos( $_path, "\\" ) === false ) {
				if ( $_root_path == "" ) {
						$_root_path = SAXUE_WEB_PATH;
				} 
				if ( $_path == "" ) {
						return $_root_path;
				} 
				return $_root_path . "/" . $_path;
		} else if ( substr( $_path, 0, 1 ) === '/' ) {
				return SAXUE_WEB_PATH . $_path;
		} 
		return $_path;
} 

function saxue_fileurl( $_path, $_url = "", $_root_url = "" ) {
		if ( !empty( $_url ) ) {
				return $_url;
		} 
		if ( $_path == "" ) {
				return $_root_url;
		} else if ( substr( $_path, 0, 1 ) === '/' ) {
				return $_root_url . $_path;
		} 
		return $_root_url . "/" . $_path;
}