<?php
$_POST['cid'] = intval( $_POST['cid'] );
$title = rawurlencode( strip_tags( $_POST['title'] ) );
$content = rawurlencode( strip_tags( $_POST['content'] ) );
$content = str_replace('%EF%BB%BF', '', $content);
$tags = $tagids = array();
$data = @implode( '', file( "http://keyword.discuz.com/related_kw.html?ics=utf-8&ocs=utf-8&title=$title&content=$content" ) );
if ( $data ) {
	$parser = xml_parser_create();
	xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 );
	xml_parser_set_option( $parser, XML_OPTION_SKIP_WHITE, 1 );
	xml_parse_into_struct( $parser, $data, $values, $index );
	xml_parser_free( $parser );

	$kws = array();

	foreach( $values as $valuearray ) {
		if ( $valuearray['tag'] == 'kw' || $valuearray['tag'] == 'ekw' ) {
			$kws[] = trim( $valuearray['value'] );
		} 
	} 

	if ( $kws ) {
		include "../core.php";
		include SAXUE_ROOT_PATH . "/model/tag.php";
		$tag_handler = &saxuetaghandler :: getinstance("saxuetaghandler");
		foreach ( $kws as $kw ) {
			$kw = htmlspecialchars( trim( $kw ) );
			if ( mb_strlen( $kw, 'utf-8' ) > 10 || mb_strlen( $kw, 'utf-8' ) < 2 || false !== strpos( $kw, ',' ) ) {
				continue;
			} 
			$res = $tag_handler -> queryobjects( new criteria( 'tagname', $kw ) );
			$tag = $tag_handler -> getobject( $res );
			if ( !is_object( $tag ) ) {
				$_POST['tagname'] = $kw;
				$tag = $tag_handler -> create();
				if ( !$tag_handler -> insert( $tag ) ) {
					exit( json_encode( array( 'flag' => 0 ) ) );
				} 
			}
			$tags[] = $kw;
			$tagids[] = $tag -> getvar( 'tagid' );
		}
	} 
} 
if ( $tags ) {
	exit( json_encode( array( 'flag' => 1, 'tags' => implode( ',', $tags ), 'tagids' => implode( ',', $tagids ) ) ) );
} else {
	exit( json_encode( array( 'flag' => 0 ) ) );
}