<?
  if ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) {
    define( 'ROOT', 'http://'.$_SERVER['HTTP_HOST'] );
    define( 'ROOT_DIR', $_SERVER['DOCUMENT_ROOT'] );
    session_start();
    header( 'Content-type: text/html; charset=windows-1251' );
    include_once ROOT_DIR . '/engine/config.php';
    include_once ROOT_DIR . '/engine/function.php';
  } else {
    if ( !defined( 'MISOFT' ) ) { exit(); }
  }

  #Проверяем отмечен ли посетитель как "онлайн":
  $get_online = mysql_query( "SELECT id FROM online WHERE ip = '" . real_IP() . "' and phpsession = '" . session_id() . "' LIMIT 1" );

  if ( !mysql_num_rows( $get_online ) ) {
    mysql_query("INSERT INTO online SET ip = '" . real_IP() . "', iduser = '" . ( int ) $_SESSION['iduser'] . "', phpsession = '" . session_id() . "', rsite = '" . mysql_real_escape_string( check_text( $_SERVER['HTTP_REFERER'] ) ) . "', browser = '" . check_text( user_browser( $_SERVER['HTTP_USER_AGENT'] ) ) . "'");
  } else {
    mysql_query( "UPDATE online SET dt = NOW(), iduser = '" . ( int ) $_SESSION['iduser'] . "' WHERE ip = '" . real_IP() . "' and phpsession = '" . session_id() . "', rsite = '" . mysql_real_escape_string( check_text( $_SERVER['HTTP_REFERER'] ) ) . "', '" . check_text( user_browser( $_SERVER['HTTP_USER_AGENT'] ) ) . "'" );
  }

  #Обновляем данные последнего входа
  if ( isset( $_SESSION['iduser'] ) ) {
    mysql_query( "UPDATE user SET logindate = '" . time() . "' WHERE id = '" . ( int ) $_SESSION['iduser'] . "'" );
  }
  
  #Удаляем если пользователь не обновлял страницу более 5 минут
  mysql_query( "DELETE FROM online WHERE dt < NOW() - 300 " );
?>