<?

session_start();

if ( !isset( $_SESSION['id'] ) ) {
    exit();
}
if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) {
    exit();
} else {
    define( 'ROOT', 'http://'.$_SERVER['HTTP_HOST'] );
    define( 'ROOT_DIR', $_SERVER['DOCUMENT_ROOT'] );
    include_once ROOT_DIR . '/engine/config.php';
    include_once ROOT_DIR . '/engine/func.php';

    /*---Проверка данных на SQL иньекции---*/
    if ( $_REQUEST ) {
        foreach ( $_REQUEST as $v ) {
            if ( init_inj( $v ) ) {
                exit();
            }
        }
    }

    $get_messages = mysql_query( "SELECT * FROM php_messages WHERE m_state = 'inbox' and from_id = '" . ( int ) $_POST['id'] . "' and to_id = '" . $_SESSION['id'] . "' and m_type = '0' ORDER BY data DESC" );

    if ( mysql_num_rows( $get_messages ) > 0 ) {

        while ( $row = mysql_fetch_array( $get_messages ) ) {
            $info_from_id = mysql_fetch_array( mysql_query( "SELECT login FROM php_user WHERE id = '" . $row['from_id'] . "' LIMIT 1" ) );
            mysql_query( "UPDATE php_messages SET m_type = 1 WHERE id = '" . $row['id'] . "' and m_state = 'inbox' and m_type = 0" );

            if ( date( 'd.m.Y', $row['data'] ) == date( 'd.m.Y', time() ) ) {
                $data = 'сегодня в ' . date( 'H:i', $row['data'] );
            } else
            if ( date( 'd.m.Y', $row['data'] ) == date( 'd.m.Y', time() - 86400 ) ) {
                $data = 'вчера в ' . date( 'H:i', $row['data'] );
            } else {
                $data = date( 'd.m.Y H:i', $row['data'] );
            }

            $array = array( 'id' => $row['id'], 'login' => iconv( 'windows-1251', 'UTF-8', $info_from_id['login'] ), 'text' => iconv( 'windows-1251', 'UTF-8', $row['text'] ), 'data' => iconv( 'windows-1251', 'UTF-8', $data ) );

            $json['mread'][] = $array;
        }

        if ( count( $json['mread'] ) ) {
            $json['ok'] = 1;
        }
        print json_encode( $json ); //кодируем в json
    } else {

    }
}

?>