<?php
include "../core.php";
saxue_checklogin();
$uid = intval( $_REQUEST['uid'] );
$uname = '';
include SAXUE_ROOT_PATH . "/model/member_message.php";
$message_handler = &saxuemembermessagehandler :: getinstance( "saxuemembermessagehandler" );
$sql = 'SELECT * FROM ' . saxue_dbprefix( "member_message" ) . ' WHERE (fromid=' . $_SESSION['saxueUserId'] . ' AND toid=' . $uid . ' AND fromdel=0) OR (fromid=' . $uid . ' AND (toid=0 OR toid=' . $_SESSION['saxueUserId'] . ') AND todel=0) ORDER BY postdate DESC';
$res = $message_handler -> db -> query( $sql );
$k = 0;
$history = false;
$messagerows = array();
$readrows = array();
while ( $v = $message_handler -> getobject( $res ) ) {
		$messagerows[$k] = $v -> getvars( "n" );
		if ( $messagerows[$k]['fromid'] == $_SESSION['saxueUserId'] ) {
				$messagerows[$k]['my'] = 1;
				$messagerows[$k]['history'] = 0;
		} else {
				$messagerows[$k]['my'] = 0;
				if ( !$history && $messagerows[$k]['isread'] && $messagerows[$k]['toid'] == $_SESSION['saxueUserId'] ) {
						$messagerows[$k]['history'] = 1;
						$history = true;
				} else {
						$messagerows[$k]['history'] = 0;
				}
				if ( !$messagerows[$k]['isread'] && $messagerows[$k]['toid'] == $_SESSION['saxueUserId'] ) {
						$readrows[] = $messagerows[$k]['messageid'];
				} 
		}
		if ( $uid && empty( $uname ) ) {
				if ( $messagerows[$k]['fromid'] == $uid ) {
						$uname = $messagerows[$k]['fromname'];
				} else {
						$uname = $messagerows[$k]['toname'];
				}
		}
		++$k;
}
if ( count( $readrows ) > 0 ) {
		$message_handler -> updatefields( 'isread=1', 'messageid IN(' . implode( ',', $readrows ) . ')' );
} 
include SAXUE_WEB_PATH . "/member/header.php";
$saxueTpl -> assign_by_ref( "messagerows", $messagerows );
$saxueTpl -> assign( "uname", $uname );
$saxueTpl -> assign( "uid", $uid );
$saxueTpl -> assign( "uavatar", saxue_geturl( 'user_avatar', $uid ) );
$saxueTpl -> setcaching( 0 );
$saxueTset['saxue_contents_template'] = SAXUE_THEME_PATH . "/member/messagedetail.html";
include SAXUE_WEB_PATH . "/member/footer.php";
