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

defined('_IN_JOHNCMS') or die('Error: restricted access');

$textl .= ' | Чистка форума';
require_once('../incfiles/head.php');

if ($rights < 9){
  echo functions::display_error('У вас недостаточно прав для просмотра этой страницы!<br /><a href="index.php">Форум</a>');
  require_once('../incfiles/end.php');
  exit;
}

if (isset($_GET['files'])){
  $tree = array('<a href="index.php">Форум</a>', 'Удаление временных файлов');
  echo '<div class="phdr">'.functions::display_menu($tree).'</div>';

  if (isset($_GET['yes'])){
    $total = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_files` WHERE `tempid` > 0 AND `time` < '".(time() - 86400)."' "), 0);
    
    if ($total){
      $req = mysql_query("SELECT * FROM `forum_files` WHERE `tempid` > 0 AND `time` < '".(time() - 86400)."' ");
      while ($res = mysql_fetch_array($req)){
        unlink('../files/forum/'.$res['filename']);
      }

      mysql_query("DELETE FROM `forum_files` WHERE `tempid` > 0 AND `time` < '".(time() - 86400)."' ");
    }

    header ('Refresh:3; URL=index.php');
    echo '<div class="gmenu">Очищено (Удалено '.$total.' файлов)<br /><a href="index.php">Далее</a></div>';
  }else{
    $total = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_files` WHERE `tempid` > 0 "), 0);
    if ($start >= $total){
      // Исправляем запрос на несуществующую страницу
      $start = max(0, $total - (($total % $kmess) == 0 ? $kmess : ($total % $kmess)));
    }

    if ($total){
      if ($total > $kmess)
        echo '<div class="topmenu">'.functions::display_pagination('index.php?act=clean&amp;files&amp;', $start, $total, $kmess).'</div>';
        
      $req = mysql_query("SELECT `forum_files`.*, `forum_files`.`user_id` AS `id`, `users`.`sex`, `users`.`name`, `users`.`rights`, `users`.`lastdate`, `users`.`datereg` FROM `forum_files` LEFT JOIN `users` ON `forum_files`.`user_id` = `users`.`id` WHERE `forum_files`.`tempid` > '0' $sql ORDER BY `forum_files`.`time` DESC LIMIT $start, $kmess ");
      while ($res = mysql_fetch_array($req)){
        echo $i % 2 ? '<div class="list2">' : '<div class="list1">';
        
        $header = '<span class="gray">'.functions::display_date($res['time']).'</span>';
        $text = ($res['time'] > (time() - (3 * 24 * 3600)) ? '<span class="red">новый</span> ' : '').show_file($res);
        $array = array('header' => $header, 'body' => $text, 'sub' => '');
        core::$user_set['avatar'] = 0;
        echo functions::display_user($res, $array);
        echo '</div>';
        ++$i;
      }
      echo '<div class="phdr">Файлов: '.$total.'</div>';
      if ($total > $kmess)
        echo '<div class="topmenu">'.functions::display_pagination('index.php?act=clean&amp;files&amp;', $start, $total, $kmess).'</div>';
      
      echo '<div class="rmenu"><a href="index.php?act=clean&amp;files&amp;yes">Очистить</a></div>'; 
    }else{
      echo '<div class="list1">Пусто</div>';
    }

  }  
}elseif (isset($_GET['logs'])){
  $tree = array('<a href="index.php">Форум</a>', 'Логи форума');
  echo '<div class="phdr">'.functions::display_menu($tree).'</div>';
  
  if (isset($_GET['yes'])){
    mysql_query("TRUNCATE `forum_logs` ");
    
    header ('Refresh:3; URL=index.php');
    echo '<div class="gmenu">Логи очищены<br /><a href="index.php">Далее</a></div>';
    require_once('../incfiles/end.php');
    exit;
  }
  
  $total = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_logs` "), 0);
  if ($start >= $total){
    // Исправляем запрос на несуществующую страницу
    $start = max(0, $total - (($total % $kmess) == 0 ? $kmess : ($total % $kmess)));
  }
  
  if ($total){
    $query = mysql_query("SELECT `forum_logs`.*,  `forum_logs`.`user_id` AS `id`, `users`.`sex`, `users`.`name`, `users`.`rights`, `users`.`lastdate`, `users`.`datereg` FROM `forum_logs` LEFT JOIN `users` ON `forum_logs`.`user_id` = `users`.`id` ORDER BY `forum_logs`.`time` DESC LIMIT $start, $kmess ");
    while ($res = mysql_fetch_assoc($query)){
      echo $i % 2 ? '<div class="list2">' : '<div class="list1">';
      $header = '<span class="gray">'.functions::display_date($res['time']).'</span>';
      $text = functions::checkout($res['text'], 1, 1);
      $array = array('header' => $header, 'body' => $text, 'sub' => '');
      core::$user_set['avatar'] = 0;
      echo functions::display_user($res, $array);
      echo '</div>';
      ++$i;
    }
    
    echo '<div class="rmenu"><a href="index.php?act=clean&amp;logs&amp;yes">Очистить логи</a></div>';
  }else{
    echo '<div class="list1">Пусто</div>';
  }
  
}elseif(isset($_GET['user'])){
  
  $tree = array('<a href="index.php">Форум</a>', 'Удаление активности пользователя');
  echo '<div class="phdr">'.functions::display_menu($tree).'</div>';
   
  if (isset($_POST['send']) && !empty($_POST['user']) && !empty($_POST['del']) && $_POST['user'] != $user_id){
    $user = mysql_fetch_array(mysql_query("SELECT * FROM `users` WHERE `id` = '".intval($_POST['user'])."' LIMIT 1 "));
    if ($user['postforum']){
      if ($_POST['del'] == 2){
        $files = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_files` WHERE `user_id` = '".$user['id']."' "), 0);
        if ($files){
          $req = mysql_query("SELECT * FROM `forum_files` WHERE `user_id` = '".$user['id']."' ");
          while ($res = mysql_fetch_assoc($req)){
            @unlink('../files/forum/'.$res['filename']);
          }
          mysql_query("DELETE FROM `forum_files` WHERE `user_id` = '".$user['id']."' ");
        }
        
        $posts = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_posts` WHERE `user_id` = '".$user['id']."' "), 0);
        if ($posts){
          $req = mysql_query("SELECT * FROM `forum_posts` WHERE `user_id` = '".$user['id']."' ");
          while ($res = mysql_fetch_assoc($req)){
            mysql_query("DELETE FROM `forum_posts` WHERE `post` = '".$res['post']."' LIMIT 1 ");
            $lastPost = mysql_fetch_array(mysql_query("SELECT `post`, `time`, `user` FROM `forum_posts` WHERE `topic` = '".$res['topic']."' ORDER BY `time` DESC LIMIT 1 "));
            mysql_query("UPDATE `forum_topics` SET
            `time` = '".$lastPost['time']."',
            `lastpost` = '".$lastPost['user'].":|:".$lastPost['post']."',
            `count`= count - 1
            WHERE `topic`='".$res['topic']."' LIMIT 1 ");
            if ($res['rating'])
              mysql_query("DELETE FROM `forum_posts_rating` WHERE `post` = '".$res['post']."' ");  
          }
        }
        mysql_query("UPDATE `users` SET `postforum` = '0' WHERE `id` = '".$user['id']."' LIMIT 1 ");
        
        $topicReq = mysql_query("SELECT * FROM `forum_topics` WHERE `user_id` = '".$user['id']."' AND `count` = '0' ");
        if (mysql_num_rows($topicReq)){
          while ($topicRes = mysql_fetch_assoc($topicReq)){
            mysql_query("DELETE FROM `forum_topics` WHERE `topic`='".$topicRes['topic']."' ");
            mysql_query("DELETE FROM `forum_favourites` WHERE `topic` = '".$topicRes['topic']."' ");
            if ($topicRes['poll_name']){
              mysql_query("DELETE FROM `forum_polls` WHERE `topic` = '".$topicRes['topic']."' ");
              mysql_query("DELETE FROM `forum_polled` WHERE `topic` = '".$topicRes['topic']."' ");
              mysql_query("OPTIMIZE TABLE `forum_polled` ");
            }    
            
            $lastTopic = mysql_fetch_assoc(mysql_query("SELECT * FROM `forum_topics` WHERE `forum` = '".$topicRes['forum']."' ORDER BY `time` DESC LIMIT 1 "));
              
            $sql = empty($lastTopic['topicname']) ? '' : $lastTopic['topic'].':|:'.$lastTopic['topicname'].':|:'.$lastTopic['time'];
            mysql_query("UPDATE `forum_forums` SET
            `last_topic` = '$sql',
            `count` = count - 1
            WHERE `forum` = '".$topicRes['forum']."' LIMIT 1 ");
          }
        }
      }
      mysql_query("DELETE FROM `forum_readed` WHERE `user_id` = '".$user['id']."' ");
      mysql_query("DELETE FROM `forum_favourites` WHERE `user_id` = '".$user['id']."' ");
      mysql_query("DELETE FROM `forum_journal` WHERE `user_id` = '".$user['id']."' ");
           
      echo '<div class="gmenu">Активность пользователя на форуме очищена<br /><a href="index.php">Далее</a></div>';
    }else{
      echo functions::display_error('Пользователь не имеет активности на форуме!<br /><a href="index.php">Форум</a>');
    }
  }else{
    echo '<div class="rmenu">Нажав на кнопку вы удалите активность пользователя. Это может занять некоторое время!</div><form action="index.php?act=clean&amp;user" method="post"><div class="gmenu">ID пользователя: <input type="text" size="3" name="user" /> <input type="submit" name="send" vlaue="Удалить" /><br /><label><input type="radio" name="del" value="1" />Журнал, закладки</label><br /><label><input type="radio" name="del" value="2" />Журнал, закладки, темы, сообщения и файлы</label></div></form>';
  }
}elseif(isset($_GET['posts'])){
  $tree = array('<a href="index.php">Форум</a>', 'Сообщения  с отрицательным рейтингом');
  echo '<div class="phdr">'.functions::display_menu($tree).'</div>';
  $total = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_posts` WHERE `rating` < '-4' "), 0);
  
  if ($start >= $total){
    // Исправляем запрос на несуществующую страницу
    $start = max(0, $total - (($total % $kmess) == 0 ? $kmess : ($total % $kmess)));
  }
  
  if ($total){
    $req = mysql_query("SELECT `forum_posts`.*, `users`.`id`, `users`.`name`, `users`.`sex`, `users`.`rights`, `users`.`lastdate`, `users`.`status`, `users`.`datereg` FROM `forum_posts` LEFT JOIN `users` ON `forum_posts`.`user_id`=`users`.`id`  WHERE `rating` < '-4' ORDER BY `time` DESC LIMIT $start, $kmess ");
    while ($res = mysql_fetch_array($req)){
      echo $i % 2 ? '<div class="list2">' : '<div class="list1">';

      $header = ' '.functions::display_date($res['time']).' <a href="index.php?post='.$res['post'].'&amp;find" title="Перейти к сообщению">&gt;&gt;</a>';

      $text = quote(functions::checkout($res['text'], 1, 1));
      if ($set_user['smileys'])
        $text = functions::smileys($text, $res['rights'] >= 1 ? 1 : 0);
      
      if ($res['files']){
        $file = mysql_query("SELECT * FROM `forum_files` WHERE `post` = '".$res['post']."' LIMIT ".$res['files']." ");
        if (mysql_num_rows($file)){
          $text .= '<div class="func">Файл(ы):<br />';
          while($fileRes = mysql_fetch_array($file)){
            $text .= show_file($fileRes).'<br />';
          }
          $text .= '</div>';
        }
      }

      if ($res['edit']){
        $edit = explode(':|:', $res['edit']);
        $text .= '<div style="font-size: x-small; color: gray">Изменил(а) '.$edit['0'].' '.functions::display_date($edit['1']).($edit['2'] ? '<br />Причина: '.functions::checkout($edit['2'], 2) : '').'</div>';
      }

      $sub = false;
      if (!$topic){
        $topicRes = mysql_fetch_array(mysql_query("SELECT * FROM `forum_topics` WHERE `topic` = '".$res['topic']."' LIMIT 1 "));
        $sub = 'Тема: <a href="index.php?topic='.$topicRes['topic'].'">'.functions::checkout($topicRes['topicname']).'</a>';
      }
      $array = array('header' => $header, 'body' => $text, 'sub' => $sub);
      echo functions::display_user($res, $array).'</div>';
      ++$i;
    }
    
    echo '<div class="phdr">Сообщений: '.$total.'</div>';
    if ($total > $kmess)
      echo '<div class="topmenu">'.functions::display_pagination('index.php?act=clean&amp;posts&amp;', $start, $total, $kmess).'</div>';
  }else{
    echo '<div class="list1">Пусто</div>';
  }
}else{
  $tree = array('<a href="index.php">Форум</a>', 'Чистка форума');
  echo '<div class="phdr">'.functions::display_menu($tree).'</div>';
  echo '<div class="list1"><a href="index.php?act=clean&amp;files">Удаление временных файлов</a><br /><a href="index.php?act=clean&amp;user">Удаление активности пользователя</a><br /><a href="index.php?act=clean&amp;posts">Сообщения с отриц. рейтингом</a><br /><a href="index.php?act=clean&amp;logs">Логи форума</a></div>';
}