<?php
//
// blogstatistics - pLog Blog Statistics and Traffic Statistics
//
// Copyright 2004 by Minstrel Chiu. All rights reserved.
//
// Licensed under the GNU GPL License, Version 2.0 (the "License");
// Everyone is permitted to copy and distribute verbatim copies
// of this license document, but changing it is not allowed.
// You may obtain a copy of the License at
//
//   http://www.fsf.org/copyleft/gpl.html
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

	include_once( PLOG_CLASS_PATH."class/plugin/pluginbase.class.php" );
	include_once( PLOG_CLASS_PATH."class/plugin/pluginmanager.class.php" );
	include_once( PLOG_CLASS_PATH."class/dao/model.class.php" );
	include_once( PLOG_CLASS_PATH."class/data/Date.class.php" );
	include_once( PLOG_CLASS_PATH."class/net/client.class.php" );
	include_once( PLOG_CLASS_PATH."class/net/url.class.php" );
	include_once( PLOG_CLASS_PATH."class/net/httpvars.class.php" );
	include_once( PLOG_CLASS_PATH."class/data/timestamp.class.php" );

	class PluginBlogStatistics extends PluginBase
	{
		var $_prefix;
		var $_now;
		var $_date;
		var $_prevdate;
		var $_weekdate;
		var $_month;
		var $_onlinestamp;

		function PluginBlogStatistics()
		{
			$this->author = "Minstrel Chiu";
			$this->desc = "
			<p>This plugin offers a statistics of plog. Part of code is originally written by Mark Wu. And also thanks to Reic Wang.<br>
			Add the following code in header.template<br><br>
			<b>{\$blogstatistics->logStatistics()}</b><br>
			<br>
			Several functions are available:<br>
			 1. <b>Totoal Read Number</b>: <b><i>getTotalReadNumber()</i></b><br>
			 2. <b>Totoal Post Number</b>: <b><i>getTotalPostNumber()</i></b><br>
			 3. <b>Totoal Comment Number</b>: <b><i>getTotalCommentNumber()</i></b><br>
			 4. <b>Totoal Trackback Number</b>: <b><i>getTotalTrackbackNumber()</i></b><br>
			 5. <b>Total Referer Number</b>: <b><i>getTotalRefererNumber()</i></b><br>
			 6. <b>Today Visitor</b>: <b><i>getTodayVisitor()</i></b><br>
			 7. <b>Today Distinct Visitor</b>: <b><i>getTodayDistinctVisitor()</i></b><br>
			 8. <b>Yesterday Visitor</b>: <b><i>getYesterdayVisitor()</i></b><br>
			 9. <b>Yesterday Distinct Visitor</b>: <b><i>getYesterdayDistinctVisitor()</i></b><br>
			10. <b>This Week Visitor</b>: <b><i>getThisWeekVisitor()</i></b><br>
			11. <b>This Week Distinct Visitor</b>: <b><i>getThisWeekDistinctVisitor()</i></b><br>
			12. <b>This Month Visitor</b>: <b><i>getThisMonthVisitor()</i></b><br>
			13. <b>This Month Distinct Visitor</b>: <b><i>getThisMonthDistinctVisitor()</i></b><br>
			14. <b>Total Visitor</b>: <b><i>getTotalVisitor()</i></b><br>
			15. <b>Total Distinct Visitor</b>: <b><i>getTotalDistinctVisitor()</i></b><br>
			16. <b>Current Online Visitor</b>: <b><i>getOnlineVisitor()</i></b><br>
			<br>
			All above function default return all site statistics. If wanna get particular blog statistics,<br>
			can pass <b>{\$blog->getId()}</b> in, to get the particular blog statistics data.<br>
			<br>
			Examples:<br>
			<br>
			<p><b>
			Total Read: {\$blogstatistics->getTotalReadNumber()} Times<br />
			Total Post: {\$blogstatistics->getTotalPostNumber(()} Posts<br />
			Total Comments: {\$blogstatistics->getTotalCommentNumber()} Comments<br />
			Total Trackbacks: {\$blogstatistics->getTotalTrackbackNumber()} Trackbacks<br />
			Total Referers: {\$blogstatistics->getTotalRefererNumber()} Referers<br />
			<br />
			Today Visitors: {\$blogstatistics->getTodayVisitor()}<br />
			Yesterday Visitors: {\$blogstatistics->getYesterdayVisitor()}<br />
			This Week Visitors: {\$blogstatistics->getThisWeekVisitor()}<br />
			This Month Visitors: {\$blogstatistics->getThisMonthVisitor()}<br />
			Total Visitors: {\$blogstatistics->getTotalVisitor()}<br />
			Online Visitors: {\$blogstatistics->getOnlineVisitor()}<br />
			</b></p>
			</p>";

			$config = new Config();
			$this->_prefix = $config->getValue('db_prefix');

			$this->_now = new Date();

			$prevday = $this->_now->getPrevDay();

			$this->_date = $this->_now->format("%Y%m%d");
			$this->_month = $this->_now->format("%Y%m");
			$this->_prevdate = $prevday->format("%Y%m%d");

			$weekdate = $this->_now;
			$weekday = $this->_now->getDayOfWeek();

			for($day=$weekday; $day>0; $day--)
				$weekdate = $weekdate->getPrevDay();

			$this->_weekdate = $weekdate->format("%Y%m%d");
			
			$online = $this->_now;
			$online->subtractSeconds(360);
			
			$this->_onlinestamp = $online->getDate(DATE_FORMAT_TIMESTAMP);

			$this->PluginBase();
		}

		function register()
		{
			$this->connectDb();
			$stat = new BlogStatistics();
			$stat->createTable();
		}

		function logStatistics()
		{
			$blog = $this->blogInfo->getId();
			$timestamp = $this->_now->getDate(DATE_FORMAT_TIMESTAMP);
			$clientip = Client::getIp();
			$refer = $_SERVER["HTTP_REFERER"];
			$ourHost = $_SERVER["HTTP_HOST"];
			$agent = $_SERVER["HTTP_USER_AGENT"];

			$refererUrl = new Url( $refer );

			if( $refererUrl->getHost() == $ourHost || $refererUrl->getHost() == "" )
			{
				$refer = "";
			}

			$params = HttpVars::getRequest();
			$articleId = $params["articleId"];

			if($articleId == "")
				$articleId = 0;

			$this->injectSql("(`blog_id`, `article_id`, `time`, `ip`,  `refer`, `agent`) VALUES ('$blog', '$articleId', '$timestamp', '$clientip', '$refer', '$agent');");
		}

		function injectSql($dbqry)
		{
			$query = "INSERT INTO ".$this->_prefix."statistics $dbqry";
			$result = $this->db->Execute( $query );
		}

		////////////////////////////////////////////////////////////////////////////////////////////
		//
		//
		// Blog Static Statistics
		//
		//
		////////////////////////////////////////////////////////////////////////////////////////////

		function getTotalPostNumber($blogId = -1)
		{
			$query = "SELECT * FROM ".$this->_prefix."articles WHERE status='published'";

			if( $blogId != -1 )
				$query .= " AND blog_id = ".$blogId;

			$query .= ";";

			$result = $this->db->Execute( $query );

			if( $result )
				$count = $result->RecordCount();

			return $count;
		}

		function getTotalCommentNumber($blogId = -1)
		{
			$query = "SELECT * FROM ".$this->_prefix."articles_comments,".$this->_prefix."articles WHERE ".$this->_prefix."articles_comments.article_id=".$this->_prefix."articles.id AND ".$this->_prefix."articles.status='published'";

			if( $blogId != -1 )
				$query .= " AND ".$this->_prefix."articles.blog_id=".$blogId;

			$query .= ";";

			$result = $this->db->Execute( $query );

			if( $result )
				$count = $result->RecordCount();

			return $count;
		}

		function getTotalReadNumber($blogId = -1)
		{
			$query = "SELECT SUM(num_reads) AS readNumber FROM ".$this->_prefix."articles WHERE status='published'";

			if( $blogId != -1 )
				$query .= " AND blog_id = ".$blogId;

			$query .= ";";

			$result = $this->db->Execute( $query );

			if( !$result )
				return false;

			$row = $result->FetchRow();
			return $row["readNumber"];
		}

		function getTotalRefererNumber($blogId = -1)
		{
			$query = "SELECT * FROM ".$this->_prefix."referers";

			if( $blogId != -1 )
				$query .= " WHERE blog_id = ".$blogId;

			$query .= ";";

			$result = $this->db->Execute( $query );

			if( $result )
				$count = $result->RecordCount();

			return $count;
		}

		function getTotalTrackbackNumber($blogId = -1)
		{
			$query = "SELECT * FROM ".$this->_prefix."trackbacks,".$this->_prefix."articles WHERE ".$this->_prefix."trackbacks.article_id=".$this->_prefix."articles.id AND ".$this->_prefix."articles.status='published'";

			if( $blogId != -1 )
				$query .= " AND ".$this->_prefix."articles.blog_id=".$blogId;

			$query .= ";";

			$result = $this->db->Execute( $query );

			if( $result )
				$count = $result->RecordCount();

			return $count;
		}

		////////////////////////////////////////////////////////////////////////////////////////////
		//
		//
		// Blog Dynamic Statistics
		//
		//
		////////////////////////////////////////////////////////////////////////////////////////////

		function getOnlineVisitor($blogId = -1)
		{
			$query = "SELECT DISTINCT ip FROM ".$this->_prefix."statistics WHERE date_format(time, '%Y%m%d%H%i%S') >= ".$this->_onlinestamp;
			
			if( $blogId != -1 )
				$query .= " AND blog_id = ".$blogId;

			$query .= ";";

			$result = $this->db->Execute( $query );

			if( $result )
				$count = $result->RecordCount();

			return $count;
		}
		
		function getTotalVisitor($blogId = -1)
		{
			$query = "SELECT * FROM ".$this->_prefix."statistics";

			if( $blogId != -1 )
				$query .= " WHERE blog_id = ".$blogId;

			$query .= ";";

			$result = $this->db->Execute( $query );

			if( $result )
				$count = $result->RecordCount();

			return $count;
		}

		function getTotalDistinctVisitor($blogId = -1)
		{
			$query = "SELECT DISTINCT ip FROM ".$this->_prefix."statistics";

			if( $blogId != -1 )
				$query .= " WHERE blog_id = ".$blogId;

			$query .= ";";

			$result = $this->db->Execute( $query );

			if( $result )
				$count = $result->RecordCount();

			return $count;
		}

		function getTodayVisitor($blogId = -1)
		{
			$query = "SELECT * FROM ".$this->_prefix."statistics WHERE date_format(time, '%Y%m%d') = ".$this->_date;

			if( $blogId != -1 )
				$query .= " AND blog_id = ".$blogId;

			$query .= ";";

			$result = $this->db->Execute( $query );

			if( $result )
				$count = $result->RecordCount();

			return $count;
		}

		function getTodayDistinctVisitor($blogId = -1)
		{
			$query = "SELECT DISTINCT ip FROM ".$this->_prefix."statistics WHERE date_format(time, '%Y%m%d') = ".$this->_date;

			if( $blogId != -1 )
				$query .= " AND blog_id = ".$blogId;

			$query .= ";";

			$result = $this->db->Execute( $query );

			if( $result )
				$count = $result->RecordCount();

			return $count;
		}

		function getYesterdayVisitor($blogId = -1)
		{
			$query = "SELECT * FROM ".$this->_prefix."statistics WHERE date_format(`time`, '%Y%m%d' ) = ".$this->_prevdate;
			if( $blogId != -1 )
				$query .= " AND blog_id = ".$blogId;

			$query .= ";";

			$result = $this->db->Execute( $query );

			if( $result )
				$count = $result->RecordCount();

			return $count;
		}

		function getYesterdayDistinctVisitor($blogId = -1)
		{
			$query = "SELECT DISTINCT ip FROM ".$this->_prefix."statistics WHERE date_format(`time`, '%Y%m%d' ) =".$this->_prevdate;

			if( $blogId != -1 )
				$query .= " AND blog_id = ".$blogId;

			$query .= ";";

			$result = $this->db->Execute( $query );

			if( $result )
				$count = $result->RecordCount();

			return $count;
		}

		function getThisWeekVisitor($blogId = -1)
		{
			$query = "SELECT * FROM ".$this->_prefix."statistics WHERE (date_format(`time`, '%Y%m%d')) >= ".$this->_weekdate;

			if( $blogId != -1 )
				$query .= " AND blog_id = ".$blogId;

			$query .= ";";

			$result = $this->db->Execute( $query );

			if( $result )
				$count = $result->RecordCount();

			return $count;
		}

		function getThisWeekDistinctVisitor($blogId = -1)
		{
			$query = "SELECT DISTINCT ip FROM ".$this->_prefix."statistics WHERE (date_format(`time`, '%Y%m%d')) >= ".$this->_weekdate;

			if( $blogId != -1 )
				$query .= " AND blog_id = ".$blogId;

			$query .= ";";

			$result = $this->db->Execute( $query );

			if( $result )
				$count = $result->RecordCount();

			return $count;
		}

		function getThisMonthVisitor($blogId = -1)
		{
			$query = "SELECT * FROM ".$this->_prefix."statistics WHERE date_format(`time`, '%Y%m') = ".$this->_month;

			if( $blogId != -1 )
				$query .= " AND blog_id = ".$blogId;

			$query .= ";";

			$result = $this->db->Execute( $query );

			if( $result )
				$count = $result->RecordCount();

			return $count;
		}

		function getThisMonthDistinctVisitor($blogId = -1)
		{
			$query = "SELECT DISTINCT ip FROM ".$this->_prefix."statistics WHERE date_format(`time`, '%Y%m') = ".$this->_month;

			if( $blogId != -1 )
				$query .= " AND blog_id = ".$blogId;

			$query .= ";";

			$result = $this->db->Execute( $query );

			if( $result )
				$count = $result->RecordCount();

			return $count;
		}
	}

	class BlogStatistics extends Model
	{
		function BlogStatistics()
		{
			$this->Model();
		}

		function checkTable($table, $field)
		{
			$dbPrefix = $this->getPrefix();
			$tableName = $dbPrefix.$table;

			// create the data dictionary and create the table if necessary
			$dict = NewPDbDataDictionary( $this->_db );
			$sqlArray = $dict->ChangeTableSQL( $tableName, $field );
			$result = $dict->ExecuteSQLArray( $sqlArray );

			if( $result == 0 )
				$this->_desc = "There was an error initializing the tables.";
		}

		function createTable()
		{
			$table = "statistics";
			$field = "blog_id I(10) NOT NULL default '-1',
				article_id I(10) NOT NULL default '-1',
				time timestamp(14),
				ip varchar(15) default '0.0.0.0',
				refer text NOT NULL,
				agent text NOT NULL";

			$this->checkTable( $table, $field );

			return true;
		}
	}

	PluginManager::registerPlugin( "blogstatistics", "PluginBlogStatistics" );
?>
