<?

require_once("header.php");

function docleanup() {
	global $signup_timeout, $autoclean_interval;

	set_time_limit(0);
	ignore_user_abort(1);

	$deadtime = time() - $signup_timeout;
	mysql_query("DELETE FROM users WHERE status = 'pending' AND added < FROM_UNIXTIME($deadtime) AND last_login < FROM_UNIXTIME($deadtime) AND last_access < FROM_UNIXTIME($deadtime)");


	// lock topics where last post was made more than x days ago
	$secs = 14*86400;
	$res = mysql_query("SELECT topics.id FROM topics LEFT JOIN posts ON topics.lastpost = posts.id AND topics.sticky = 'no' WHERE " . gmtime() . " - UNIX_TIMESTAMP(posts.added) > $secs") or sqlerr(__FILE__, __LINE__);
	while ($arr = mysql_fetch_assoc($res))
		mysql_query("UPDATE topics SET locked='yes' WHERE id=$arr[id]") or sqlerr(__FILE__, __LINE__);

  //remove expired warnings
  $res = mysql_query("SELECT id FROM users WHERE warned='yes' AND warneduntil < NOW() AND warneduntil <> '0000-00-00 00:00:00'") or sqlerr(__FILE__, __LINE__);
  if (mysql_num_rows($res) > 0)
  {
    $dt = sqlesc(get_date_time());
    $msg = sqlesc("Your warning has been removed. Please keep in your best behaviour from now on.\n");
    while ($arr = mysql_fetch_assoc($res))
    {
      mysql_query("UPDATE users SET warned = 'no', warneduntil = '0000-00-00 00:00:00' WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
      mysql_query("INSERT INTO messages (sender, receiver, added, msg, poster) VALUES(0, $arr[id], $dt, $msg, 0)") or sqlerr(__FILE__, __LINE__);
    }
  }

	// Update stats
	// update forum post/topic count
	$forums = mysql_query("select id from forums");
	while ($forum = mysql_fetch_assoc($forums))
	{
		$postcount = 0;
		$topiccount = 0;
		$topics = mysql_query("select id from topics where forumid=$forum[id]");
		while ($topic = mysql_fetch_assoc($topics))
		{
			$res = mysql_query("select count(*) from posts where topicid=$topic[id]");
			$arr = mysql_fetch_row($res);
			$postcount += $arr[0];
			++$topiccount;
		}
		mysql_query("update forums set postcount=$postcount, topiccount=$topiccount where id=$forum[id]");
	}
	
	//Add points every 24. hour
	$point_interval = "86400"; // 24 hours
	$now = time();
	$res = mysql_query("SELECT value_u FROM avps WHERE arg = 'lastpointtime'");
    $row = mysql_fetch_array($res);
    if (!$row) {
        mysql_query("INSERT INTO avps (arg, value_u) VALUES ('lastpointtime',$now)");
    }
    $pi = $row[0];
    if ($pi + $point_interval > $now)
	return;
	
    mysql_query("UPDATE avps SET value_u=$now WHERE arg='lastpointtime' AND value_u = $pi");
	$res = mysql_query("SELECT id FROM users WHERE enabled = 'yes'") or sqlerr(__FILE__, __LINE__);
   if (mysql_num_rows($res) > 0)
   {
       while ($arr = mysql_fetch_assoc($res))
       {
       mysql_query("UPDATE users SET points = points+5 WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
       }
   }
	
}

?>