<?php
/**
 * @package		Article Hits for Joomla! 1.6
 * @type		Plugin (Content)
 * @filename	articlehits.php
 * @folder		<root>/plugins/content/articlehits
 * @version		1.0 
 * @modified	01 March 2011
 * @author		ToolJoom.com - Tools for Joomla!
 * @website		http://www.tooljoom.com
 * @license		GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 * 
 * @copyright (C) 2011 ToolJoom.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
**/

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

class plgContentArticleHits extends JPlugin
{
	public function __construct(&$subject, $config)
	{
		parent::__construct($subject, $config);
	}
	
	public function onContentPrepare($context, &$article, &$params, $page = 0)
	{
		if ((JString::strpos($article->text, '{hits}') === false) || (JString::strpos($article->text, '{/hits}') === false)) {
			return true;
		}
		
		$regex = "#{hits}(.*?){/hits}#s";
		
		$article->text = preg_replace_callback($regex, array(&$this, '_articlehits'), $article->text);
		
		return true;
	}
	
	protected function _articlehits($matches)
	{
		$db = &JFactory::getDBO();
		$query = 'SELECT hits FROM #__content WHERE id='. $matches[1] .' LIMIT 1';
		$db->setQuery($query);
		$hits = $db->loadResult();
		
		$return = '<span id="articlehits">'. $hits .'</span>';	
		
		return $return;
	}
}