<?php
function echo_json( $data, $callback = false ) {
		if ( $callback ) {
				exit( $callback . '(' . $data . ')' );
		}
		exit( $data );
}
if ( !defined( "SAXUE_CORE_INCLUDE" ) ) {
		include "../core.php";
} 
$callback = $_REQUEST['callback'] ? $_REQUEST['callback'] : false;
if ( !saxue_checklogin( true ) ) {
		echo_json( json_encode( array( 'flag' => 0, 'msg' => LANG_NEED_LOGIN ) ), $callback );
}
saxue_loadlang( "message" );
$_REQUEST['toid'] = intval( $_REQUEST['toid'] );
$_REQUEST['toname'] = trim( $_REQUEST['toname'] );
if ( strlen( $_REQUEST['toname'] ) == 0 && !$_REQUEST['toid'] ) {
		echo_json( json_encode( array( 'flag' => 0, 'msg' => $saxueLang['message']['message_need_receiver'] ) ), $callback );
} 
if ( $_REQUEST['toname'] == $_SESSION['saxueUserName'] || $_REQUEST['toid'] == $_SESSION['saxueUserId'] ) {
		echo_json( json_encode( array( 'flag' => 0, 'msg' => $saxueLang['message']['message_nosend_self'] ) ), $callback );
} 
$_REQUEST['content'] = saxue_htmlstr( trim( $_REQUEST['content'] ) );
if ( strlen( $_REQUEST['content'] ) == 0 ) {
		echo_json( json_encode( array( 'flag' => 0, 'msg' => $saxueLang['message']['message_need_content'] ) ), $callback );
} 
include_once SAXUE_ROOT_PATH . "/model/member_users.php";
$users_handler = &saxuememberusershandler :: getinstance( "saxuememberusershandler" );
if ( $_REQUEST['toid'] ) {
		$touser = $users_handler -> get( $_REQUEST['toid'] );
} else {
		$touser = $users_handler -> getbyname( $_REQUEST['toname'] );
}
if ( !$touser ) {
		echo_json( json_encode( array( 'flag' => 0, 'msg' => $saxueLang['message']['message_no_receiver'] ) ), $callback );
} 
$_REQUEST['title'] = saxue_htmlstr( trim( $_REQUEST['title'] ) );
if ( strlen( $_REQUEST['title'] ) == 0 ) {
		$_REQUEST['title'] = mb_substr( strip_tags( $_REQUEST['content'] ), 0, 50, 'utf-8' );
} elseif ( mb_strlen( $_REQUEST['title'] ) > 50 ) {
		$_REQUEST['title'] = mb_substr( strip_tags( $_REQUEST['title'] ), 0, 50, 'utf-8' );
}
include SAXUE_ROOT_PATH . "/model/member_message.php";
$message_handler = &saxuemembermessagehandler :: getinstance( "saxuemembermessagehandler" );
$newMessage = &$message_handler -> create();
$newMessage -> setvar( "title", $_REQUEST['title'] );
$newMessage -> setvar( "content", $_REQUEST['content'] );
$newMessage -> setvar( "postdate", SAXUE_NOW_TIME );
$newMessage -> setvar( "fromid", $_SESSION['saxueUserId'] );
$newMessage -> setvar( "fromname", $_SESSION['saxueUserName'] );
$newMessage -> setvar( "toid", $touser -> getvar( "uid", "n" ) );
$newMessage -> setvar( "toname", $touser -> getvar( "uname", "n" ) );
if ( !$message_handler -> insert( $newMessage ) ) {
		echo_json( json_encode( array( 'flag' => 0, 'msg' => $saxueLang['message']['message_send_failure'] ) ), $callback );
} 
echo_json( json_encode( array( 'flag' => 1 ) ), $callback );
