<?php
/**
* @version		$Id: helper.php 10857 2008-08-30 06:41:16Z willebil $
* @package		Joomla
* @copyright	Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
* @license		GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
require_once (JPATH_SITE.DS.'components'.DS.'com_content'.DS.'helpers'.DS.'route.php');
class modMicroBlogHelper
{
	function getList(&$params)
	{
		global $mainframe;
		$db			=& JFactory::getDBO();
		$user		=& JFactory::getUser();
		$userId		= (int) $user->get('id');
		$articleSource = $params->get('article_source','cat');
		$count		= (int) $params->get('count', 5);
		$catid		= $params->get('catid');
		$artid		= $params->get('artid');
		$show_front	= (int)$params->get('show_front', 1);
		$aid		= $user->get('aid', 0);
		$dateFormat		= $params->get('dateFormat', 'j M, y');
		$translateDate		= $params->get('translateDate', '0');
		$dateString		= $params->get('dateString', 'DATE_FORMAT_LC3');	
		$renderPlugin	= $params->get('renderPlugin','render');
		$contentConfig = &JComponentHelper::getParams( 'com_content' );
		$access		= !$contentConfig->get('show_noauth');
		$linkTarget = $params->get('linkTarget','article');
		$showCategory = $params->get('showCategory',0);
		$catlink = $params->get('catLink',0);
		$stripTags = $params->get('strip_tags',0);
		$introSuffix = $params->get('introSuffix','');
		$wordCount	= $params->get( 'wordCount','');		
		$tags	= $params->get( 'allowed_tags', '10' );
		$nullDate	= $db->getNullDate();
		$date =& JFactory::getDate();
		$now = $date->toMySQL();
		$where		= 'a.state = 1'
			. ' AND ( a.publish_up = '.$db->Quote($nullDate).' OR a.publish_up <= '.$db->Quote($now).' )'
			. ' AND ( a.publish_down = '.$db->Quote($nullDate).' OR a.publish_down >= '.$db->Quote($now).' )'
			;
		// User Filter
		switch ($params->get( 'user_id' ))
		{
			case 'by_me':
				$where .= ' AND (created_by = ' . (int) $userId . ' OR modified_by = ' . (int) $userId . ')';
				break;
			case 'not_me':
				$where .= ' AND (created_by <> ' . (int) $userId . ' AND modified_by <> ' . (int) $userId . ')';
				break;
		}
		// Ordering
		switch ($params->get( 'ordering' ))
		{
			case 'random':
				$ordering = 'rand()';
				break;
			case 'm_dsc':
				$ordering		= 'a.modified DESC, a.created DESC';
				break;
			case 'date':
				$ordering = 'a.created';
				break;
			case 'rdate':
				$ordering = 'a.created DESC';
				break;
			case 'alpha':
				$ordering = 'a.title';
				break;
			case 'ralpha':
				$ordering = 'a.title DESC';
				break;
			case 'hits':
				$ordering = 'a.hits DESC';
				break;
			case 'rhits':
				$ordering = 'a.hits ASC';
				break;
			case 'order':
			default:
				$ordering = 'a.ordering';
				break;
		}
		$frontCondition1 = ($show_front  ? ' INNER JOIN #__content_frontpage AS f ON f.content_id = a.id' : '');
		$frontCondition2 = ($show_front  ? ' AND f.content_id IS NULL ' : '');
		//we get articles in the selected categories
		$catCondition = '';
		if (($catid)&&($articleSource=='cat'))
		{ 
			if( is_array( $catid ) ) {
				if(!($catid[0])) {$catCondition = "";}else{
				$catCondition = ' AND (cc.id IN ( ' . implode( ',', $catid ) . ') )';}
			} else {
				$catCondition = ' AND (cc.id = '.$catid.')';
			}	
		} 			
		//we get the selected articles
		$artCondition = '';
		if ($artid)
		{ 
			if( is_array( $artid ) ) {
				$artCondition = ' AND (a.id IN ( ' . implode( ',', $artid ) . ') )';
			} else {
				$artCondition = ' AND (a.id = '.$artid.')';
			}	
		}
		// Content Items only
		$query = 'SELECT a.*, ' .
			' cc.title as catname,'.
			' CASE WHEN CHAR_LENGTH(a.alias) THEN CONCAT_WS(":", a.id, a.alias) ELSE a.id END as slug,'.
			' CASE WHEN CHAR_LENGTH(cc.alias) THEN CONCAT_WS(":", cc.id, cc.alias) ELSE cc.id END as catslug'.
			' FROM #__content AS a' .
			$frontCondition1.
			' INNER JOIN #__categories AS cc ON cc.id = a.catid' .
			' INNER JOIN #__sections AS s ON s.id = a.sectionid' .
			' WHERE '. $where .' AND s.id > 0' .
			($access ? ' AND a.access <= ' .(int) $aid. ' AND cc.access <= ' .(int) $aid. ' AND s.access <= ' .(int) $aid : '').
			$artCondition.
			$catCondition.
			' AND s.published = 1' .
			' AND cc.published = 1' .
			' ORDER BY '. $ordering;
		$db->setQuery($query, 0, $count);
		$rows = $db->loadObjectList();
		$i		= 0;
		$lists	= array();
		foreach ( $rows as $row )
		{
			if($row->access <= $aid)
			{
				if($linkTarget == 'article' or $linkTarget == 'panel') $lists[$i]->link = JRoute::_(ContentHelperRoute::getArticleRoute($row->slug, $row->catslug, $row->sectionid));
				if($linkTarget == 'default') $lists[$i]->link = JRoute::_(ContentHelperRoute::getCategoryRoute($row->catslug,$row->sectionid).'&layout=default');
				if($linkTarget == 'blog') $lists[$i]->link = JRoute::_(ContentHelperRoute::getCategoryRoute($row->catslug,$row->sectionid).'&layout=blog');
				$lists[$i]->catlink = JRoute::_(ContentHelperRoute::getCategoryRoute($row->catslug,$row->sectionid).'&layout=blog');
			} else {
				$lists[$i]->link = JRoute::_('index.php?option=com_user&view=login');
			}
			
			$imghtml= $row->introtext;
			$imghtml .= "alt='...' title='...' />";
			$pattern = '/<img[^>]+src[\\s=\'"]';
			$pattern .= '+([^"\'>\\s]+)/is';
			if(preg_match(
			$pattern,
			$imghtml,
			$match))
			$lists[$i]->firstImage = "$match[1]";
			else $lists[$i]->firstImage = "";
			$row->introtext = $stripTags ? self::_cleanIntrotext($row->introtext,$tags) : $row->introtext;
			$row->introtext = $wordCount ? self::string_limit_words($row->introtext, $wordCount, $introSuffix) : $row->introtext;
			$lists[$i]->metakey = $row->metakey;
			$lists[$i]->title = $row->title;
			$lists[$i]->introtext = $row->introtext;
			$lists[$i]->fulltext = $row->fulltext;
			
			if (!$translateDate) {
				$lists[$i]->dateCreated = date($dateFormat,  (strtotime($row->created)));
			}
			else {
				$lists[$i]->dateCreated = JHTML::_('date', $item->created, JText::_(''.$dateString.''));
			}
		
			$lists[$i]->id = $row->id;
			if($showCategory)$lists[$i]->catname = $row->catname;
			$i++;
		}
		return $lists;
	}
	
	public static function _cleanIntrotext($introtext,$tags)
	{
		//$introtext = str_replace('<p>', ' ', $introtext);
		//$introtext = str_replace('</p>', ' ', $introtext);
		$introtext = strip_tags($introtext, $tags);

		$introtext = trim($introtext);

		return $introtext;
	}
	
	public static function string_limit_words($introText, $wordCount, $suffixChar='&hellip;') 
	{
	    $introText = trim($introText); 
		$id = explode(' ', $introText);
		 $suffix = count($id) <= $wordCount ? '' : $suffixChar;
	     return implode(' ', array_slice($id, 0, $wordCount)) . $suffix;
	 }
	
	/**
	* This is a better truncate implementation than what we
	* currently have available in the library. In particular,
	* on index.php/Banners/Banners/site-map.html JHtml's truncate
	* method would only return "Article...". This implementation
	* was taken directly from the Stack Overflow thread referenced
	* below. It was then modified to return a string rather than
	* print out the output and made to use the relevant JString
	* methods.
	*
	* @link http://stackoverflow.com/questions/1193500/php-truncate-html-ignoring-tags
	* @param mixed $html
	* @param mixed $maxLength
	*/
	public static function truncate($html, $maxLength = 0, $suffixChar='&hellip;')
	{
		$printedLength = 0;
		$position = 0;
		$tags = array();
		$suffix = '';
		$output = '';
		
		if((JString::strlen($html)) > ($maxLength+1)){
			$suffix = $suffixChar;
		}
			
		if (empty($html)) {
			return $output;
		}

		while ($printedLength < $maxLength && preg_match('{</?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;}', $html, $match, PREG_OFFSET_CAPTURE, $position))
		{
			list($tag, $tagPosition) = $match[0];

			// Print text leading up to the tag.
			$str = JString::substr($html, $position, $tagPosition - $position);
			if ($printedLength + JString::strlen($str) > $maxLength) {
				$output .= JString::substr($str, 0, $maxLength - $printedLength);
				$printedLength = $maxLength;
				break;
			}

			$output .= $str;
			$lastCharacterIsOpenBracket = (JString::substr($output, -1, 1) === '<');

			if ($lastCharacterIsOpenBracket) {
				$output = JString::substr($output, 0, JString::strlen($output) - 1);
			}

			$printedLength += JString::strlen($str);

			if ($tag[0] == '&') {
				// Handle the entity.
				$output .= $tag;
				$printedLength++;
			}
			else {
				// Handle the tag.
				$tagName = $match[1][0];

				if ($tag[1] == '/') {
					// This is a closing tag.
					$openingTag = array_pop($tags);

					$output .= $tag;
				}
				else if ($tag[JString::strlen($tag) - 2] == '/') {
					// Self-closing tag.
					$output .= $tag;
				}
				else {
					// Opening tag.
					$output .= $tag;
					$tags[] = $tagName;
				}
			}

			// Continue after the tag.
			if ($lastCharacterIsOpenBracket) {
				$position = ($tagPosition - 1) + JString::strlen($tag);
			}
			else {
				$position = $tagPosition + JString::strlen($tag);
			}

		}

		// Print any remaining text.
		if ($printedLength < $maxLength && $position < JString::strlen($html)) {
			$output .= JString::substr($html, $position, $maxLength - $printedLength);
		}

		$output .= $suffix;
		// Close any open tags.
		while (!empty($tags))
		{
			$output .= sprintf('</%s>', array_pop($tags));
		}

		$length = JString::strlen($output);
		$lastChar = JString::substr($output, ($length - 1), 1);
		$characterNumber = ord($lastChar);

		if ($characterNumber === 194) {
			$output = JString::substr($output, 0, JString::strlen($output) - 1);
		}

		$output = JString::rtrim($output);

		return $output;
	}
}
//Class modified from K2 Content Module helper
class modMBK2ContentHelper {
  function getList(&$params) {
  	global $mainframe;
    jimport('joomla.filesystem.file');
    $limit = (int) $params->get('count', 5);
    $cid = $params->get('k2catid', NULL);
    $ordering = $params->get('orderingK2');
    $limitstart = JRequest::getInt('limitstart');
    $user = &JFactory::getUser();
    $aid = $user->get('aid');
    $db = &JFactory::getDBO();
    $linkTarget = $params->get('linkTarget','article');
	$dateFormat	= $params->get('dateFormat', 'j M, y');	
	$translateDate		= $params->get('translateDate', '0');
		$dateString		= $params->get('dateString', 'DATE_FORMAT_LC3');	
	$stripTags = $params->get('strip_tags',0);
	$introSuffix = $params->get('introSuffix','');
	$wordCount	= $params->get( 'wordCount','');
	$tags	= $params->get( 'allowed_tags', '10' );
    $jnow = &JFactory::getDate();
    $now = $jnow->toMySQL();
    $nullDate = $db->getNullDate();
	$itemid = $params->get('itemid','');
    $query = "SELECT i.*, c.name AS categoryname,c.id AS categoryid, c.alias AS categoryalias, c.params AS categoryparams";
    if ($ordering == 'best')
      $query .= ", (r.rating_sum/r.rating_count) AS rating";
    $query .= " FROM #__k2_items as i LEFT JOIN #__k2_categories c ON c.id = i.catid";
    if ($ordering == 'best')
      $query .= " LEFT JOIN #__k2_rating r ON r.itemID = i.id";
    $query .= " WHERE i.published = 1 AND i.access <= {$aid} AND i.trash = 0 AND c.published = 1 AND c.access <= {$aid} AND c.trash = 0";
    $query .= " AND ( i.publish_up = ".$db->Quote($nullDate)." OR i.publish_up <= ".$db->Quote($now)." )";
    $query .= " AND ( i.publish_down = ".$db->Quote($nullDate)." OR i.publish_down >= ".$db->Quote($now)." )";
	if($params->get('itemFilter') != 'item'){
		if (!is_null($cid)) {
	        if (is_array($cid)) {
	         if ($params->get('getChildren')) {
	           require_once (JPATH_SITE.DS.'components'.DS.'com_k2'.DS.'models'.DS.'itemlist.php');
	           $allChildren = array();
	           foreach ($cid as $id) {
	             $categories = K2ModelItemlist::getCategoryChilds($id);
	             $categories[] = $id;
	             $categories = @array_unique($categories);
	             $allChildren = @array_merge($allChildren, $categories);
	           }
	           $allChildren = @array_unique($allChildren);
	           $sql = @implode(',', $allChildren);
	           $query .= " AND i.catid IN ({$sql})";
	         } else {
	           $query .= " AND i.catid IN(".implode(',', $cid).")";
	         }
	       } else {
	         if ($params->get('getChildren')) {
	           require_once (JPATH_SITE.DS.'components'.DS.'com_k2'.DS.'models'.DS.'itemlist.php');
	           $categories = K2ModelItemlist::getCategoryChilds($cid);
	           $categories[] = $cid;
	           $categories = @array_unique($categories);
	           $sql = @implode(',', $categories);
	           $query .= " AND i.catid IN ({$sql})";
	         } else {
	           $query .= " AND i.catid={$cid}";
	         }
	       }
	     }
	}
    if($params->get('itemFilter') == 'item'){
		if(!is_array($itemid)) {$itemid		= preg_split("/[\s,]+/", $itemid);}
		JArrayHelper::toInteger( $itemid );
		$query .= ' AND (i.id=' . implode( ' OR i.id=', $itemid ) . ')';
	}
	if($params->get('itemFilter') == 'catitem'){
		$itemid		= preg_split("/[\s,]+/", $itemid);
		JArrayHelper::toInteger( $itemid );
		$query .= ' OR (i.id=' . implode( ' OR i.id=', $itemid ) . ')';
	}
    if ($params->get('itemFilter') == 'feat')
      $query .= " AND i.featured = 1";
    switch ($ordering) {
      case 'date':
        $orderby = 'i.created ASC';
        break;
      case 'rdate':
        $orderby = 'i.created DESC';
        break;
      case 'alpha':
        $orderby = 'i.title';
        break;
      case 'ralpha':
        $orderby = 'i.title DESC';
        break;
      case 'order':
        if ($params->get('itemFilter') == 'feat')
          $orderby = 'i.featured_ordering';
        else
          $orderby = 'i.ordering';
        break;
      case 'hits':
        $orderby = 'i.hits DESC';
        break;
      case 'rand':
        $orderby = 'RAND()';
        break;
      case 'best':
        $orderby = 'rating DESC';
        break;
      default:
        $orderby = 'i.id DESC';
        break;
    }
    $query .= " ORDER BY ".$orderby;
    $db->setQuery($query, 0, $limit);
    $items = $db->loadObjectList();
	require_once (JPATH_SITE.DS.'components'.DS.'com_k2'.DS.'models'.DS.'item.php');
	$model = new K2ModelItem;
	require_once (JPATH_SITE.DS.'components'.DS.'com_k2'.DS.'helpers'.DS.'route.php');
    if (count($items)) {
      	$k2ImageSource = $params->get('displayImages','k2content');
		foreach ($items as $item) {
        //Images
		$item->firstImage = "";
		if($k2ImageSource == "k2item")
		{
			if (JFile::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'src'.DS.md5("Image".$item->id).'.jpg'))
	            $item->imageOriginal = 'media/k2/items/src/'.md5("Image".$item->id).'.jpg';
			if (JFile::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_XS.jpg'))
	            $item->imageXSmall = 'media/k2/items/cache/'.md5("Image".$item->id).'_XS.jpg';
          if (JFile::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_S.jpg'))
            $item->imageSmall = 'media/k2/items/cache/'.md5("Image".$item->id).'_S.jpg';
          if (JFile::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_M.jpg'))
            $item->imageMedium = 'media/k2/items/cache/'.md5("Image".$item->id).'_M.jpg';
          if (JFile::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_L.jpg'))
            $item->imageLarge = 'media/k2/items/cache/'.md5("Image".$item->id).'_L.jpg';
          if (JFile::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_XL.jpg'))
            $item->imageXLarge = 'media/k2/items/cache/'.md5("Image".$item->id).'_XL.jpg';
          if (JFile::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_Generic.jpg'))
            $item->imageGeneric = 'media/k2/items/cache/'.md5("Image".$item->id).'_Generic.jpg';
        $image = 'image'.$params->get('itemImageSize');
            $item->firstImage = $item->$image;
		}
		elseif($k2ImageSource == "k2content")
		{
			$imghtml= $item->introtext;
			$imghtml .= "alt='...' title='...' />";
			$pattern = '/<img[^>]+src[\\s=\'"]';
			$pattern .= '+([^"\'>\\s]+)/is';
			if(preg_match(
			$pattern,
			$imghtml,
			$match))
			$item->firstImage = "$match[1]";
			else $item->firstImage = "";
		}
        $item->numOfComments = $model->countItemComments($item->id);
        //Read more link
        if($linkTarget == 'article'){$item->link = urldecode(JRoute::_(K2HelperRoute::getItemRoute($item->id.':'.urlencode($item->alias), $item->catid.':'.urlencode($item->categoryalias))));
}else{
$item->link = urldecode(JRoute::_(K2HelperRoute::getCategoryRoute($item->catid.':'.urlencode($item->categoryalias))));
}
       // Item text
		$item->text = $item->title;
		$item->introtext = $stripTags ? self::_cleanIntrotext($item->introtext,$tags) : $item->introtext;
		$item->introtext = $wordCount ? self::string_limit_words($item->introtext, $wordCount, $introSuffix) : $item->introtext;
		$item->video = $item->video;
		$item->metakey = $item->metakey;
		$item->catname = $item->categoryname;
		// Date Variables
		if (!$translateDate) {
		$item->dateCreated = date($dateFormat, (strtotime($item->created))); 
		}
		else {
			$item->dateCreated = JHTML::Date($item->date, JText::_(''.$dateString.'')); 	
		}
		$item->catlink = urldecode(JRoute::_(K2HelperRoute::getCategoryRoute($item->catid.':'.urlencode($item->categoryalias))));
        $rows[] = $item;
      }
      return $rows;
    }
  }
	public static function _cleanIntrotext($introtext,$tags)
	{
		//$introtext = str_replace('<p>', ' ', $introtext);
		//$introtext = str_replace('</p>', ' ', $introtext);
		$introtext = strip_tags($introtext, $tags);

		$introtext = trim($introtext);

		return $introtext;
	}
	
	public static function string_limit_words($introText, $wordCount, $suffixChar='&hellip;') 
	{
	     $introText = trim($introText); 
		 $id = explode(' ', $introText);
		 $suffix = count($id) <= $wordCount ? '' : $suffixChar;
	     return implode(' ', array_slice($id, 0, $wordCount)) . $suffix;
	 }
	
	/**
	* This is a better truncate implementation than what we
	* currently have available in the library. In particular,
	* on index.php/Banners/Banners/site-map.html JHtml's truncate
	* method would only return "Article...". This implementation
	* was taken directly from the Stack Overflow thread referenced
	* below. It was then modified to return a string rather than
	* print out the output and made to use the relevant JString
	* methods.
	*
	* @link http://stackoverflow.com/questions/1193500/php-truncate-html-ignoring-tags
	* @param mixed $html
	* @param mixed $maxLength
	*/
	public static function truncate($html, $maxLength = 0, $suffixChar='&hellip;')
	{
		$printedLength = 0;
		$position = 0;
		$tags = array();
		$suffix = '';
		$output = '';
		
		if((JString::strlen($html)) > ($maxLength+1)){
			$suffix = $suffixChar;
		}
			
		if (empty($html)) {
			return $output;
		}

		while ($printedLength < $maxLength && preg_match('{</?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;}', $html, $match, PREG_OFFSET_CAPTURE, $position))
		{
			list($tag, $tagPosition) = $match[0];

			// Print text leading up to the tag.
			$str = JString::substr($html, $position, $tagPosition - $position);
			if ($printedLength + JString::strlen($str) > $maxLength) {
				$output .= JString::substr($str, 0, $maxLength - $printedLength);
				$printedLength = $maxLength;
				break;
			}

			$output .= $str;
			$lastCharacterIsOpenBracket = (JString::substr($output, -1, 1) === '<');

			if ($lastCharacterIsOpenBracket) {
				$output = JString::substr($output, 0, JString::strlen($output) - 1);
			}

			$printedLength += JString::strlen($str);

			if ($tag[0] == '&') {
				// Handle the entity.
				$output .= $tag;
				$printedLength++;
			}
			else {
				// Handle the tag.
				$tagName = $match[1][0];

				if ($tag[1] == '/') {
					// This is a closing tag.
					$openingTag = array_pop($tags);

					$output .= $tag;
				}
				else if ($tag[JString::strlen($tag) - 2] == '/') {
					// Self-closing tag.
					$output .= $tag;
				}
				else {
					// Opening tag.
					$output .= $tag;
					$tags[] = $tagName;
				}
			}

			// Continue after the tag.
			if ($lastCharacterIsOpenBracket) {
				$position = ($tagPosition - 1) + JString::strlen($tag);
			}
			else {
				$position = $tagPosition + JString::strlen($tag);
			}

		}

		// Print any remaining text.
		if ($printedLength < $maxLength && $position < JString::strlen($html)) {
			$output .= JString::substr($html, $position, $maxLength - $printedLength);
		}

		$output .= $suffix;
		// Close any open tags.
		while (!empty($tags))
		{
			$output .= sprintf('</%s>', array_pop($tags));
		}

		$length = JString::strlen($output);
		$lastChar = JString::substr($output, ($length - 1), 1);
		$characterNumber = ord($lastChar);

		if ($characterNumber === 194) {
			$output = JString::substr($output, 0, JString::strlen($output) - 1);
		}

		$output = JString::rtrim($output);

		return $output;
	}
}
