<?php
# Script by seg0ro http://mobilarts.ru
# Not for sale!!!

defined('_IN_JOHNCMS') or die('Restricted access');

class journal {
  /**
  Функция добавления в таблицу журнала записи
  $toId - id пользователя, кому предназначена запись
  $string - текст записи
  */
  public static function addEntry($toId = 0, $string = ''){
    $check = mysql_result(mysql_query("SELECT COUNT(*) FROM `users` WHERE `id` = '$toId' "), 0);
    if ($check && $string){
      $total = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_journal` "), 0);
      if ($total < 100){
        mysql_query("INSERT INTO `forum_journal` SET `time` = '".time()."', `user_id` = '$toId', `text` = '".mysql_real_escape_string($string)."' ");
      }else{
        $lastEntry = mysql_fetch_assoc(mysql_query("SELECT `time` FROM `forum_journal` WHERE `user_id` = '$toId' ORDER BY `time` ASC LIMIT 1 "));
        mysql_query("UPDATE `forum_journal` SET `time` = '".time()."', `text` = '".mysql_real_escape_string($string)."' WHERE `user_id` = '$toId' AND `time` = '".$lastEntry['time']."' LIMIT 1 ");
      }
    }
  }
  
  /**
  Функция удаления записи из таблицы журнала
  $time = 0 очищает весь журнал пользователя
  $time = n удаляет запись с временной меткой n
  Возвращает true или false
  */
  public static function deleteEntry($time = 0){
    if ($time){
      $check = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_journal` WHERE `time` = '$time' AND `user_id` = '".core::$user_id."' "), 0);
      if ($check)
        mysql_query("DELETE FROM `forum_journal` WHERE `time` = '$time' AND `user_id` = '".core::$user_id."' LIMIT 1 ");
      else
        return false;  
    }else{
      $check = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_journal` WHERE `user_id` = '".core::$user_id."' "), 0);
      if ($check)
        mysql_query("DELETE FROM `forum_journal` WHERE `user_id` = '".core::$user_id."' ");
      else
        return false;
    }
    return true;
  }
  
  /**
  Функция выводит cсылку на журнал с указанием новых записей
  */
  public static function displayNew(){
    $totalNew = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_journal` WHERE `user_id` = '".core::$user_id."' AND `readed` = '0'  "), 0);
    if ($totalNew)
      return ' <span class="badge" title="Новая запись в журнале">'.$totalNew.'</span>';
    else
      return false;  
  }
  
}