<?php

/*
 *	W-AGORA 4.1
 *	-----------
 *	$Id: find_stats.inc,v 1.14 2006/03/06 15:19:22 mdruilhe Exp $
 *	Usage:		Include file for functions used in statistics module
 *	Author:		Syloo (syloo@w-agora.net)
 */

if (!defined('_GLOBALS')) {
	die('Hacking attempt');
}

if (defined('_FIND_STATS')) return;
define('_FIND_STATS', 1);

if (file_exists("$lang_dir/stats_$lang.inc") ) {
	include("$lang_dir/stats_$lang.inc");
} else {
	include("$lang_dir/stats_${default_lang}.inc");
}

define (BAR_NUM_HITS, 1);
define (BAR_NUM_LOGINS, 2);
define (BAR_NUM_POSTS, 3);
define (BAR_NUM_SUBSCRIBES, 4);
define (BAR_NUM_VISITS, 5);

function siteGeneralStats($site) {
	global $db;

	$stats = $db->getSiteStats($site, true);
	if (is_array($stats) ) {
		$stats['site_name'] = $site;
		$stats['totalsubscribes'] = $db->countSubscribedUsers($site);
	}

	return $stats;
}

/**
 * Find stats for site forums
 * @param     $site     site to find
 * @access    public
 * @return    void
 */
function SiteForumStats($site) {
	global $db,$ext,$agora_dir;

	$forums = $db->getForums($site);
	$tab_userforum = $site . "_userforum";
	$tab_userthread = $site . "_userthread";
	$i = 1;
	reset($forums);
	while (list($cur_forum,$title) = each($forums)) {
		$forum[$i] = $db->getForum($site,$cur_forum);
		$table = $forum[$i]["bn_db"];
		$name = $forum[$i]["bn_name"];
		$access = $forum[$i]["type"];

		$stats = $db->getForumStats($table);
		if (is_array($stats) ) {
			$forum[$i]['totalauthors'] = $stats['totalauthors'];
			$forum[$i]['totalhits'] = $stats['totalhits'];
			unset($stats);
		}
		$forum[$i]['totalsubscribes'] = $db->countSubscribedUsers($site, $table);

		if (($access == "rest") || ($access == "priv")) {
			$q = "SELECT count(userid) as tot_register FROM $tab_userforum WHERE state='1' AND bn_name	= '$name'";
			$db->query("$q");
			if ($db->next_record()) {
				$forum[$i]["totalregisters"] = $db->f("tot_register");
			}
		}
		$i++;
	}//while
	return $forum;
}

/**
 * Find hit parade for the site
 * @param     $site     site to find
 * @param     $hit      hit parade to build
 * @param     $n        #lines to build
 * @access    public
 * @return    void
 */
function siteHitParade($site,$num_hit,$n = 10) {
	global $db,$ext,$agora_dir;
	switch ($num_hit) {
		case 1: $hit["title"] = TITLE_RECENT_THREADS;
				$hit["title_color"] = "#ffcccc";
				break;
		case 2: $hit["title"] = TITLE_ACTIVE_THREADS;
				$hit["title_color"] = "#ffcccc";
				break;
		case 3: $hit["title"] = TITLE_READ_NOTES;
				$hit["title_color"] = "#ffffcc";
				break;
	}
	$forums = $db->getForums($site);
	reset($forums);
	while (list($bn) = each ($forums) ) {
		$forum = $db->getForum($site, $bn);
		$bn_db = $forum["bn_db"];
		$bn_title = $forum["bn_title"];
		$bn_name = explode("_",$forum["bn_name"]);
		if (!isset($tables [$bn_db]) ) {
			$tables [$bn_db] = $bn; // eliminate doubles
		}
		if (!isset($titles [$bn_db]) ) {
			$titles [$bn_db] = $bn_title;   // eliminate doubles
		}
		if (!isset($names [$bn_db]) ) {
			$names [$bn_db] = $bn_name[1];  // eliminate doubles
		}
	}
	reset ($tables);
	reset ($titles);
	reset ($names);
	while (list($table, $bn) = each ($tables) ) {
		if ($num_hit == 1) {
			// latest thread
			$q = "SELECT cle,unixdate,username,subject,hits,newest FROM $table WHERE parent=0 ORDER BY newest DESC LIMIT $n";
		} elseif ($num_hit == 2) {
			// order by most active
			// $q = "SELECT thread as cle, min(unixdate) as open_date, max(unixdate) AS newest,	count(cle) as tot_replies, sum(hits) as tot_hits, count(DISTINCT username) as tot_authors FROM $table GROUP BY thread";
			$q = "SELECT thread as cle, min(unixdate) as open_date, max(unixdate) AS newest, count(cle) as tot_replies FROM $table GROUP BY thread";
		} else {
			// most read notes
			$q = "SELECT cle,unixdate,username,subject,hits,newest FROM $table ORDER BY hits DESC LIMIT $n";
		}
		$result = $db->query ("$q");
		while ($db->next_record() ) {
			$k = $db->f("cle");
			$rec[$k] = $db->Record;
			$rec[$k]["bn"] = $bn;
			$rec[$k]["bn_title"] = $titles[$table];
			$rec[$k]["bn_name"] = $names[$table];
			$rec[$k]["table"] = $table;
			if ($num_hit == 1) {
				$sort[$k] = $db->f("newest");
			} elseif ($num_hit == 2) {
				// $sort[$k] = (1 + $db->f("tot_replies")) * (1 + $db->f("tot_hits")) * (1 + pow((int)$db->f("tot_authors"),2));
				// $sort[$k] /= pow(pow(time() - $db->f("open_date"),1/2) * (time() - $db->f("newest")),1/2);
				// $sort[$k] = pow($sort[$k],1/3);
				// $age = ceil((time() - $db->f("open_date") ) / 3600);
				// $updated_time = ceil((time() - $db->f("newest")) / 3600);
				// $r = $db->f("tot_replies");
				$sort[$k] = $db->f("tot_replies") / ceil((time() - $db->f("newest")) / 3600);
			} else{
				$sort[$k] = $db->f("hits");
			}
		}
	}

	if (empty($sort)) {
		return $hit;
	}

	//percentage calcul
	if ($num_hit == 2) {
		$max = max($sort);
		if ($max>0) {
			reset($sort);
			while (list($k,$ratio) = each($sort)) {
				$sort[$k] = round(100 * $ratio / $max, 1);
			}
		}
	}

	// sort by reverse order
	arsort ($sort);
	$i = 0;
	reset($sort);
	while (list($id,$s) = each ($sort) ) {
		if (++$i > $n) break;
		$bn = $rec[$id]["bn"];
		$name = $rec[$id]["bn_name"];
		$title = $rec[$id]["bn_title"];
		$key = $rec[$id]["cle"];
		$username = $rec[$id]["username"];
		$auth = $rec[$id]["tot_authors"];
		$replies = $rec[$id]["tot_replies"];
		$tot_hits = $rec[$id]["tot_hits"];
		if ($num_hit == 2) {
			$table = $rec[$id]["table"];
			$unixdate = $rec[$id]["open_date"];
			$q = "SELECT subject FROM $table WHERE unixdate = $unixdate";
			$result = $db->query("$q");
			if ($db->next_record()) {
				$rec[$id]["subject"] = $db->f("subject");
			}
		}
		$subject = $rec[$id]["subject"];
		$short_subject = (strlen($subject) > 30)? substr($subject,0,30) . ".": $subject;
		$date = formated_date($rec[$id]["newest"]);
		$line_sort = ($num_hit == 1)? LABEL_LAST . ": <font color='#ff6666'>$date</font>": (($num_hit == 2)? LABEL_RATIO . ": <font color='#ff6666'>$s %</font>": LABEL_READ . " <font color='#ff6666'><b>$s</b></font> " . LABEL_TIMES);
		$link = anchor("$agora_dir/view.$ext?bn=$bn&key=$key", '', $short_subject, $subject);
		$hit[$i] = "$link<br>&nbsp;&nbsp;" . LABEL_FORUM . "&nbsp;<a href=\"$agora_dir/list.$ext?bn=$bn\" class=label>$name</a><br>&nbsp;&nbsp;&nbsp;<span class=s_label>($title)<br>&nbsp;&nbsp;$line_sort";
	}
	return $hit;
}

/**
 * Find stats by month for site
 * @param     $site     site to find
 * @access    public
 */
function siteMonthStats($site,$to_find) {
	global $db;

	$result = $db->getMonthlyStats($site);
	if (!is_array($result)) {
		return $result;
	}

	if (!empty($to_find["visits"])) {
		$visits = $db->getMonthlyVisitors($site);
	}

	$this_month = date("m");
	$this_year = date("Y");
	$i = 12;
	while ($i > 0) {
		$cur_month = (($this_month + $i - 12) > 0)? $this_month + $i - 12 : $this_month + $i;
		$cur_year = (($this_month + $i - 12) > 0)? $this_year : $this_year - 1;
		$stat[$i]["date"] = strtotime("$cur_month/1/$cur_year");
		$cur_date = sprintf ('%04d%02d', $cur_year, $cur_month);
		if (!empty($to_find["hits"])) {
			$stat[$i][BAR_NUM_HITS] = $result[$cur_date]['view'];
		}
		if (!empty($to_find["logins"])) {
			$stat[$i][BAR_NUM_LOGINS] = $result[$cur_date]['login'];
		}
		if (!empty($to_find["posts"])) {
			$stat[$i][BAR_NUM_POSTS] = $result[$cur_date]['insert'];
		}
		if (!empty($to_find["subscribes"])) {
			$stat[$i][BAR_NUM_SUBSCRIBES] = $result[$cur_date]['subscribe'];
		}
		if (is_array($visits)) {
			$stat[$i][BAR_NUM_VISITS] = $visits[$cur_date];
		}
		$i--;
	}
	return $stat;
}

/**
 * Find general stats for specified site and month
 */
function monthGeneralStats($site, $month, $year) {
	global $db;

	$result = $db->getMonthlyStats($site, $year, $month);
	if (!is_array($result)) {
		return $result;
	}

	$visits = $db->getMonthlyVisitors($site, $year, $month);

	$stat['site_name'] = $site;
	$stat['month_name'] = date ('M. Y', strtotime("$month/1/$year"));

	$yearmonth = sprintf ('%04d%02d', $year, $month);

	$stat["totalposts"] = $result[$yearmonth]['insert'];
	$stat["totalhits"] = $result[$yearmonth]['view'];
	$stat["totallogins"] = $result[$yearmonth]['login'];
	$stat["totalsubscribes"] = $result[$yearmonth]['subscribe'];
	$stat["totalhits"] = $result[$yearmonth]['view'];
	$stat["totalvisits"] = $visits[$yearmonth];

	return $stat;
} // end func



/**
 * Find daily stats for specified site and month
 */
function monthDailyStats($site, $month, $year, $to_find) {
	global $db;


	$result = $db->getDailyStats($site, $year, $month);
	if (!is_array($result)) {
		return $result;
	}

	if (!empty($to_find["visits"])) {
		$visits = $db->getDailyVisitors($site, $year, $month);
	}

	$last_day = date('t', strtotime("$month/1/$year"));
	for ($i_day=1; $i_day <= $last_day; $i_day++) {

		$cur_day = sprintf("%02d",$i_day);

		if (!empty($to_find["hits"])) {
			$stat[$i_day][BAR_NUM_HITS] = $result[$cur_day]['view'];
		}
		if (!empty($to_find["logins"])) {
			$stat[$i_day][BAR_NUM_LOGINS] = $result[$cur_day]['login'];
		}
		if (!empty($to_find["posts"])) {
			$stat[$i_day][BAR_NUM_POSTS] = $result[$cur_day]['insert'];
		}
		if (!empty($to_find["subscribes"])) {
			$stat[$i_day][BAR_NUM_SUBSCRIBES] = $result[$cur_day]['subscribe'];
		}
		if (is_array($visits)) {
			$stat[$i_day][BAR_NUM_VISITS] = $visits[$cur_day];
		}
	}

	return $stat;
} // end func


?>