Example #1
1
	function onBeforeDisplayContent( &$article, &$params, $limitstart ){
		//this may fire fron a component other than com_content
		
		if(!file_exists(JPATH_SITE.DS.'plugins'.DS.'system'.DS.'myApiConnectFacebook.php') || ( !array_key_exists('category',$article) && !array_key_exists('showK2Plugins',$params)  )){ return; }
		
		if((@$article->id != '') && (@$_POST['fb_sig_api_key'] == '') && class_exists('plgSystemmyApiOpenGraph')){
			$row = & JTable::getInstance('content');
			$row->load($article->id);
			$attribs = new JParameter($row->attribs);
			if($attribs->get('ogimage','') == ''){
				$attribs->set('ogimage',plgContentmyApiOpenGraphContent::getContentImage($article->text));
				$row->attribs = $attribs->toString();
				$row->bind($row);
				$row->store();
			}
			//Set open graph tags
			if(JRequest::getVar('view','','get') == 'article' || (JRequest::getVar('option','','get') == 'com_k2' && JRequest::getVar('view','','get') == 'item')){
				if(isset($article->slug)){
					require_once(JPATH_SITE.DS.'components'.DS.'com_content'.DS.'helpers'.DS.'route.php');
					$link = ContentHelperRoute::getArticleRoute($article->slug, $article->catslug, $article->sectionid);
				}elseif(method_exists('K2HelperRoute','getItemRoute')){
					$link = K2HelperRoute::getItemRoute($article->id.':'.urlencode($article->alias),$article->catid.':'.urlencode($article->category->alias));
				}else{
					error_log('myApi unable to calculate link for the article id '.$article->id);
					return;
				}
				$u =& JURI::getInstance( JURI::base().$link );
				$port 	= ($u->getPort() == '') ? '' : ":".$u->getPort();
				$articleURL = 'http://'.$u->getHost().$port.$u->getPath().'?'.$u->getQuery();
				$rawText = strip_tags($article->introtext);
				$newTags = array();
				$newTags['og:title'] 		= $article->title;
				$newTags['og:description'] 	= (strlen($rawText) > 247) ? substr($rawText,0,247).'...' : $rawText;
				$newTags['og:type']	= 'article';
				$newTags['og:author']	= (is_object($article->author)) ? $article->author->name : $article->author;
				$newTags['og:url'] 	= $articleURL;
				if($attribs->get('ogimage','0') != '0') $newTags['og:image'] = $attribs->get('ogimage');
				
				plgSystemmyApiOpenGraph::setTags($newTags);
			}
		}
	}
Example #2
0
 /** I HAVE NOT MODIFIED BELOW THIS LINE **/
 function getItems($args)
 {
     global $mainframe;
     $advlink =& AdvLink::getInstance();
     require_once JPATH_SITE . DS . 'components' . DS . 'com_k2' . DS . 'helpers' . DS . 'route.php';
     $items = array();
     $view = isset($args->view) ? $args->view : '';
     switch ($view) {
         default:
             $categories = AdvlinkK2::_getK2Categories();
             foreach ($categories as $category) {
                 $items[] = array('id' => K2HelperRoute::getCategoryRoute($category->id), 'name' => $category->name, 'class' => 'folder content');
             }
             break;
         case 'itemlist':
             $categories = AdvlinkK2::_getK2Categories($args->id);
             $itemlist = AdvlinkK2::_getK2Items($args->id);
             foreach ($categories as $category) {
                 $items[] = array('id' => K2HelperRoute::getCategoryRoute($category->id), 'name' => $category->name, 'class' => 'folder content');
             }
             foreach ($itemlist as $item) {
                 $items[] = array('id' => K2HelperRoute::getItemRoute($item->id, $args->id), 'name' => $item->title, 'class' => 'file');
             }
             break;
         case 'item':
             break;
     }
     return $items;
 }
Example #3
0
 private static function _getCurrentItemURL($article)
 {
     require_once JPATH_SITE . '/components/com_k2/helpers/route.php';
     $url = K2HelperRoute::getItemRoute($article->id . ":" . urlencode($article->alias), $article->catid);
     $url = SCArticleContent::_getCompleteURL($url);
     return $url;
 }
Example #4
0
 public static function getAssociations($id = 0, $view = null)
 {
     jimport('helper.route', JPATH_COMPONENT_SITE);
     $application = JFactory::getApplication();
     $view = is_null($view) ? $application->input->get('view') : $view;
     $task = $application->input->get('task');
     $id = empty($id) ? $application->input->getInt('id') : $id;
     if ($view == 'item') {
         if ($id) {
             $associations = self::getItemAssociations($id);
             $return = array();
             foreach ($associations as $tag => $item) {
                 $return[$tag] = K2HelperRoute::getItemRoute($item->id, $item->catid, $item->language);
             }
             return $return;
         }
     } else {
         if ($view == 'itemlist' && $task == 'category') {
             if ($id) {
                 $associations = self::getCategoryAssociations($id);
                 $return = array();
                 foreach ($associations as $tag => $category) {
                     $return[$tag] = K2HelperRoute::getCategoryRoute($category->id, $category->language);
                 }
                 return $return;
             }
         }
     }
     return array();
 }
Example #5
0
 /**
  * Prepare item properties
  */
 protected function _prepareItem($item)
 {
     $item->link = JRoute::_(K2HelperRoute::getItemRoute($item->id, $item->catid));
     $item->introtext = JHtml::_('string.truncate', $item->introtext, $this->_params->get('intro_length', 200));
     $item->cat_link = urldecode(JRoute::_(K2HelperRoute::getCategoryRoute($item->catid . ':' . urlencode($item->catslug))));
     return $item;
 }
Example #6
0
 /**
  * Retrieves the profile link
  *
  * @since	5.0
  * @access	public
  * @param	string
  * @return	
  */
 public function getLink()
 {
     if (!$this->exists()) {
         return parent::getLink();
     }
     $link = K2HelperRoute::getUserRoute($this->profile->id);
     return $link;
 }
Example #7
0
function com_k2_get_url(&$article, $isNew)
{
    $url = null;
    $helperPath = dirname(__FILE__) . "/../../../../../components/com_k2/helpers/route.php";
    if (is_file($helperPath)) {
        require_once $helperPath;
        $helper = new K2HelperRoute();
        $url = $helper->getItemRoute($article->id, $article->catid);
        $app = JApplication::getInstance('site');
        $router =& $app->getRouter();
        $uri = $router->build($url);
        $url = $uri->toString();
        if (strpos($url, "/administrator") === 0) {
            $url = substr($url, strlen("/administrator"));
        }
    }
    return $url;
}
Example #8
0
 function getTagRoute($tag)
 {
     $needles = array('tag' => $tag);
     $link = 'index.php?option=com_k2&view=itemlist&task=tag&tag=' . urlencode($tag);
     if ($item = K2HelperRoute::_findItem($needles)) {
         $link .= '&Itemid=' . $item->id;
     }
     return $link;
 }
Example #9
0
 function get_link($num)
 {
     if ($this->mode == 'com_content') {
         return $this->parent->content[$num]['id'] != 0 ? JRoute::_(ContentHelperRoute::getArticleRoute($this->parent->content[$num]['id'], $this->parent->content[$num]['cid'])) : JRoute::_('index.php?option=com_users&view=login');
     } else {
         if ($this->mode == 'com_k2') {
             //
             require_once JPATH_SITE . DS . 'components' . DS . 'com_k2' . DS . 'helpers' . DS . 'route.php';
             //
             return urldecode(JRoute::_(K2HelperRoute::getItemRoute($this->parent->content[$num]['id'] . ':' . urlencode($this->parent->content[$num]['alias']), $this->parent->content[$num]['cid'] . ':' . urlencode($this->parent->content[$num]['cat_alias']))));
         } else {
             return false;
         }
     }
 }
 public function getChildCategories($catId, $titleMax)
 {
     $categories = array();
     $query = "\n\t\t\t\tSELECT c.id, c.name as title, c.alias\n\t\t\t\tFROM #__k2_categories c\n\t\t\t\tWHERE\n\t\t\t\t\tc.published = 1\n\t\t\t\t\tAND c.parent = {$catId}\n\t\t\t";
     $this->db->setQuery($query);
     $rows = $this->db->loadObjectList();
     foreach ($rows as $category) {
         $categories[$category->id] = $category;
         // // category url
         // $slug = $category->alias ? $category->id.':'.$category->alias : $category->id;
         // $category->url = JRoute::_( ContentHelperRoute::getCategoryRoute($slug) );
         $category->url = urldecode(JRoute::_(K2HelperRoute::getCategoryRoute($category->id . ':' . urlencode($category->alias))));
         // category title truncate
         $category->title = YtUtils::shorten($category->title, $titleMax);
     }
     return $categories;
 }
Example #11
0
 function getObjectInfo($id, $language = null)
 {
     $info = new JCommentsObjectInfo();
     $routerHelper = JPATH_SITE . '/components/com_k2/helpers/route.php';
     if (is_file($routerHelper)) {
         require_once $routerHelper;
         $db = JFactory::getDBO();
         $query = "SELECT i.id, i.title, i.catid, i.alias, i.access, i.created_by, c.alias as catalias" . " FROM #__k2_items as i" . " LEFT JOIN #__k2_categories as c ON c.id=i.catid" . " WHERE i.id = " . $id;
         $db->setQuery($query);
         $row = $db->loadObject();
         if (!empty($row)) {
             $info->title = $row->title;
             $info->access = $row->access;
             $info->userid = $row->created_by;
             $info->link = JRoute::_(K2HelperRoute::getItemRoute($row->id . ':' . urlencode($row->alias), $row->catid . ':' . urlencode($row->catalias)));
         }
     }
     return $info;
 }
Example #12
0
 function get_link($num)
 {
     if ($this->mode == 'com_content') {
         return $this->parent->content[$num]['id'] != 0 ? JRoute::_(ContentHelperRoute::getArticleRoute($this->parent->content[$num]['id'], $this->parent->content[$num]['cid'])) : JRoute::_('index.php?option=com_users&view=login');
     } else {
         if ($this->mode == 'com_k2') {
             //
             require_once JPATH_SITE . DS . 'components' . DS . 'com_k2' . DS . 'helpers' . DS . 'route.php';
             //
             return urldecode(JRoute::_(K2HelperRoute::getItemRoute($this->parent->content[$num]['id'] . ':' . urlencode($this->parent->content[$num]['alias']), $this->parent->content[$num]['cid'] . ':' . urlencode($this->parent->content[$num]['cat_alias']))));
         } else {
             if ($this->mode == 'com_virtuemart') {
                 $itemid = $this->parent->config['vm_itemid'];
                 $link = 'index.php?option=com_virtuemart&view=productdetails&virtuemart_product_id=' . $this->parent->content[$num]['id'] . '&virtuemart_category_id=' . $this->parent->content[$num]['cid'] . '&Itemid=' . $itemid;
                 //
                 return $link;
             } else {
                 return false;
             }
         }
     }
 }
Example #13
0
 public function go($allGet)
 {
     $uri = JUri::getInstance();
     $currentLink = $uri->toString(array('path', 'query'));
     $start = JFactory::getApplication()->input->getInt('start', 0);
     JTable::addIncludePath(JPATH_ROOT . '/administrator/components/com_k2/tables');
     $limitstring = '';
     if ($start > 0) {
         $limits = $this->params->get('limits', 5);
         if ($start % $limits != 0) {
             $start = intval($start / $limits) * $limits;
         }
         $limitstring .= "?start=" . $start;
     }
     if ($allGet['view'] == 'item' && $allGet['task'] == '') {
         $item = JTable::getInstance('K2Item', 'Table');
         $item->load($allGet['id']);
         $category = JTable::getInstance('K2Category', 'Table');
         $category->load($item->catid);
         $original_link = JRoute::_(K2HelperRoute::getItemRoute($item->id . ':' . urlencode($item->alias), $item->catid . ':' . urlencode($category->alias)), false);
     } else {
         if ($allGet['view'] == 'itemlist' && $allGet['task'] == 'category') {
             $category = JTable::getInstance('K2Category', 'Table');
             $category->load((int) $allGet['id']);
             $original_link = JRoute::_(K2HelperRoute::getCategoryRoute((int) $allGet['id'] . ':' . urlencode($category->alias)), false) . $limitstring;
         } else {
             if ($allGet['view'] == 'itemlist' && $allGet['task'] == 'user') {
                 $original_link = JRoute::_(K2HelperRoute::getUserRoute((int) $allGet['id']), false) . $limitstring;
             } else {
                 return false;
             }
         }
     }
     if ($original_link && $original_link != $currentLink) {
         $this->shRedirect($original_link);
     }
     return true;
 }
Example #14
0
 private function format(&$items, $params)
 {
     if (!$items) {
         return;
     }
     // Add K2's table path
     JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_k2/tables');
     foreach ($items as $item) {
         $category = JTable::getInstance('K2Category', 'Table');
         $category->load($item->catid);
         $item->category = $category;
         $item->permalink = K2HelperRoute::getItemRoute($item->id . ':' . $item->alias, $item->catid);
         $item->category->permalink = K2HelperRoute::getCategoryRoute($category->id . ':' . $category->alias);
         $item->content = empty($item->introtext) ? $item->fulltext : $item->introtext;
         $titleLength = $params->get('title_length');
         $contentLength = $params->get('content_length');
         if ($titleLength) {
             $item->title = JString::substr($item->title, 0, $titleLength);
         }
         if ($contentLength) {
             $item->content = JString::substr(strip_tags($item->content), 0, $contentLength);
         }
     }
 }
Example #15
0
 /**
  * get the list of k2 items
  * 
  * @param JParameter $params;
  * @return Array
  */
 public function __getList($params)
 {
     global $mainframe;
     $maxTitle = $params->get('max_title', '100');
     $maxDesciption = $params->get('max_description', 100);
     $openTarget = $params->get('open_target', 'parent');
     $formatter = $params->get('style_displaying', 'title');
     $titleMaxChars = $params->get('title_max_chars', '100');
     $descriptionMaxChars = $params->get('description_max_chars', 100);
     $condition = $this->buildConditionQuery($params);
     $ordering = $params->get('k2_ordering', 'created_asc');
     $limit = $params->get('limit_items', 5);
     $ordering = str_replace('_', '  ', $ordering);
     $my =& JFactory::getUser();
     $aid = $my->get('aid', 0);
     $limitDescriptionBy = $params->get('limit_description_by', 'char');
     $thumbWidth = (int) $params->get('thumbnail_width', 35);
     $thumbHeight = (int) $params->get('thumbnail_height', 60);
     $imageHeight = (int) $params->get('main_height', 300);
     $imageWidth = (int) $params->get('main_width', 660);
     $isThumb = $params->get('auto_renderthumb', 1);
     $isStripedTags = $params->get('auto_strip_tags', 1);
     $extraURL = $params->get('open_target') != 'modalbox' ? '' : '&tmpl=component';
     $db =& JFactory::getDBO();
     $date =& JFactory::getDate();
     $now = $date->toMySQL();
     require_once JPath::clean(JPATH_SITE . '/components/com_k2/helpers/route.php');
     $query = "SELECT a.*, cr.rating_sum/cr.rating_count as rating, c.name as category_title,\n\t\t\t\t\t\t\tc.id as categoryid, c.alias as categoryalias, c.params as categoryparams, cc.commentcount as commentcount" . " FROM #__k2_items as a" . " LEFT JOIN #__k2_categories c ON c.id = a.catid" . " LEFT JOIN #__k2_rating as cr ON a.id = cr.itemid" . " LEFT JOIN (select cm.itemid  as id, count(cm.id) as commentcount from #__k2_comments as cm\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhere cm.published=1 group by cm.itemid) as cc on a.id = cc.id";
     $query .= " WHERE a.published = 1" . " AND a.access IN (" . implode(',', $my->authorisedLevels()) . ")" . " AND a.trash = 0";
     if ($params->get('featured_items_show', '0') == 0) {
         $query .= " AND a.featured != 1";
     } elseif ($params->get('featured_items_show', '0') == 2) {
         $query .= " AND a.featured = 1";
     }
     $query .= $condition . ' ORDER BY ' . $ordering;
     $query .= $limit ? ' LIMIT ' . $limit : '';
     $db->setQuery($query);
     $data = $db->loadObjectlist();
     if (empty($data)) {
         return array();
     }
     foreach ($data as $key => &$item) {
         $item->link = JRoute::_(K2HelperRoute::getItemRoute($item->id . ':' . $item->alias, $item->catid . ':' . $item->categoryalias) . $extraURL);
         $item->date = JHtml::_('date', $item->created, JText::_('DATE_FORMAT_LC2'));
         $item->subtitle = $this->substring($item->title, $titleMaxChars);
         if ($limitDescriptionBy == 'word') {
             $string = preg_replace("/\\s+/", " ", strip_tags($item->introtext));
             $tmp = explode(" ", $string);
             $item->description = $descriptionMaxChars > count($tmp) ? $string : implode(" ", array_slice($tmp, 0, $descriptionMaxChars));
         } else {
             $item->description = self::substring($item->introtext, $descriptionMaxChars, '', $isStripedTags);
         }
         $item->rating = is_numeric($item->rating) ? floatval($item->rating / 5 * 100) : null;
         $item->author = $item->created_by;
         $item = $this->generateImages($item, $isThumb);
         $item->categoryLink = urldecode(JRoute::_(K2HelperRoute::getCategoryRoute($item->catid . ':' . urlencode($item->categoryalias))));
         if ($params->get('itemAuthor')) {
             if (!empty($item->created_by_alias)) {
                 $item->author = $item->created_by_alias;
                 $item->authorGender = NULL;
             } else {
                 $author =& JFactory::getUser($item->created_by);
                 $item->author = $author->name;
                 $query = "SELECT `gender` FROM #__k2_users WHERE userID=" . (int) $author->id;
                 $db->setQuery($query, 0, 1);
                 $item->authorGender = $db->loadResult();
                 //Author Link
                 $item->authorLink = JRoute::_(K2HelperRoute::getUserRoute($item->created_by));
             }
         }
     }
     return $data;
 }
Example #16
0
	/**
	 * @param  int|TableInterface  $row
	 * @param  bool                $htmlspecialchars
	 * @param  string              $type
	 * @return string
	 */
	static public function getUrl( $row, $htmlspecialchars = true, $type = 'article' )
	{
		global $_CB_framework;

		$plugin				=	cbconsultationsClass::getPlugin();

		if ( is_integer( $row ) ) {
			$row			=	new cbconsultationsconsultationTable();

			$row->load( (int) $row );
		}

		$category			=	$row->getCategory();

		/** @noinspection PhpIncludeInspection */
		require_once ( $_CB_framework->getCfg( 'absolute_path' ) . '/components/com_k2/helpers/route.php' );

		$categorySlug		=	$row->get( 'catid' ) . ( $category->get( 'alias' ) ? ':' . $category->get( 'alias' ) : null );
		$articleSlug		=	$row->get( 'id' ) . ( $row->get( 'alias' ) ? ':' . $row->get( 'alias' ) : null );

		switch ( $type ) {
			case 'section':
				/** @noinspection PhpUndefinedClassInspection */
				$url		=	K2HelperRoute::getCategoryRoute( $plugin->params->get( 'consultation_section', null ) );
				break;
			case 'category':
				/** @noinspection PhpUndefinedClassInspection */
				$url		=	K2HelperRoute::getCategoryRoute( $categorySlug );
				break;
			case 'article':
			default:
			/** @noinspection PhpUndefinedClassInspection */
				$url		=	K2HelperRoute::getItemRoute( $articleSlug, $categorySlug );
				break;
		}

		if ( ! stristr( $url, 'Itemid' ) ) {
			$url			=	$_CB_framework->getCfg( 'live_site' ) . '/' . $url;
		} else {
			$url			=	JRoute::_( $url, false );
		}

		if ( $url ) {
			if ( $htmlspecialchars ) {
				$url		=	htmlspecialchars( $url );
			}
		}

		return $url;
	}
Example #17
0
	function onBeforeDisplayContent( &$article, &$params, $limitstart ){
		if(!file_exists(JPATH_SITE.DS.'plugins'.DS.'system'.DS.'myApiConnectFacebook.php') || (!array_key_exists('category',$article) && !isset($params->showK2Plugins)  )){ return; }
		
		//this may fire fron a component other than com_content
		if((@$article->id != '') && (@$_POST['fb_sig_api_key'] == '')){
			$doc = & JFactory::getDocument();
			
			$plugin = & JPluginHelper::getPlugin('content', 'myApiSend');

			// Load plugin params info
			$myapiparama = new JParameter($plugin->params);
			
			$send_sections 		= $myapiparama->get('send_sections');
			$send_categories 	= $myapiparama->get('send_categories');
			$send_show_on 		= $myapiparama->get('send_show_on');
			$layout_style 		= $myapiparama->get('layout_style');
			$show_faces 		= $myapiparama->get('show_faces');
			$color_scheme 		= $myapiparama->get('color_scheme');
			$verb 				= $myapiparama->get('verb');
			$width 				= $myapiparama->get('width');
			$send_style 		= $myapiparama->get('send_style');
			$font 				= $myapiparama->get('send_font');
			$ref 				= $myapiparama->get('send_ref');
			$show_send 			= $myapiparama->get('send_send');
			$position			= $myapiparama->get('position','myApiShareTop');
			$send_show 			= false;
		
			$facebook = plgSystemmyApiConnect::getFacebook();
			
			if(isset($article->sectionid)){
				if( is_array($send_sections) ){	
					foreach($send_sections as $id){ if($id == $article->sectionid) $send_show = true;  }
				}
				elseif($send_sections == $article->sectionid) $send_show = true;
			}
			
			if(isset($article->category)){
				if( is_array($send_categories) ){	
					foreach($send_categories as $id){ if($id == $article->category) $send_show = true; }
				}
				elseif($send_categories == $article->category) $send_show = true;
			}
			
			if(($send_show) || ($send_show_on == 'all')){
				require_once(JPATH_SITE.DS.'components'.DS.'com_content'.DS.'helpers'.DS.'route.php');
				
				if(isset($article->slug)){
					require_once(JPATH_SITE.DS.'components'.DS.'com_content'.DS.'helpers'.DS.'route.php');
					$link = ContentHelperRoute::getArticleRoute($article->slug, $article->catslug, $article->sectionid);
				}elseif(method_exists('K2HelperRoute','getItemRoute')){
					$link = K2HelperRoute::getItemRoute($article->id.':'.urlencode($article->alias),$article->catid.':'.urlencode($article->category->alias));
				}else{
					error_log('myApi unable to calculate link for the article id '.$article->id);
					return;
				}
				$u =& JURI::getInstance( JURI::base().$link );
				$port 	= ($u->getPort() == '') ? '' : ":".$u->getPort();
				$link = 'http://'.$u->getHost().$port.$u->getPath().'?'.$u->getQuery();
				$button	= '<fb:send href="'.$link.'" colorscheme="'.$color_scheme.'" font="'.$font.'" ref="'.$ref.'"></fb:send>';
		
				require_once(JPATH_SITE.DS.'plugins'.DS.'system'.DS.'myApiDom.php');
				$article->text = myApiButtons::addToTable($article->text,$position,$button);
			}
		}
	}
Example #18
0
    function display($tpl = null)
    {
        $mainframe =& JFactory::getApplication();
        $user =& JFactory::getUser();
        $document =& JFactory::getDocument();
        $params =& JComponentHelper::getParams('com_k2');
        $limitstart = JRequest::getInt('limitstart', 0);
        $view = JRequest::getWord('view');
        $task = JRequest::getWord('task');
        $db =& JFactory::getDBO();
        $jnow =& JFactory::getDate();
        $now = $jnow->toMySQL();
        $nullDate = $db->getNullDate();
        $this->setLayout('item');
        //Add link
        if (K2HelperPermissions::canAddItem()) {
            $addLink = JRoute::_('index.php?option=com_k2&view=item&task=add&tmpl=component');
        }
        $this->assignRef('addLink', $addLink);
        //Get item
        $model =& $this->getModel();
        $item = $model->getData();
        //Prepare item
        if ($user->guest) {
            $cache =& JFactory::getCache('com_k2_extended');
            $hits = $item->hits;
            $item->hits = 0;
            $item = $cache->call(array('K2ModelItem', 'prepareItem'), $item, $view, $task);
            $item->hits = $hits;
        } else {
            $item = $model->prepareItem($item, $view, $task);
        }
        //Plugins
        $item = $model->execPlugins($item, $view, $task);
        //Access check
        if ($this->getLayout() == 'form') {
            JError::raiseError(403, JText::_("ALERTNOTAUTH"));
        }
        if ($item->access > $user->get('aid', 0) || $item->category->access > $user->get('aid', 0)) {
            JError::raiseError(403, JText::_("ALERTNOTAUTH"));
        }
        //Published check
        if (!$item->published || $item->trash) {
            JError::raiseError(404, JText::_("Item not found"));
        }
        if ($item->publish_up != $nullDate && $item->publish_up > $now) {
            JError::raiseError(404, JText::_("Item not found"));
        }
        if ($item->publish_down != $nullDate && $item->publish_down < $now) {
            JError::raiseError(404, JText::_("Item not found"));
        }
        if (!$item->category->published || $item->category->trash) {
            JError::raiseError(404, JText::_("Item not found"));
        }
        //Increase hits counter
        $model->hit($item->id);
        //Set default image
        K2HelperUtilities::setDefaultImage($item, $view);
        //Comments
        $item->event->K2CommentsCounter = '';
        $item->event->K2CommentsBlock = '';
        if ($item->params->get('itemComments')) {
            //Trigger comments events
            $dispatcher =& JDispatcher::getInstance();
            JPluginHelper::importPlugin('k2');
            $results = $dispatcher->trigger('onK2CommentsCounter', array(&$item, &$params, $limitstart));
            $item->event->K2CommentsCounter = trim(implode("\n", $results));
            $results = $dispatcher->trigger('onK2CommentsBlock', array(&$item, &$params, $limitstart));
            $item->event->K2CommentsBlock = trim(implode("\n", $results));
            //Load K2 native comments system only if there are no plugins overriding it
            if (empty($item->event->K2CommentsCounter) && empty($item->event->K2CommentsBlock)) {
                //Load reCAPTCHA script
                if (!JRequest::getInt('print') && ($item->params->get('comments') == '1' || $item->params->get('comments') == '2' && K2HelperPermissions::canAddComment($item->catid))) {
                    if ($item->params->get('recaptcha') && $user->guest) {
                        $document->addScript('http://api.recaptcha.net/js/recaptcha_ajax.js');
                        $js = 'function showRecaptcha(){
								    Recaptcha.create("' . $item->params->get('recaptcha_public_key') . '", "recaptcha", {
								        theme: "' . $item->params->get('recaptcha_theme', 'clean') . '"
								    });
								}
								window.addEvent(\'load\', function(){
									showRecaptcha();
								})';
                        $document->addScriptDeclaration($js);
                    }
                    //Auto complete some fields for registered users
                    if (!$user->guest) {
                        $js = "window.addEvent('domready', function(){\n\t\t\t\t\t\t\t\t\t\$('userName').setProperty('value','" . $user->name . "');\n\t\t\t\t\t\t\t\t\t\$('userName').setProperty('disabled','disabled');\n\t\t\t\t\t\t\t\t\t\$('commentEmail').setProperty('value','" . $user->email . "');\n\t\t\t\t\t\t\t\t\t\$('commentEmail').setProperty('disabled','disabled');\n\n\t\t\t\t\t\t\t\t})";
                        $document->addScriptDeclaration($js);
                    }
                }
                $limit = $params->get('commentsLimit');
                $comments = $model->getItemComments($item->id, $limitstart, $limit);
                $pattern = "@\\b(https?://)?(([0-9a-zA-Z_!~*'().&=+\$%-]+:)?[0-9a-zA-Z_!~*'().&=+\$%-]+\\@)?(([0-9]{1,3}\\.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+\\.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\\.[a-zA-Z]{2,6})(:[0-9]{1,4})?((/[0-9a-zA-Z_!~*'().;?:\\@&=+\$,%#-]+)*/?)@";
                for ($i = 0; $i < sizeof($comments); $i++) {
                    $comments[$i]->commentText = nl2br($comments[$i]->commentText);
                    $comments[$i]->commentText = preg_replace($pattern, '<a target="_blank" rel="nofollow" href="\\0">\\0</a>', $comments[$i]->commentText);
                    $comments[$i]->userImage = K2HelperUtilities::getAvatar($comments[$i]->userID, $comments[$i]->commentEmail, $params->get('commenterImgWidth'));
                    if ($comments[$i]->userID > 0) {
                        $comments[$i]->userLink = K2HelperRoute::getUserRoute($comments[$i]->userID);
                    } else {
                        $comments[$i]->userLink = $comments[$i]->commentURL;
                    }
                }
                $item->comments = $comments;
                jimport('joomla.html.pagination');
                $total = $item->numOfComments;
                $pagination = new JPagination($total, $limitstart, $limit);
            }
        }
        //Author's latest items
        if ($params->get('itemAuthorLatest') && $item->created_by_alias == '') {
            $model =& $this->getModel('itemlist');
            $authorLatestItems = $model->getAuthorLatest($item->id, $params->get('itemAuthorLatestLimit'), $item->created_by);
            if (count($authorLatestItems)) {
                for ($i = 0; $i < sizeof($authorLatestItems); $i++) {
                    $authorLatestItems[$i]->link = urldecode(JRoute::_(K2HelperRoute::getItemRoute($authorLatestItems[$i]->id . ':' . urlencode($authorLatestItems[$i]->alias), $authorLatestItems[$i]->catid . ':' . urlencode($authorLatestItems[$i]->categoryalias))));
                }
                $this->assignRef('authorLatestItems', $authorLatestItems);
            }
        }
        //Related items
        if ($params->get('itemRelated') && isset($item->tags) && count($item->tags)) {
            $model =& $this->getModel('itemlist');
            $relatedItems = $model->getRelatedItems($item->id, $item->tags, $params->get('itemRelatedLimit'));
            if (count($relatedItems)) {
                for ($i = 0; $i < sizeof($relatedItems); $i++) {
                    $relatedItems[$i]->link = urldecode(JRoute::_(K2HelperRoute::getItemRoute($relatedItems[$i]->id . ':' . urlencode($relatedItems[$i]->alias), $relatedItems[$i]->catid . ':' . urlencode($relatedItems[$i]->categoryalias))));
                }
                $this->assignRef('relatedItems', $relatedItems);
            }
        }
        //Navigation (previous and next item)
        if ($params->get('itemNavigation')) {
            $model =& $this->getModel('item');
            $nextItem = $model->getNextItem($item->id, $item->catid, $item->ordering);
            if (!is_null($nextItem)) {
                $item->nextLink = urldecode(JRoute::_(K2HelperRoute::getItemRoute($nextItem->id . ':' . urlencode($nextItem->alias), $nextItem->catid . ':' . urlencode($item->category->alias))));
                $item->nextTitle = $nextItem->title;
            }
            $previousItem = $model->getPreviousItem($item->id, $item->catid, $item->ordering);
            if (!is_null($previousItem)) {
                $item->previousLink = urldecode(JRoute::_(K2HelperRoute::getItemRoute($previousItem->id . ':' . urlencode($previousItem->alias), $previousItem->catid . ':' . urlencode($item->category->alias))));
                $item->previousTitle = $previousItem->title;
            }
        }
        // Absolute URL
        $uri =& JURI::getInstance();
        $item->absoluteURL = $uri->_uri;
        //Email link
        $item->emailLink = JRoute::_('index.php?option=com_mailto&tmpl=component&link=' . base64_encode($item->absoluteURL));
        //Twitter link
        if ($params->get('itemTwitterLink') && $params->get('twitterUsername')) {
            $itemURLForTwitter = $params->get('tinyURL') ? @file_get_contents('http://tinyurl.com/api-create.php?url=' . $item->absoluteURL) : $item->absoluteURL;
            $item->twitterURL = 'http://twitter.com/home/?status=' . urlencode('Reading @' . $params->get('twitterUsername') . ' ' . $item->title . ' ' . $itemURLForTwitter);
        }
        //Social link
        $item->socialLink = urlencode($item->absoluteURL);
        //Look for template files in component folders
        $this->_addPath('template', JPATH_COMPONENT . DS . 'templates');
        $this->_addPath('template', JPATH_COMPONENT . DS . 'templates' . DS . 'default');
        //Look for overrides in template folder (K2 template structure)
        $this->_addPath('template', JPATH_SITE . DS . 'templates' . DS . $mainframe->getTemplate() . DS . 'html' . DS . 'com_k2' . DS . 'templates');
        $this->_addPath('template', JPATH_SITE . DS . 'templates' . DS . $mainframe->getTemplate() . DS . 'html' . DS . 'com_k2' . DS . 'templates' . DS . 'default');
        //Look for overrides in template folder (Joomla! template structure)
        $this->_addPath('template', JPATH_SITE . DS . 'templates' . DS . $mainframe->getTemplate() . DS . 'html' . DS . 'com_k2' . DS . 'default');
        $this->_addPath('template', JPATH_SITE . DS . 'templates' . DS . $mainframe->getTemplate() . DS . 'html' . DS . 'com_k2');
        //Look for specific K2 theme files
        if ($item->params->get('theme')) {
            $this->_addPath('template', JPATH_COMPONENT . DS . 'templates' . DS . $item->params->get('theme'));
            $this->_addPath('template', JPATH_SITE . DS . 'templates' . DS . $mainframe->getTemplate() . DS . 'html' . DS . 'com_k2' . DS . 'templates' . DS . $item->params->get('theme'));
            $this->_addPath('template', JPATH_SITE . DS . 'templates' . DS . $mainframe->getTemplate() . DS . 'html' . DS . 'com_k2' . DS . $item->params->get('theme'));
        }
        //Assign data
        $this->assignRef('item', $item);
        $this->assignRef('user', $user);
        $this->assignRef('params', $item->params);
        $this->assignRef('pagination', $pagination);
        parent::display($tpl);
    }
Example #19
0
<?php
Example #20
0
        <?php 
if ($showCategories) {
    ?>
     
        <!--  CONTENT RIGHT OF THE BOX //-->	   
        <div class="lof-box-right">            
        	  <div class="lof-header"><span><?php 
    echo JTEXT::_('Topic');
    ?>
</span></div>                                                    
                <div class="lof-subcategories">
                    <?php 
    foreach ($categories as $cii => $category) {
        ?>
                        <p><a href="<?php 
        echo urldecode(JRoute::_(K2HelperRoute::getCategoryRoute($category->id . ':' . urlencode($category->alias))));
        ?>
"><?php 
        echo $category->name;
        ?>
</a></p>
                    <?php 
        if ($cii + 1 >= $maxCatsShowed) {
            break;
        }
    }
    ?>
                </div>
      	  </div>
          <!--  ENDCONTENT RIGHT OF THE BOX //--> 
          <?php 
Example #21
0
 public function getContentPermalink()
 {
     $link = '';
     if (JFactory::getApplication()->isSite()) {
         $link = K2HelperRoute::getItemRoute($this->_item->id . ':' . urlencode($this->_item->alias), $this->_item->catid . ':' . urlencode($this->_item->category_alias));
         $link = urldecode(JRoute::_($link));
     } else {
         $link = 'index.php?option=com_k2&view=item&id=' . $this->_item->id . $this->_getItemId();
     }
     $link = $this->prepareLink($link);
     return $link;
 }
Example #22
0
 function display($tpl = null)
 {
     $mainframe = JFactory::getApplication();
     $params = K2HelperUtilities::getParams('com_k2');
     $document = JFactory::getDocument();
     if (K2_JVERSION == '15') {
         $document->setMimeEncoding('application/json');
         $document->setType('json');
     }
     $model = $this->getModel('itemlist');
     //Set limit for model
     $limit = JRequest::getInt('limit');
     if ($limit > 100 || $limit == 0) {
         $limit = 100;
         JRequest::setVar('limit', $limit);
     }
     $page = JRequest::getInt('page');
     if ($page <= 0) {
         $limitstart = 0;
     } else {
         $page--;
         $limitstart = $page * $limit;
     }
     JRequest::setVar('limitstart', $limitstart);
     $view = JRequest::getWord('view');
     $task = JRequest::getWord('task');
     $response = new JObject();
     unset($response->_errors);
     // Site
     $response->site = new stdClass();
     $uri = JURI::getInstance();
     $response->site->url = $uri->toString(array('scheme', 'host', 'port'));
     $config = JFactory::getConfig();
     $response->site->name = K2_JVERSION == '30' ? $config->get('sitename') : $config->getValue('config.sitename');
     $moduleID = JRequest::getInt('moduleID');
     if ($moduleID) {
         $result = $model->getModuleItems($moduleID);
         $items = $result->items;
         $title = $result->title;
         $prefix = 'cat';
     } else {
         //Get data depending on task
         switch ($task) {
             case 'category':
                 //Get category
                 $id = JRequest::getInt('id');
                 JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . DS . 'tables');
                 $category = JTable::getInstance('K2Category', 'Table');
                 $category->load($id);
                 // State Check
                 if (!$category->published || $category->trash) {
                     JError::raiseError(404, JText::_('K2_CATEGORY_NOT_FOUND'));
                 }
                 //Access check
                 $user = JFactory::getUser();
                 if (K2_JVERSION != '15') {
                     if (!in_array($category->access, $user->getAuthorisedViewLevels())) {
                         JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
                     }
                     $languageFilter = $mainframe->getLanguageFilter();
                     $languageTag = JFactory::getLanguage()->getTag();
                     if ($languageFilter && $category->language != $languageTag && $category->language != '*') {
                         return;
                     }
                 } else {
                     if ($category->access > $user->get('aid', 0)) {
                         JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
                     }
                 }
                 //Merge params
                 $cparams = class_exists('JParameter') ? new JParameter($category->params) : new JRegistry($category->params);
                 if ($cparams->get('inheritFrom')) {
                     $masterCategory = JTable::getInstance('K2Category', 'Table');
                     $masterCategory->load($cparams->get('inheritFrom'));
                     $cparams = class_exists('JParameter') ? new JParameter($masterCategory->params) : new JRegistry($masterCategory->params);
                 }
                 $params->merge($cparams);
                 //Category link
                 $category->link = urldecode(JRoute::_(K2HelperRoute::getCategoryRoute($category->id . ':' . urlencode($category->alias))));
                 //Category image
                 $category->image = K2HelperUtilities::getCategoryImage($category->image, $params);
                 //Category plugins
                 $dispatcher = JDispatcher::getInstance();
                 JPluginHelper::importPlugin('content');
                 $category->text = $category->description;
                 if (K2_JVERSION != '15') {
                     $dispatcher->trigger('onContentPrepare', array('com_k2.category', &$category, &$params, $limitstart));
                 } else {
                     $dispatcher->trigger('onPrepareContent', array(&$category, &$params, $limitstart));
                 }
                 $category->description = $category->text;
                 //Category K2 plugins
                 $category->event->K2CategoryDisplay = '';
                 JPluginHelper::importPlugin('k2');
                 $results = $dispatcher->trigger('onK2CategoryDisplay', array(&$category, &$params, $limitstart));
                 $category->event->K2CategoryDisplay = trim(implode("\n", $results));
                 $category->text = $category->description;
                 $dispatcher->trigger('onK2PrepareContent', array(&$category, &$params, $limitstart));
                 $category->description = $category->text;
                 //Category children
                 $ordering = $params->get('subCatOrdering');
                 $children = $model->getCategoryFirstChildren($id, $ordering);
                 $subCategories = array();
                 if (count($children)) {
                     foreach ($children as $child) {
                         if ($params->get('subCatTitleItemCounter')) {
                             $child->numOfItems = $model->countCategoryItems($child->id);
                         }
                         $child->image = K2HelperUtilities::getCategoryImage($child->image, $params);
                         $child->link = urldecode(JRoute::_(K2HelperRoute::getCategoryRoute($child->id . ':' . urlencode($child->alias))));
                         unset($child->params);
                         unset($child->access);
                         unset($child->published);
                         unset($child->trash);
                         unset($child->language);
                         $subCategories[] = $child;
                     }
                 }
                 //Set featured flag
                 JRequest::setVar('featured', $params->get('catFeaturedItems'));
                 //Set title
                 $title = $category->name;
                 // Set ordering
                 if ($params->get('singleCatOrdering')) {
                     $ordering = $params->get('singleCatOrdering');
                 } else {
                     $ordering = $params->get('catOrdering');
                 }
                 // Set parameters prefix
                 $prefix = 'cat';
                 // Prepare the JSON category object;
                 $row = new JObject();
                 unset($row->_errors);
                 $row->id = $category->id;
                 $row->name = $category->name;
                 $row->alias = $category->alias;
                 $row->link = $category->link;
                 $row->parent = $category->parent;
                 $row->extraFieldsGroup = $category->extraFieldsGroup;
                 $row->image = $category->image;
                 $row->ordering = $category->ordering;
                 //$row->plugins = $category->plugins;
                 $row->events = $category->event;
                 $row->chidlren = $subCategories;
                 $response->category = $row;
                 break;
             case 'user':
                 //Get user
                 $id = JRequest::getInt('id');
                 $userObject = JFactory::getUser($id);
                 //Check user status
                 if ($userObject->block) {
                     JError::raiseError(404, JText::_('K2_USER_NOT_FOUND'));
                 }
                 //Get K2 user profile
                 $userObject->profile = $model->getUserProfile();
                 //User image
                 $userObject->avatar = K2HelperUtilities::getAvatar($userObject->id, $userObject->email, $params->get('userImageWidth'));
                 //User K2 plugins
                 $userObject->event->K2UserDisplay = '';
                 if (is_object($userObject->profile) && $userObject->profile->id > 0) {
                     $dispatcher = JDispatcher::getInstance();
                     JPluginHelper::importPlugin('k2');
                     $results = $dispatcher->trigger('onK2UserDisplay', array(&$userObject->profile, &$params, $limitstart));
                     $userObject->event->K2UserDisplay = trim(implode("\n", $results));
                     $userObject->profile->url = htmlspecialchars($userObject->profile->url, ENT_QUOTES, 'UTF-8');
                 }
                 //Set title
                 $title = $userObject->name;
                 // Set ordering
                 $ordering = $params->get('userOrdering');
                 // Set parameters prefix
                 $prefix = 'user';
                 // Prepare the JSON user object;
                 $row = new JObject();
                 unset($row->_errors);
                 //$row->id = $userObject->id;
                 $row->name = $userObject->name;
                 //$row->username = $userObject->username;
                 if (isset($userObject->profile->plugins)) {
                     unset($userObject->profile->plugins);
                 }
                 $row->profile = $userObject->profile;
                 $row->avatar = $userObject->avatar;
                 $row->events = $userObject->event;
                 $response->user = $row;
                 break;
             case 'tag':
                 //Set limit
                 $limit = $params->get('tagItemCount');
                 //set title
                 $title = JText::_('K2_DISPLAYING_ITEMS_BY_TAG') . ' ' . JRequest::getVar('tag');
                 // Set ordering
                 $ordering = $params->get('tagOrdering');
                 // Set parameters prefix
                 $prefix = 'tag';
                 $response->tag = JRequest::getVar('tag');
                 break;
             case 'search':
                 //Set title
                 $title = JText::_('K2_SEARCH_RESULTS_FOR') . ' ' . JRequest::getVar('searchword');
                 // Set parameters prefix
                 $prefix = 'generic';
                 $response->search = JRequest::getVar('searchword');
                 break;
             case 'date':
                 // Set title
                 if (JRequest::getInt('day')) {
                     $date = strtotime(JRequest::getInt('year') . '-' . JRequest::getInt('month') . '-' . JRequest::getInt('day'));
                     $dateFormat = K2_JVERSION == '15' ? '%A, %d %B %Y' : 'l, d F Y';
                     $title = JText::_('K2_ITEMS_FILTERED_BY_DATE') . ' ' . JHTML::_('date', $date, $dateFormat);
                 } else {
                     $date = strtotime(JRequest::getInt('year') . '-' . JRequest::getInt('month'));
                     $dateFormat = K2_JVERSION == '15' ? '%B %Y' : 'F Y';
                     $title = JText::_('K2_ITEMS_FILTERED_BY_DATE') . ' ' . JHTML::_('date', $date, $dateFormat);
                 }
                 // Set ordering
                 $ordering = 'rdate';
                 // Set parameters prefix
                 $prefix = 'generic';
                 $response->date = JHTML::_('date', $date, $dateFormat);
                 break;
             default:
                 $user = JFactory::getUser();
                 //Set limit
                 $limit = $params->get('num_leading_items') + $params->get('num_primary_items') + $params->get('num_secondary_items') + $params->get('num_links');
                 //Set featured flag
                 JRequest::setVar('featured', $params->get('catFeaturedItems'));
                 //Set title
                 $title = $params->get('page_title');
                 // Set ordering
                 $ordering = $params->get('catOrdering');
                 // Set parameters prefix
                 $prefix = 'cat';
                 break;
         }
         if (!isset($ordering)) {
             $items = $model->getData();
         } else {
             $items = $model->getData($ordering);
         }
     }
     //Prepare items
     $user = JFactory::getUser();
     $cache = JFactory::getCache('com_k2_extended');
     $model = JModelLegacy::getInstance('item', 'K2Model');
     $rows = array();
     for ($i = 0; $i < sizeof($items); $i++) {
         //Item group
         if ($task == "category" || $task == "") {
             $items[$i]->itemGroup = 'links';
             if ($i < $params->get('num_links') + $params->get('num_leading_items') + $params->get('num_primary_items') + $params->get('num_secondary_items')) {
                 $items[$i]->itemGroup = 'links';
             }
             if ($i < $params->get('num_secondary_items') + $params->get('num_leading_items') + $params->get('num_primary_items')) {
                 $items[$i]->itemGroup = 'secondary';
             }
             if ($i < $params->get('num_primary_items') + $params->get('num_leading_items')) {
                 $items[$i]->itemGroup = 'primary';
             }
             if ($i < $params->get('num_leading_items')) {
                 $items[$i]->itemGroup = 'leading';
             }
         } else {
             $items[$i]->itemGroup = '';
         }
         $itemParams = class_exists('JParameter') ? new JParameter($items[$i]->params) : new JRegistry($items[$i]->params);
         $itemParams->set($prefix . 'ItemIntroText', true);
         $itemParams->set($prefix . 'ItemFullText', true);
         $itemParams->set($prefix . 'ItemTags', true);
         $itemParams->set($prefix . 'ItemExtraFields', true);
         $itemParams->set($prefix . 'ItemAttachments', true);
         $itemParams->set($prefix . 'ItemRating', true);
         $itemParams->set($prefix . 'ItemAuthor', true);
         $itemParams->set($prefix . 'ItemImageGallery', true);
         $itemParams->set($prefix . 'ItemVideo', true);
         $itemParams->set($prefix . 'ItemImage', true);
         $items[$i]->params = $itemParams->toString();
         //Check if model should use cache for preparing item even if user is logged in
         if ($user->guest || $task == 'tag' || $task == 'search' || $task == 'date') {
             $cacheFlag = true;
         } else {
             $cacheFlag = true;
             if (K2HelperPermissions::canEditItem($items[$i]->created_by, $items[$i]->catid)) {
                 $cacheFlag = false;
             }
         }
         //Prepare item
         if ($cacheFlag) {
             $hits = $items[$i]->hits;
             $items[$i]->hits = 0;
             JTable::getInstance('K2Category', 'Table');
             $items[$i] = $cache->call(array($model, 'prepareItem'), $items[$i], $view, $task);
             $items[$i]->hits = $hits;
         } else {
             $items[$i] = $model->prepareItem($items[$i], $view, $task);
         }
         //Plugins
         $items[$i]->params->set('genericItemIntroText', $params->get('catItemIntroText'));
         $items[$i] = $model->execPlugins($items[$i], $view, $task);
         //Trigger comments counter event
         $dispatcher = JDispatcher::getInstance();
         JPluginHelper::importPlugin('k2');
         $results = $dispatcher->trigger('onK2CommentsCounter', array(&$items[$i], &$params, $limitstart));
         $items[$i]->event->K2CommentsCounter = trim(implode("\n", $results));
         // Set default image
         if ($task == 'user' || $task == 'tag' || $task == 'search' || $task == 'date') {
             $items[$i]->image = isset($items[$i]->imageGeneric) ? $items[$i]->imageGeneric : '';
         } else {
             if (!$moduleID) {
                 K2HelperUtilities::setDefaultImage($items[$i], $view, $params);
             }
         }
         $rows[] = $model->prepareJSONItem($items[$i]);
     }
     $response->items = $rows;
     // Prevent spammers from using the tag view
     if ($task == 'tag' && !count($response->items)) {
         $tag = JRequest::getString('tag');
         $db = JFactory::getDBO();
         $db->setQuery('SELECT id FROM #__k2_tags WHERE name = ' . $db->quote($tag));
         $tagID = $db->loadResult();
         if (!$tagID) {
             JError::raiseError(404, JText::_('K2_NOT_FOUND'));
             return false;
         }
     }
     // Output
     $json = json_encode($response);
     $callback = JRequest::getCmd('callback');
     if ($callback) {
         $document->setMimeEncoding('application/javascript');
         echo $callback . '(' . $json . ')';
     } else {
         echo $json;
     }
 }
Example #23
0
 protected function index(FinderIndexerResult $item, $format = 'html')
 {
     // Check if the extension is enabled
     if (JComponentHelper::isEnabled($this->extension) == false) {
         return;
     }
     // Initialize the item parameters.
     $registry = new JRegistry();
     $registry->loadString($item->params);
     $item->params = JComponentHelper::getParams('com_k2', true);
     $item->params->merge($registry);
     $registry = new JRegistry();
     $registry->loadString($item->metadata);
     $item->metadata = $registry;
     // Trigger the onContentPrepare event.
     $item->summary = FinderIndexerHelper::prepareContent($item->summary, $item->params);
     $item->body = FinderIndexerHelper::prepareContent($item->body, $item->params);
     // Build the necessary route and path information.
     $item->url = $this->getURL($item->id, $this->extension, $this->layout);
     $item->route = K2HelperRoute::getItemRoute($item->slug, $item->catslug);
     $item->path = FinderIndexerHelper::getContentPath($item->route);
     // Get the menu title if it exists.
     $title = $this->getItemMenuTitle($item->url);
     // Adjust the title if necessary.
     if (!empty($title) && $this->params->get('use_menu_title', true)) {
         $item->title = $title;
     }
     // Add the meta-author.
     $item->metaauthor = $item->metadata->get('author');
     // Add the meta-data processing instructions.
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metakey');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metadesc');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metaauthor');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'author');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'created_by_alias');
     // Translate the state. Articles should only be published if the category is published.
     $item->state = $this->translateState($item->state, $item->cat_state);
     // Translate the trash state. Articles should only be accesible if the category is accessible.
     if ($item->trash || $item->cat_trash) {
         $item->state = 0;
     }
     // Add the type taxonomy data.
     $item->addTaxonomy('Type', 'K2 Item');
     // Add the author taxonomy data.
     if (!empty($item->author) || !empty($item->created_by_alias)) {
         $item->addTaxonomy('Author', !empty($item->created_by_alias) ? $item->created_by_alias : $item->author);
     }
     // Add the category taxonomy data.
     $item->addTaxonomy('K2 Category', $item->category, $item->cat_state, $item->cat_access);
     // Add the language taxonomy data.
     $item->addTaxonomy('Language', $item->language);
     // Get content extras.
     FinderIndexerHelper::getContentExtras($item);
     // Index the item.
     FinderIndexer::index($item);
 }
Example #24
0
 function display($tpl = null)
 {
     $mainframe = JFactory::getApplication();
     $params = K2HelperUtilities::getParams('com_k2');
     $model = $this->getModel('itemlist');
     $limitstart = JRequest::getInt('limitstart');
     $view = JRequest::getWord('view');
     $task = JRequest::getWord('task');
     $db = JFactory::getDBO();
     // Add link
     if (K2HelperPermissions::canAddItem()) {
         $addLink = JRoute::_('index.php?option=com_k2&view=item&task=add&tmpl=component');
     }
     $this->assignRef('addLink', $addLink);
     // Get data depending on task
     switch ($task) {
         case 'category':
             // Get category
             $id = JRequest::getInt('id');
             JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . DS . 'tables');
             $category = JTable::getInstance('K2Category', 'Table');
             $category->load($id);
             $category->event = new stdClass();
             // State check
             if (!$category->published || $category->trash) {
                 JError::raiseError(404, JText::_('K2_CATEGORY_NOT_FOUND'));
             }
             // Access check
             $user = JFactory::getUser();
             if (K2_JVERSION != '15') {
                 if (!in_array($category->access, $user->getAuthorisedViewLevels())) {
                     if ($user->guest) {
                         $uri = JFactory::getURI();
                         $url = 'index.php?option=com_users&view=login&return=' . base64_encode($uri->toString());
                         $mainframe->redirect(JRoute::_($url, false), JText::_('K2_YOU_NEED_TO_LOGIN_FIRST'));
                     } else {
                         JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
                         return;
                     }
                 }
                 $languageFilter = $mainframe->getLanguageFilter();
                 $languageTag = JFactory::getLanguage()->getTag();
                 if ($languageFilter && $category->language != $languageTag && $category->language != '*') {
                     return;
                 }
             } else {
                 if ($category->access > $user->get('aid', 0)) {
                     if ($user->guest) {
                         $uri = JFactory::getURI();
                         $url = 'index.php?option=com_user&view=login&return=' . base64_encode($uri->toString());
                         $mainframe->redirect(JRoute::_($url, false), JText::_('K2_YOU_NEED_TO_LOGIN_FIRST'));
                     } else {
                         JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
                         return;
                     }
                 }
             }
             // Hide the add new item link if user cannot post in the specific category
             if (!K2HelperPermissions::canAddItem($id)) {
                 unset($this->addLink);
             }
             // Merge params
             $cparams = class_exists('JParameter') ? new JParameter($category->params) : new JRegistry($category->params);
             // Get the meta information before merging params since we do not want them to be inherited
             $category->metaDescription = $cparams->get('catMetaDesc');
             $category->metaKeywords = $cparams->get('catMetaKey');
             $category->metaRobots = $cparams->get('catMetaRobots');
             $category->metaAuthor = $cparams->get('catMetaAuthor');
             if ($cparams->get('inheritFrom')) {
                 $masterCategory = JTable::getInstance('K2Category', 'Table');
                 $masterCategory->load($cparams->get('inheritFrom'));
                 $cparams = class_exists('JParameter') ? new JParameter($masterCategory->params) : new JRegistry($masterCategory->params);
             }
             $params->merge($cparams);
             // Category link
             $category->link = urldecode(JRoute::_(K2HelperRoute::getCategoryRoute($category->id . ':' . urlencode($category->alias))));
             // Category image
             $category->image = K2HelperUtilities::getCategoryImage($category->image, $params);
             // Category plugins
             $dispatcher = JDispatcher::getInstance();
             JPluginHelper::importPlugin('content');
             $category->text = $category->description;
             if (K2_JVERSION != '15') {
                 $dispatcher->trigger('onContentPrepare', array('com_k2.category', &$category, &$params, $limitstart));
             } else {
                 $dispatcher->trigger('onPrepareContent', array(&$category, &$params, $limitstart));
             }
             $category->description = $category->text;
             // Category K2 plugins
             $category->event->K2CategoryDisplay = '';
             JPluginHelper::importPlugin('k2');
             $results = $dispatcher->trigger('onK2CategoryDisplay', array(&$category, &$params, $limitstart));
             $category->event->K2CategoryDisplay = trim(implode("\n", $results));
             $category->text = $category->description;
             $dispatcher->trigger('onK2PrepareContent', array(&$category, &$params, $limitstart));
             $category->description = $category->text;
             $this->assignRef('category', $category);
             $this->assignRef('user', $user);
             // Category children
             $ordering = $params->get('subCatOrdering');
             $children = $model->getCategoryFirstChildren($id, $ordering);
             if (count($children)) {
                 foreach ($children as $child) {
                     if ($params->get('subCatTitleItemCounter')) {
                         $child->numOfItems = $model->countCategoryItems($child->id);
                     }
                     $child->image = K2HelperUtilities::getCategoryImage($child->image, $params);
                     $child->name = htmlspecialchars($child->name, ENT_QUOTES);
                     $child->link = urldecode(JRoute::_(K2HelperRoute::getCategoryRoute($child->id . ':' . urlencode($child->alias))));
                     $subCategories[] = $child;
                 }
                 $this->assignRef('subCategories', $subCategories);
             }
             // Set limit
             $limit = $params->get('num_leading_items') + $params->get('num_primary_items') + $params->get('num_secondary_items') + $params->get('num_links');
             // Set featured flag
             JRequest::setVar('featured', $params->get('catFeaturedItems'));
             // Set layout
             $this->setLayout('category');
             // Set title
             $title = $category->name;
             $category->name = htmlspecialchars($category->name, ENT_QUOTES);
             // Set ordering
             if ($params->get('singleCatOrdering')) {
                 $ordering = $params->get('singleCatOrdering');
             } else {
                 $ordering = $params->get('catOrdering');
             }
             $addHeadFeedLink = $params->get('catFeedLink');
             break;
         case 'user':
             // Get user
             $id = JRequest::getInt('id');
             $userObject = JFactory::getUser($id);
             $userObject->event = new stdClass();
             // Check user status
             if ($userObject->block) {
                 JError::raiseError(404, JText::_('K2_USER_NOT_FOUND'));
             }
             // Get K2 user profile
             $userObject->profile = $model->getUserProfile();
             // User image
             $userObject->avatar = K2HelperUtilities::getAvatar($userObject->id, $userObject->email, $params->get('userImageWidth'));
             // User K2 plugins
             $userObject->event->K2UserDisplay = '';
             if (is_object($userObject->profile) && $userObject->profile->id > 0) {
                 $dispatcher = JDispatcher::getInstance();
                 JPluginHelper::importPlugin('k2');
                 $results = $dispatcher->trigger('onK2UserDisplay', array(&$userObject->profile, &$params, $limitstart));
                 $userObject->event->K2UserDisplay = trim(implode("\n", $results));
                 $userObject->profile->url = htmlspecialchars($userObject->profile->url, ENT_QUOTES, 'UTF-8');
             }
             $this->assignRef('user', $userObject);
             $date = JFactory::getDate();
             $now = K2_JVERSION == '15' ? $date->toMySQL() : $date->toSql();
             $this->assignRef('now', $now);
             // Set layout
             $this->setLayout('user');
             // Set limit
             $limit = $params->get('userItemCount');
             // Set title
             $title = $userObject->name;
             $userObject->name = htmlspecialchars($userObject->name, ENT_QUOTES);
             // Set ordering
             $ordering = $params->get('userOrdering');
             $addHeadFeedLink = $params->get('userFeedLink', 1);
             break;
         case 'tag':
             // Set layout
             $this->setLayout('tag');
             // Set limit
             $limit = $params->get('tagItemCount');
             // Set title
             $title = JText::_('K2_DISPLAYING_ITEMS_BY_TAG') . ' ' . JRequest::getVar('tag');
             // Set ordering
             $ordering = $params->get('tagOrdering');
             $addHeadFeedLink = $params->get('tagFeedLink', 1);
             break;
         case 'search':
             // Set layout
             $this->setLayout('generic');
             // Set limit
             $limit = $params->get('genericItemCount');
             // Set title
             $title = JText::_('K2_SEARCH_RESULTS_FOR') . ' ' . JRequest::getVar('searchword');
             $addHeadFeedLink = $params->get('genericFeedLink', 1);
             break;
         case 'date':
             // Set layout
             $this->setLayout('generic');
             // Set limit
             $limit = $params->get('genericItemCount');
             // Fix wrong timezone
             if (function_exists('date_default_timezone_get')) {
                 $originalTimezone = date_default_timezone_get();
             }
             if (function_exists('date_default_timezone_set')) {
                 date_default_timezone_set('UTC');
             }
             // Set title
             if (JRequest::getInt('day')) {
                 $date = strtotime(JRequest::getInt('year') . '-' . JRequest::getInt('month') . '-' . JRequest::getInt('day'));
                 $dateFormat = K2_JVERSION == '15' ? '%A, %d %B %Y' : 'l, d F Y';
                 $title = JText::_('K2_ITEMS_FILTERED_BY_DATE') . ' ' . JHTML::_('date', $date, $dateFormat);
             } else {
                 $date = strtotime(JRequest::getInt('year') . '-' . JRequest::getInt('month'));
                 $dateFormat = K2_JVERSION == '15' ? '%B %Y' : 'F Y';
                 $title = JText::_('K2_ITEMS_FILTERED_BY_DATE') . ' ' . JHTML::_('date', $date, $dateFormat);
             }
             // Restore the original timezone
             if (function_exists('date_default_timezone_set') && isset($originalTimezone)) {
                 date_default_timezone_set($originalTimezone);
             }
             // Set ordering
             $ordering = 'rdate';
             $addHeadFeedLink = $params->get('genericFeedLink', 1);
             break;
         default:
             // Set layout
             $this->setLayout('category');
             $user = JFactory::getUser();
             $this->assignRef('user', $user);
             // Set limit
             $limit = $params->get('num_leading_items') + $params->get('num_primary_items') + $params->get('num_secondary_items') + $params->get('num_links');
             // Set featured flag
             JRequest::setVar('featured', $params->get('catFeaturedItems'));
             // Set title
             $title = $params->get('page_title');
             // Set ordering
             $ordering = $params->get('catOrdering');
             $addHeadFeedLink = $params->get('catFeedLink', 1);
             break;
     }
     // Set limit for model
     if (!$limit) {
         $limit = 10;
     }
     JRequest::setVar('limit', $limit);
     // Get items
     if (!isset($ordering)) {
         $items = $model->getData();
     } else {
         $items = $model->getData($ordering);
     }
     // Pagination
     jimport('joomla.html.pagination');
     $total = count($items) ? $model->getTotal() : 0;
     $pagination = new JPagination($total, $limitstart, $limit);
     //Prepare items
     $user = JFactory::getUser();
     $cache = JFactory::getCache('com_k2_extended');
     $model = $this->getModel('item');
     for ($i = 0; $i < sizeof($items); $i++) {
         //Item group
         if ($task == "category" || $task == "") {
             if ($i < $params->get('num_links') + $params->get('num_leading_items') + $params->get('num_primary_items') + $params->get('num_secondary_items')) {
                 $items[$i]->itemGroup = 'links';
             }
             if ($i < $params->get('num_secondary_items') + $params->get('num_leading_items') + $params->get('num_primary_items')) {
                 $items[$i]->itemGroup = 'secondary';
             }
             if ($i < $params->get('num_primary_items') + $params->get('num_leading_items')) {
                 $items[$i]->itemGroup = 'primary';
             }
             if ($i < $params->get('num_leading_items')) {
                 $items[$i]->itemGroup = 'leading';
             }
         }
         // Check if the model should use the cache for preparing the item even if the user is logged in
         if ($user->guest || $task == 'tag' || $task == 'search' || $task == 'date') {
             $cacheFlag = true;
         } else {
             $cacheFlag = true;
             if (K2HelperPermissions::canEditItem($items[$i]->created_by, $items[$i]->catid)) {
                 $cacheFlag = false;
             }
         }
         // Prepare item
         if ($cacheFlag) {
             $hits = $items[$i]->hits;
             $items[$i]->hits = 0;
             JTable::getInstance('K2Category', 'Table');
             $items[$i] = $cache->call(array($model, 'prepareItem'), $items[$i], $view, $task);
             $items[$i]->hits = $hits;
         } else {
             $items[$i] = $model->prepareItem($items[$i], $view, $task);
         }
         // Plugins
         $items[$i] = $model->execPlugins($items[$i], $view, $task);
         // Trigger comments counter event
         $dispatcher = JDispatcher::getInstance();
         JPluginHelper::importPlugin('k2');
         $results = $dispatcher->trigger('onK2CommentsCounter', array(&$items[$i], &$params, $limitstart));
         $items[$i]->event->K2CommentsCounter = trim(implode("\n", $results));
     }
     // Set title
     $document = JFactory::getDocument();
     $application = JFactory::getApplication();
     $menus = $application->getMenu();
     $menu = $menus->getActive();
     if (is_object($menu)) {
         if (is_string($menu->params)) {
             $menu_params = K2_JVERSION == '15' ? new JParameter($menu->params) : new JRegistry($menu->params);
         } else {
             $menu_params = $menu->params;
         }
         if (!$menu_params->get('page_title')) {
             $params->set('page_title', $title);
         }
     } else {
         $params->set('page_title', $title);
     }
     // We're adding a new variable here which won't get the appended/prepended site title,
     // when enabled via Joomla!'s SEO/SEF settings
     $params->set('page_title_clean', $title);
     if (K2_JVERSION != '15') {
         if ($mainframe->getCfg('sitename_pagetitles', 0) == 1) {
             $tmpTitle = JText::sprintf('JPAGETITLE', $mainframe->getCfg('sitename'), $params->get('page_title'));
             $params->set('page_title', $tmpTitle);
         } elseif ($mainframe->getCfg('sitename_pagetitles', 0) == 2) {
             $tmpTitle = JText::sprintf('JPAGETITLE', $params->get('page_title'), $mainframe->getCfg('sitename'));
             $params->set('page_title', $tmpTitle);
         }
     }
     $document->setTitle($params->get('page_title'));
     // Search - Update the Google Search results container (K2 v2.6.6+)
     if ($task == 'search') {
         $googleSearchContainerID = trim($params->get('googleSearchContainer', 'k2GoogleSearchContainer'));
         if ($googleSearchContainerID == 'k2Container') {
             $googleSearchContainerID = 'k2GoogleSearchContainer';
         }
         $params->set('googleSearchContainer', $googleSearchContainerID);
     }
     // Set metadata for category
     if ($task == 'category') {
         if ($category->metaDescription) {
             $document->setDescription($category->metaDescription);
         } else {
             $metaDescItem = preg_replace("#{(.*?)}(.*?){/(.*?)}#s", '', $this->category->description);
             $metaDescItem = strip_tags($metaDescItem);
             $metaDescItem = K2HelperUtilities::characterLimit($metaDescItem, $params->get('metaDescLimit', 150));
             $metaDescItem = htmlspecialchars($metaDescItem, ENT_QUOTES, 'UTF-8');
             $document->setDescription($metaDescItem);
         }
         if ($category->metaKeywords) {
             $document->setMetadata('keywords', $category->metaKeywords);
         }
         if ($category->metaRobots) {
             $document->setMetadata('robots', $category->metaRobots);
         }
         if ($category->metaAuthor) {
             $document->setMetadata('author', $category->metaAuthor);
         }
     }
     if (K2_JVERSION != '15') {
         // Menu metadata options
         if ($params->get('menu-meta_description')) {
             $document->setDescription($params->get('menu-meta_description'));
         }
         if ($params->get('menu-meta_keywords')) {
             $document->setMetadata('keywords', $params->get('menu-meta_keywords'));
         }
         if ($params->get('robots')) {
             $document->setMetadata('robots', $params->get('robots'));
         }
         // Menu page display options
         if ($params->get('page_heading')) {
             $params->set('page_title', $params->get('page_heading'));
         }
         $params->set('show_page_title', $params->get('show_page_heading'));
     }
     // Pathway
     $pathway = $mainframe->getPathWay();
     if (!isset($menu->query['task'])) {
         $menu->query['task'] = '';
     }
     if ($menu) {
         switch ($task) {
             case 'category':
                 if ($menu->query['task'] != 'category' || $menu->query['id'] != JRequest::getInt('id')) {
                     $pathway->addItem($title, '');
                 }
                 break;
             case 'user':
                 if ($menu->query['task'] != 'user' || $menu->query['id'] != JRequest::getInt('id')) {
                     $pathway->addItem($title, '');
                 }
                 break;
             case 'tag':
                 if ($menu->query['task'] != 'tag' || $menu->query['tag'] != JRequest::getVar('tag')) {
                     $pathway->addItem($title, '');
                 }
                 break;
             case 'search':
             case 'date':
                 $pathway->addItem($title, '');
                 break;
         }
     }
     // Feed link
     $config = JFactory::getConfig();
     $menu = $application->getMenu();
     $default = $menu->getDefault();
     $active = $menu->getActive();
     if ($task == 'tag') {
         $link = K2HelperRoute::getTagRoute(JRequest::getVar('tag'));
     } else {
         $link = '';
     }
     $sef = K2_JVERSION == '30' ? $config->get('sef') : $config->getValue('config.sef');
     if (!is_null($active) && $active->id == $default->id && $sef) {
         $link .= '&Itemid=' . $active->id . '&format=feed&limitstart=';
     } else {
         $link .= '&format=feed&limitstart=';
     }
     $feed = JRoute::_($link);
     $this->assignRef('feed', $feed);
     // Add head feed link
     if ($addHeadFeedLink) {
         $attribs = array('type' => 'application/rss+xml', 'title' => 'RSS 2.0');
         $document->addHeadLink(JRoute::_($link . '&type=rss'), 'alternate', 'rel', $attribs);
         $attribs = array('type' => 'application/atom+xml', 'title' => 'Atom 1.0');
         $document->addHeadLink(JRoute::_($link . '&type=atom'), 'alternate', 'rel', $attribs);
     }
     // Assign data
     if ($task == "category" || $task == "") {
         $leading = @array_slice($items, 0, $params->get('num_leading_items'));
         $primary = @array_slice($items, $params->get('num_leading_items'), $params->get('num_primary_items'));
         $secondary = @array_slice($items, $params->get('num_leading_items') + $params->get('num_primary_items'), $params->get('num_secondary_items'));
         $links = @array_slice($items, $params->get('num_leading_items') + $params->get('num_primary_items') + $params->get('num_secondary_items'), $params->get('num_links'));
         $this->assignRef('leading', $leading);
         $this->assignRef('primary', $primary);
         $this->assignRef('secondary', $secondary);
         $this->assignRef('links', $links);
     } else {
         $this->assignRef('items', $items);
     }
     // Set default values to avoid division by zero
     if ($params->get('num_leading_columns') == 0) {
         $params->set('num_leading_columns', 1);
     }
     if ($params->get('num_primary_columns') == 0) {
         $params->set('num_primary_columns', 1);
     }
     if ($params->get('num_secondary_columns') == 0) {
         $params->set('num_secondary_columns', 1);
     }
     if ($params->get('num_links_columns') == 0) {
         $params->set('num_links_columns', 1);
     }
     $this->assignRef('params', $params);
     $this->assignRef('pagination', $pagination);
     // Set Facebook meta data
     $document = JFactory::getDocument();
     $uri = JURI::getInstance();
     $document->setMetaData('og:url', $uri->toString());
     $document->setMetaData('og:title', htmlspecialchars($document->getTitle(), ENT_QUOTES, 'UTF-8'));
     $document->setMetaData('og:type', 'website');
     if ($task == 'category' && $this->category->image && strpos($this->category->image, 'placeholder/category.png') === false) {
         $image = substr(JURI::root(), 0, -1) . str_replace(JURI::root(true), '', $this->category->image);
         $document->setMetaData('og:image', $image);
         $document->setMetaData('image', $image);
     }
     $document->setMetaData('og:description', htmlspecialchars(strip_tags($document->getDescription()), ENT_QUOTES, 'UTF-8'));
     // Look for template files in component folders
     $this->_addPath('template', JPATH_COMPONENT . DS . 'templates');
     $this->_addPath('template', JPATH_COMPONENT . DS . 'templates' . DS . 'default');
     // Look for overrides in template folder (K2 template structure)
     $this->_addPath('template', JPATH_SITE . DS . 'templates' . DS . $mainframe->getTemplate() . DS . 'html' . DS . 'com_k2' . DS . 'templates');
     $this->_addPath('template', JPATH_SITE . DS . 'templates' . DS . $mainframe->getTemplate() . DS . 'html' . DS . 'com_k2' . DS . 'templates' . DS . 'default');
     // Look for overrides in template folder (Joomla! template structure)
     $this->_addPath('template', JPATH_SITE . DS . 'templates' . DS . $mainframe->getTemplate() . DS . 'html' . DS . 'com_k2' . DS . 'default');
     $this->_addPath('template', JPATH_SITE . DS . 'templates' . DS . $mainframe->getTemplate() . DS . 'html' . DS . 'com_k2');
     // Look for specific K2 theme files
     if ($params->get('theme')) {
         $this->_addPath('template', JPATH_COMPONENT . DS . 'templates' . DS . $params->get('theme'));
         $this->_addPath('template', JPATH_SITE . DS . 'templates' . DS . $mainframe->getTemplate() . DS . 'html' . DS . 'com_k2' . DS . 'templates' . DS . $params->get('theme'));
         $this->_addPath('template', JPATH_SITE . DS . 'templates' . DS . $mainframe->getTemplate() . DS . 'html' . DS . 'com_k2' . DS . $params->get('theme'));
     }
     $nullDate = $db->getNullDate();
     $this->assignRef('nullDate', $nullDate);
     $dispatcher = JDispatcher::getInstance();
     JPluginHelper::importPlugin('k2');
     $dispatcher->trigger('onK2BeforeViewDisplay');
     // Prevent spammers from using the tag view
     if ($task == 'tag' && !count($this->items)) {
         $tag = JRequest::getString('tag');
         $db = JFactory::getDBO();
         $db->setQuery('SELECT id FROM #__k2_tags WHERE name = ' . $db->quote($tag));
         $tagID = $db->loadResult();
         if (!$tagID) {
             JError::raiseError(404, JText::_('K2_NOT_FOUND'));
             return false;
         }
     }
     parent::display($tpl);
 }
Example #25
0
 public static function getList(&$params)
 {
     jimport('joomla.filesystem.file');
     $mainframe = JFactory::getApplication();
     $limit = $params->get('itemCount', 5);
     $cid = $params->get('category_id', NULL);
     $ordering = $params->get('itemsOrdering', '');
     $componentParams = JComponentHelper::getParams('com_k2');
     $limitstart = JRequest::getInt('limitstart');
     $user = JFactory::getUser();
     $aid = $user->get('aid');
     $db = JFactory::getDBO();
     $jnow = JFactory::getDate();
     $now = K2_JVERSION == '15' ? $jnow->toMySQL() : $jnow->toSql();
     $nullDate = $db->getNullDate();
     if ($params->get('source') == 'specific') {
         $value = $params->get('items');
         $current = array();
         if (is_string($value) && !empty($value)) {
             $current[] = $value;
         }
         if (is_array($value)) {
             $current = $value;
         }
         $items = array();
         foreach ($current as $id) {
             $query = "SELECT i.*, c.name AS categoryname,c.id AS categoryid, c.alias AS categoryalias, c.params AS categoryparams \n\t\t\t\tFROM #__k2_items as i \n\t\t\t\tLEFT JOIN #__k2_categories c ON c.id = i.catid \n\t\t\t\tWHERE i.published = 1 ";
             if (K2_JVERSION != '15') {
                 $query .= " AND i.access IN(" . implode(',', $user->getAuthorisedViewLevels()) . ") ";
             } else {
                 $query .= " AND i.access<={$aid} ";
             }
             $query .= " AND i.trash = 0 AND c.published = 1 ";
             if (K2_JVERSION != '15') {
                 $query .= " AND c.access IN(" . implode(',', $user->getAuthorisedViewLevels()) . ") ";
             } else {
                 $query .= " AND c.access<={$aid} ";
             }
             $query .= " AND c.trash = 0 \n\t\t\t\tAND ( i.publish_up = " . $db->Quote($nullDate) . " OR i.publish_up <= " . $db->Quote($now) . " ) \n\t\t\t\tAND ( i.publish_down = " . $db->Quote($nullDate) . " OR i.publish_down >= " . $db->Quote($now) . " ) \n\t\t\t\tAND i.id={$id}";
             if (K2_JVERSION != '15') {
                 if ($mainframe->getLanguageFilter()) {
                     $languageTag = JFactory::getLanguage()->getTag();
                     $query .= " AND c.language IN (" . $db->Quote($languageTag) . ", " . $db->Quote('*') . ") AND i.language IN (" . $db->Quote($languageTag) . ", " . $db->Quote('*') . ")";
                 }
             }
             $db->setQuery($query);
             $item = $db->loadObject();
             if ($item) {
                 $items[] = $item;
             }
         }
     } else {
         $query = "SELECT i.*, CASE WHEN i.modified = 0 THEN i.created ELSE i.modified END as lastChanged, 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";
         }
         if ($ordering == 'comments') {
             $query .= ", COUNT(comments.id) AS numOfComments";
         }
         $query .= " FROM #__k2_items as i RIGHT JOIN #__k2_categories c ON c.id = i.catid";
         if ($ordering == 'best') {
             $query .= " LEFT JOIN #__k2_rating r ON r.itemID = i.id";
         }
         if ($ordering == 'comments') {
             $query .= " LEFT JOIN #__k2_comments comments ON comments.itemID = i.id";
         }
         if (K2_JVERSION != '15') {
             $query .= " WHERE i.published = 1 AND i.access IN(" . implode(',', $user->getAuthorisedViewLevels()) . ") AND i.trash = 0 AND c.published = 1 AND c.access IN(" . implode(',', $user->getAuthorisedViewLevels()) . ")  AND c.trash = 0";
         } else {
             $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('catfilter')) {
             if (!is_null($cid)) {
                 if (is_array($cid)) {
                     if ($params->get('getChildren')) {
                         $itemListModel = K2Model::getInstance('Itemlist', 'K2Model');
                         $categories = $itemListModel->getCategoryTree($cid);
                         $sql = @implode(',', $categories);
                         $query .= " AND i.catid IN ({$sql})";
                     } else {
                         JArrayHelper::toInteger($cid);
                         $query .= " AND i.catid IN(" . implode(',', $cid) . ")";
                     }
                 } else {
                     if ($params->get('getChildren')) {
                         $itemListModel = K2Model::getInstance('Itemlist', 'K2Model');
                         $categories = $itemListModel->getCategoryTree($cid);
                         $sql = @implode(',', $categories);
                         $query .= " AND i.catid IN ({$sql})";
                     } else {
                         $query .= " AND i.catid=" . (int) $cid;
                     }
                 }
             }
         }
         if ($params->get('FeaturedItems') == '0') {
             $query .= " AND i.featured != 1";
         }
         if ($params->get('FeaturedItems') == '2') {
             $query .= " AND i.featured = 1";
         }
         if ($params->get('videosOnly')) {
             $query .= " AND (i.video IS NOT NULL AND i.video!='')";
         }
         if ($ordering == 'comments') {
             $query .= " AND comments.published = 1";
         }
         if (K2_JVERSION != '15') {
             if ($mainframe->getLanguageFilter()) {
                 $languageTag = JFactory::getLanguage()->getTag();
                 $query .= " AND c.language IN (" . $db->Quote($languageTag) . ", " . $db->Quote('*') . ") AND i.language IN (" . $db->Quote($languageTag) . ", " . $db->Quote('*') . ")";
             }
         }
         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('FeaturedItems') == '2') {
                     $orderby = 'i.featured_ordering';
                 } else {
                     $orderby = 'i.ordering';
                 }
                 break;
             case 'rorder':
                 if ($params->get('FeaturedItems') == '2') {
                     $orderby = 'i.featured_ordering DESC';
                 } else {
                     $orderby = 'i.ordering DESC';
                 }
                 break;
             case 'hits':
                 if ($params->get('popularityRange')) {
                     $datenow = JFactory::getDate();
                     $date = K2_JVERSION == '15' ? $datenow->toMySQL() : $datenow->toSql();
                     $query .= " AND i.created > DATE_SUB('{$date}',INTERVAL " . $params->get('popularityRange') . " DAY) ";
                 }
                 $orderby = 'i.hits DESC';
                 break;
             case 'rand':
                 $orderby = 'RAND()';
                 break;
             case 'best':
                 $orderby = 'rating DESC';
                 break;
             case 'comments':
                 if ($params->get('popularityRange')) {
                     $datenow = JFactory::getDate();
                     $date = K2_JVERSION == '15' ? $datenow->toMySQL() : $datenow->toSql();
                     $query .= " AND i.created > DATE_SUB('{$date}',INTERVAL " . $params->get('popularityRange') . " DAY) ";
                 }
                 $query .= " GROUP BY i.id ";
                 $orderby = 'numOfComments DESC';
                 break;
             case 'modified':
                 $orderby = 'lastChanged DESC';
                 break;
             case 'publishUp':
                 $orderby = 'i.publish_up DESC';
                 break;
             default:
                 $orderby = 'i.id DESC';
                 break;
         }
         $query .= " ORDER BY " . $orderby;
         // $sql = str_replace('#__','jos_',$query);
         // echo $sql;die;
         //var_dump($limit);
         $db->setQuery($query, 0, $limit);
         $items = $db->loadObjectList();
     }
     $model = K2Model::getInstance('Item', 'K2Model');
     $show_introtext = $params->get('item_desc_display', 0);
     $introtext_limit = $params->get('item_desc_max_characs', 100);
     $show_title = $params->get('item_title_display', 1);
     $title_limit = $params->get('item_title_max_characs', 20);
     $item_title_ending_char = $params->get('item_title_ending_char', '');
     $item_desc_ending_char = $params->get('item_desc_ending_char', '');
     if (count($items)) {
         foreach ($items as $item) {
             //Clean title
             $item->title = JFilterOutput::ampReplace($item->title);
             $item->displaytitle = $show_title ? self::truncate($item->title, $title_limit, $item_title_ending_char) : '';
             //Read more link
             $item->link = urldecode(JRoute::_(K2HelperRoute::getItemRoute($item->id . ':' . urlencode($item->alias), $item->catid . ':' . urlencode($item->categoryalias))));
             //Tags
             $item->tags = '';
             if ($params->get('item_tags_display')) {
                 $tags = $model->getItemTags($item->id);
                 for ($i = 0; $i < sizeof($tags); $i++) {
                     $tags[$i]->link = JRoute::_(K2HelperRoute::getTagRoute($tags[$i]->name));
                 }
                 $item->tags = $tags;
             } else {
                 $item->tags = '';
             }
             // Restore the intotext variable after plugins execution
             self::getK2Images($item, $params);
             //Clean the plugin tags
             $item->introtext = preg_replace("#{(.*?)}(.*?){/(.*?)}#s", '', $item->introtext);
             if ($item->fulltext != '') {
                 $item->fulltext = preg_replace("#{(.*?)}(.*?){/(.*?)}#s", '', $item->fulltext);
                 $item->introtext = self::_cleanText($item->introtext . $item->fulltext);
             } else {
                 $item->introtext = self::_cleanText($item->introtext);
             }
             $item->displayIntrotext = $show_introtext ? self::truncate($item->introtext, $introtext_limit, $item_desc_ending_char) : '';
             $rows[] = $item;
         }
         return $rows;
     }
 }
Example #26
0
File: k2.php Project: Tommar/vino
 /**
  * get the list of k2 items
  *
  * @param JParameter $params;
  * @return Array
  */
 public function getList()
 {
     // check k2 existing
     if (!is_file(JPATH_SITE . "/components/com_k2/k2.php")) {
         return array();
     }
     $params =& $this->_params;
     // Init vars
     $show_title = $params->get('show_title', 1);
     $titleMaxChars = $params->get('title_max_chars', '100');
     $limit_title_by = $params->get('limit_title_by', 'char');
     $replacer = $params->get('replacer', '...');
     $isStrips = $params->get("auto_strip_tags", 1);
     $stringtags = '';
     if ($isStrips) {
         $allow_tags = $params->get("allow_tags", '');
         $stringtags = '';
         if (!is_array($allow_tags)) {
             $allow_tags = explode(',', $allow_tags);
         }
         foreach ($allow_tags as $tag) {
             $stringtags .= '<' . $tag . '>';
         }
     }
     if (!$params->get('default_thumb', 1)) {
         $this->_defaultThumb = '';
     }
     /* intro */
     $show_intro = $params->get('show_intro', 1);
     $maxDesciption = $params->get('description_max_chars', 100);
     $limitDescriptionBy = $params->get('limit_description_by', 'char');
     $ordering = $params->get('ordering', 'created-desc');
     $limit = $params->get('limit_items', 12);
     // Set ordering
     $ordering = explode('-', $ordering);
     if (trim($ordering[0]) == 'rand') {
         $ordering = ' RAND() ';
     } else {
         $ordering = $ordering[0] . ' ' . $ordering[1];
     }
     $user = JFactory::getUser();
     $isThumb = $params->get('image_thumb', 1);
     $thumbWidth = (int) $params->get('thumbnail_width', 280);
     $thumbHeight = (int) $params->get('thumbnail_height', 150);
     $quality = (int) $params->get('image_quality', 80);
     $db = JFactory::getDBO();
     $date = JFactory::getDate();
     $now = $date->toSQL();
     $dateFormat = $params->get('date_format', 'DATE_FORMAT_LC3');
     $show_author = $params->get('show_author', 0);
     // main query
     $query = "SELECT  a.*, c.name as category_title,\n\t\t\t\t\t\tc.id as categoryid, c.alias as categoryalias, c.params as categoryparams, c.image as category_image" . " FROM #__k2_items as a" . " LEFT JOIN #__k2_categories c ON c.id = a.catid";
     $query .= " WHERE a.published = 1" . " AND a.access IN(" . implode(',', $user->getAuthorisedViewLevels()) . ")" . " AND a.trash = 0" . " AND c.published = 1" . " AND c.access IN(" . implode(',', $user->getAuthorisedViewLevels()) . ")" . " AND c.trash = 0 ";
     // filter by user
     $userId = $user->get('id');
     switch ($params->get('user_id')) {
         case 'by_me':
             $query .= 'AND a.created_by = ' . $userId;
             break;
         case 'not_me':
             $query .= 'AND a.created_by != ' . $userId;
             break;
         case 0:
             break;
         default:
             $query .= 'AND a.created_by = ' . $userId;
             break;
     }
     // filter by featured params
     if ($params->get('show_featured', '1') == 2) {
         $query .= " AND a.featured != 1";
     } elseif ($params->get('show_featured', '1') == 3) {
         $query .= " AND a.featured = 1";
     }
     // valid publish date
     $jnow = JFactory::getDate();
     $now = $jnow->toSql();
     $nullDate = $db->getNullDate();
     $query .= " AND ( a.publish_up = " . $db->Quote($nullDate) . " OR a.publish_up <= " . $db->Quote($now) . " )";
     $query .= " AND ( a.publish_down = " . $db->Quote($nullDate) . " OR a.publish_down >= " . $db->Quote($now) . " )";
     //filter by language
     $languageTag = JFactory::getLanguage()->getTag();
     $query .= " AND a.language IN (" . $db->quote($languageTag) . "," . $db->quote('*') . ") AND c.language IN (" . $db->quote($languageTag) . "," . $db->quote('*') . ")";
     //Get data
     $data = array();
     $source = trim($this->_params->get('source', 'k2_category'));
     $catids = self::getCategoryIds();
     if ($source == 'k2_category' && !empty($catids) && $this->_params->get('limit_items_for_each')) {
         $db->setQuery('SELECT id from #__k2_categories where id in (' . implode($catids, ',') . ') order by ordering');
         $catids = $db->loadColumn();
         foreach ($catids as $catid) {
             $condition = ' AND  a.catid = ' . $catid . ' ';
             $db->setQuery($query . $condition . ' ORDER BY ' . $ordering . ($limit ? ' LIMIT ' . $limit : ''));
             $data = array_merge($data, $db->loadObjectlist());
         }
     } else {
         $condition = $this->buildConditionQuery($source, $catids);
         $db->setQuery($query . $condition . ' ORDER BY ' . $ordering . ($limit ? ' LIMIT ' . $limit : ''));
         $data = array_merge($data, $db->loadObjectlist());
     }
     // Rebuild data
     foreach ($data as $key => &$item) {
         // authorise
         if (in_array($item->access, $user->getAuthorisedViewLevels())) {
             $item->link = JRoute::_(K2HelperRoute::getItemRoute($item->id . ':' . $item->alias, $item->catid . ':' . $item->categoryalias));
         } else {
             $item->link = JRoute::_('index.php?option=com_users&view=login');
         }
         // format date
         $item->date = JHtml::_('date', $item->created, JText::_($dateFormat));
         //cut title
         if ($limit_title_by == 'word' && $titleMaxChars > 0) {
             $item->title_cut = self::substrword($item->title, $titleMaxChars, $replacer, $isStrips);
         } elseif ($limit_title_by == 'char' && $titleMaxChars > 0) {
             $item->title_cut = self::substring($item->title, $titleMaxChars, $replacer, $isStrips);
         }
         // escape html characters
         $item->title = htmlspecialchars($item->title);
         // import joomla content prepare plugin
         if ($params->get('content_plugin')) {
             $item->introtext = JHtml::_('content.prepare', $item->introtext);
         }
         // cut introtext
         if ($limitDescriptionBy == 'word') {
             $item->description = self::substrword($item->introtext, $maxDesciption, $replacer, $isStrips, $stringtags);
         } else {
             $item->description = self::substring($item->introtext, $maxDesciption, $replacer, $isStrips, $stringtags);
         }
         $item->categoryLink = urldecode(JRoute::_(K2HelperRoute::getCategoryRoute($item->catid . ':' . urlencode($item->categoryalias))));
         // get author name & link
         if ($show_author) {
             if (!empty($item->created_by_alias)) {
                 $item->author = $item->created_by_alias;
             } else {
                 $author = JFactory::getUser($item->created_by);
                 $item->author = $author->name;
             }
             $item->authorLink = JRoute::_(K2HelperRoute::getUserRoute($item->created_by));
         }
         // make thumbnail
         $item->thumbnail = '';
         $item->mainImage = '';
         if ($params->get('show_image')) {
             $item = $this->generateImages($item, $isThumb, $quality);
         }
         //get extrafields
         $showExtrafields = $params->get('show_extrafields', array());
         if (count($showExtrafields) && $item->extra_fields) {
             $item->extra_fields = json_decode($item->extra_fields);
             if (count($item->extra_fields)) {
                 $exIds = array();
                 foreach ($item->extra_fields as $ex) {
                     $exIds[] = $ex->id;
                 }
                 $exIds = implode(',', $exIds);
                 $query = 'SELECT name FROM #__k2_extra_fields WHERE id IN (' . $exIds . ') ORDER BY ordering';
                 $db->setQuery($query);
                 $rs = $db->loadObjectlist();
                 foreach ($item->extra_fields as $key => &$ex) {
                     $ex->name = $rs[$key]->name;
                 }
             }
         }
     }
     return $data;
 }
Example #27
0
 /**
  * get list k2 items follow setting configuration.
  *
  * @param JParameter $param
  * @return array
  */
 public function getListK2($params)
 {
     global $mainframe;
     if (!file_exists(JPATH_SITE . DS . 'components' . DS . 'com_k2' . DS . 'k2.php')) {
         return;
     }
     $catsid = $params->get('k2catsid');
     $catids = array();
     if (!is_array($catsid)) {
         $catids[] = $catsid;
     } else {
         $catids = $catsid;
     }
     JArrayHelper::toInteger($catids);
     if ($catids) {
         if ($catids && count($catids) > 0) {
             foreach ($catids as $k => $catid) {
                 if (!$catid) {
                     unset($catids[$k]);
                 }
             }
         }
     }
     jimport('joomla.filesystem.file');
     $user = JFactory::getUser();
     $aid = $user->get('aid') ? $user->get('aid') : 1;
     $db = JFactory::getDBO();
     $jnow = JFactory::getDate();
     if (version_compare(JVERSION, '3.0', 'ge')) {
         $now = $jnow->toSql();
     } else {
         if (version_compare(JVERSION, '2.5', 'ge')) {
             $now = $jnow->toMySQL();
         } else {
             $now = $jnow->toMySQL();
         }
     }
     $nullDate = $db->getNullDate();
     $query = "SELECT i.*, c.name AS categoryname,c.id AS categoryid, c.alias AS categoryalias, c.name as cattitle, c.params AS categoryparams";
     $query .= "\n FROM #__k2_items as i LEFT JOIN #__k2_categories c ON c.id = i.catid";
     $query .= "\n 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 .= "\n AND ( i.publish_up = " . $db->Quote($nullDate) . " OR i.publish_up <= " . $db->Quote($now) . " )";
     $query .= "\n AND ( i.publish_down = " . $db->Quote($nullDate) . " OR i.publish_down >= " . $db->Quote($now) . " )";
     if ($catids) {
         $catids_new = $catids;
         foreach ($catids as $k => $catid) {
             $subcatids = modJABulletin::getK2CategoryChildren($catid, true);
             if ($subcatids) {
                 $catids_new = array_merge($catids_new, array_diff($subcatids, $catids_new));
             }
         }
         $catids = implode(',', $catids_new);
         $query .= "\n AND i.catid IN ({$catids})";
     }
     $featured = $params->get('show_featured', 1);
     switch ($featured) {
         case 0:
             $query .= " AND i.featured = 0 ";
             break;
         case 2:
             $query .= " AND i.featured = 1 ";
             break;
     }
     // Set ordering
     $ordering = $params->get('type', 'latest');
     if ($ordering == 'latest') {
         // Set ordering
         $order_map = array('m_dsc' => 'i.modified DESC, i.created', 'mc_dsc' => 'CASE WHEN (a.modified = ' . $db->quote($db->getNullDate()) . ') THEN i.created ELSE i.modified END', 'c_dsc' => 'i.created', 'p_dsc' => 'i.publish_up');
         $ordering = JArrayHelper::getValue($order_map, $params->get('ordering', 'm_dsc'), 'i.publish_up');
     } else {
         $ordering = 'i.hits';
     }
     if ($ordering == "i.hits" && $params->get('timerange')) {
         $datenow = JFactory::getDate();
         if (version_compare(JVERSION, '3.0', 'ge')) {
             $date = $datenow->toSql();
         } else {
             if (version_compare(JVERSION, '2.5', 'ge')) {
                 $date = $datenow->toMySQL();
             } else {
                 $date = $datenow->toMySQL();
             }
         }
         $query .= " AND i.created > DATE_SUB('{$date}',INTERVAL " . $params->get('timerange') . " DAY) ";
     }
     $query .= ' ORDER BY ' . $ordering . ' DESC ';
     if ((int) trim($params->get('count', 5)) == 0) {
         $query = str_replace("i.published = 1 AND", "i.published = 10 AND", $query);
     }
     $db->setQuery($query, 0, (int) trim($params->get('count', 5)));
     $items = $db->loadObjectList();
     if ($items) {
         $i = 0;
         $showHits = $params->get('show_hits', 0);
         $showHits = $showHits == "1" ? true : false;
         $showimg = $params->get('show_image', 1);
         $w = (int) $params->get('width', 80);
         $h = (int) $params->get('height', 96);
         $showdate = $params->get('show_date', 1);
         $thumbnailMode = $params->get('thumbnail_mode', 'crop');
         $aspect = $params->get('use_ratio', '1');
         $crop = $thumbnailMode == 'crop' ? true : false;
         $lists = array();
         $jaimage = JAImage::getInstance();
         foreach ($items as &$item) {
             $item->link = urldecode(JRoute::_(K2HelperRoute::getItemRoute($item->id . ':' . urlencode($item->alias), $item->catid . ':' . urlencode($item->categoryalias))));
             $item->text = htmlspecialchars($item->title);
             if ($showdate) {
                 $item->date = $item->modified == null || $item->modified == "" || $item->modified == "0000-00-00 00:00:00" ? $item->created : $item->modified;
             }
             $item->image = '';
             if ($showimg) {
                 $imageSource = $this->parseImages($item, $params, 'k2');
                 if ($imageSource) {
                     if ($thumbnailMode != 'none') {
                         $imageURL = $jaimage->resize($imageSource, $w, $h, $crop, $aspect);
                         if ($imageURL) {
                             if ($imageURL == $imageSource) {
                                 $width = $w ? "width=\"{$w}\"" : "";
                                 $height = $h ? "height=\"{$h}\"" : "";
                                 $item->image = "<img src=\"{$imageURL}\" alt=\"{$item->text}\" title=\"{$item->text}\" {$width} {$height} />";
                             } else {
                                 $item->image = "<img src=\"{$imageURL}\" alt=\"{$item->text}\" title=\"{$item->text}\" />";
                             }
                         } else {
                             $item->image = '';
                         }
                     } else {
                         $width = $w ? "width=\"{$w}\"" : "";
                         $height = $h ? "height=\"{$h}\"" : "";
                         $item->image = "<img src=\"{$imageSource}\" alt=\"{$item->text}\" title=\"{$item->text}\" {$width} {$height} />";
                     }
                 }
             }
             //Author
             $author = JFactory::getUser($item->created_by);
             $item->creater = $author->name;
             if ($showHits) {
                 $item->hits = isset($item->hits) ? $item->hits : 0;
             } else {
                 $item->hits = null;
             }
         }
     }
     return $items;
 }
Example #28
0
 public function getProfileLink($defaultItemId = '')
 {
     static $instance = array();
     static $phpbbDB = null;
     static $phpbbpath = null;
     static $isBlogger = array();
     // since it's for avatar, we'll follow the avatar's integration
     $config = EasyBlogHelper::getConfig();
     $source = $config->get('layout_avatarIntegration');
     if (!$config->get('main_nonblogger_profile')) {
         // 1st check if this user a blogger or not.
         $showLink = false;
         if (isset($isBlogger[$this->id])) {
             $showLink = $isBlogger[$this->id];
         } else {
             $showLink = EasyBlogHelper::isBlogger($this->id);
             $isBlogger[$this->id] = $showLink;
         }
         if (!$showLink) {
             return 'javascript: void(0);';
         }
     }
     // phpbb case
     if ($source == 'phpbb' && $phpbbDB === null) {
         $phpbbpath = $config->get('layout_phpbb_path');
         $file = JPATH_ROOT . DIRECTORY_SEPARATOR . $phpbbpath . DIRECTORY_SEPARATOR . 'config.php';
         if (JFile::exists($file)) {
             require $file;
             $host = $dbhost;
             $user = $dbuser;
             $password = $dbpasswd;
             $database = $dbname;
             $prefix = $table_prefix;
             $driver = $dbms;
             $debug = 0;
             $options = array('driver' => $driver, 'host' => $host, 'user' => $user, 'password' => $password, 'database' => $database, 'prefix' => $prefix);
             $phpbbDB = JDatabase::getInstance($options);
         } else {
             $phpbbDB = false;
         }
     }
     if ($phpbbDB === false) {
         // can't get phpbb's config file, fallback to default profile link
         $source = 'default';
     }
     // Always use the core linking if user does not wants this.
     if (!$config->get('layout_avatar_link_name')) {
         $source = 'default';
     }
     // to ensure the passed in value is only a number
     $defaultItemId = str_replace('&Itemid=', '', $defaultItemId);
     // to ensure the uniqueness of the key
     $key = $source . '-' . $defaultItemId;
     // this is where the magic starts
     if (!isset($instance[$this->id][$key])) {
         $defaultItemId = !empty($defaultItemId) ? '&Itemid=' . $defaultItemId : '';
         $defaultLink = EasyBlogRouter::_('index.php?option=com_easyblog&view=blogger&layout=listings&id=' . $this->id . $defaultItemId);
         switch ($source) {
             case 'k2':
                 $file1 = JPATH_ROOT . '/components/com_k2/helpers/route.php';
                 $file2 = JPATH_ROOT . '/components/com_k2/helpers/utilities.php';
                 jimport('joomla.filesystem.file');
                 if (JFile::exists($file1) && JFile::exists($file2)) {
                     require_once $file1;
                     require_once $file2;
                     $ret = K2HelperRoute::getUserRoute($this->id);
                 } else {
                     $ret = $defaultLink;
                 }
                 break;
             case 'mightyregistration':
                 $ret = JRoute::_('index.php?option=com_community&view=profile&user_id=' . $this->id, false);
                 break;
             case 'communitybuilder':
                 $ret = JRoute::_('index.php?option=com_comprofiler&task=userProfile&user='******'easysocial':
                 $easysocial = EasyBlogHelper::getHelper('EasySocial');
                 $ret = '';
                 if ($easysocial->exists()) {
                     $easysocial->init();
                     $user = Foundry::user($this->id);
                     $ret = $user->getPermalink();
                 }
                 break;
             case 'jomsocial':
                 $file = JPATH_ROOT . DIRECTORY_SEPARATOR . 'components' . DIRECTORY_SEPARATOR . 'com_community' . DIRECTORY_SEPARATOR . 'libraries' . DIRECTORY_SEPARATOR . 'core.php';
                 $ret = JFile::exists($file) && (require_once $file) ? CRoute::_('index.php?option=com_community&view=profile&userid=' . $this->id) : '';
                 break;
             case 'kunena':
                 $ret = JRoute::_('index.php?option=com_kunena&func=fbprofile&userid=' . $this->id, false);
                 break;
             case 'phpbb':
                 $juser = JFactory::getUser($this->id);
                 $query = 'SELECT ' . $phpbbDB->nameQuote('user_id') . ' ' . 'FROM ' . $phpbbDB->nameQuote('#__users') . ' WHERE LOWER(' . $phpbbDB->nameQuote('username') . ') = LOWER(' . $phpbbDB->quote($juser->username) . ') ';
                 $phpbbDB->setQuery($query, 0, 1);
                 $phpbbuserid = $phpbbDB->loadResult();
                 $ret = $phpbbuserid ? JURI::root() . rtrim($phpbbpath, '/') . '/memberlist.php?mode=viewprofile&u=' . $phpbbuserid : '';
                 break;
             case 'anahita':
                 $person = KFactory::get('lib.anahita.se.person.helper')->getPerson($this->id);
                 $ret = $person->getURL();
                 break;
             case 'easydiscuss':
                 $file = JPATH_ROOT . DIRECTORY_SEPARATOR . 'components' . DIRECTORY_SEPARATOR . 'com_easydiscuss' . DIRECTORY_SEPARATOR . 'helpers' . DIRECTORY_SEPARATOR . 'router.php';
                 $ret = JFile::exists($file) && (require_once $file) ? DiscussRouter::_('index.php?option=com_easydiscuss&view=profile&id=' . $this->id, false) : '';
                 break;
             case 'gravatar':
             case 'default':
             default:
                 $ret = '';
                 break;
         }
         $instance[$this->id][$key] = $ret ? $ret : $defaultLink;
     }
     return $instance[$this->id][$key];
 }
Example #29
0
<ul class="k2UserBlockActions">
	<?php 
if (is_object($user->profile) && isset($user->profile->addLink)) {
    ?>
	<li> <a class="modal" rel="{handler:'iframe',size:{x:990,y:550}}" href="<?php 
    echo $user->profile->addLink;
    ?>
"><?php 
    echo JText::_('K2_ADD_NEW_ITEM');
    ?>
</a> </li>
	<?php 
}
?>
	<li> <a href="<?php 
echo JRoute::_(K2HelperRoute::getUserRoute($user->id));
?>
"><?php 
echo JText::_('K2_MY_PAGE');
?>
</a> </li>
	<li> <a href="<?php 
echo $profileLink;
?>
"><?php 
echo JText::_('K2_MY_ACCOUNT');
?>
</a> </li>
	<li> <a class="modal" rel="{handler:'iframe',size:{x:990,y:550}}" href="<?php 
echo JRoute::_('index.php?option=com_k2&view=comments&tmpl=component');
?>
Example #30
0
 function display($tpl = null)
 {
     $mainframe = JFactory::getApplication();
     $params = K2HelperUtilities::getParams('com_k2');
     $document = JFactory::getDocument();
     $model = $this->getModel('itemlist');
     $limitstart = JRequest::getInt('limitstart');
     $moduleID = JRequest::getInt('moduleID');
     if ($moduleID) {
         $result = $model->getModuleItems($moduleID);
         $items = $result->items;
         $title = $result->title;
     } else {
         //Get data depending on task
         $task = JRequest::getCmd('task');
         switch ($task) {
             case 'category':
                 //Get category
                 $id = JRequest::getInt('id');
                 JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . DS . 'tables');
                 $category = JTable::getInstance('K2Category', 'Table');
                 $category->load($id);
                 // State check
                 if (!$category->published || $category->trash) {
                     JError::raiseError(404, JText::_('K2_CATEGORY_NOT_FOUND'));
                 }
                 //Access check
                 $user = JFactory::getUser();
                 if (K2_JVERSION != '15') {
                     if (!in_array($category->access, $user->getAuthorisedViewLevels())) {
                         if ($user->guest) {
                             $uri = JFactory::getURI();
                             $url = 'index.php?option=com_users&view=login&return=' . base64_encode($uri->toString());
                             $mainframe->redirect(JRoute::_($url, false), JText::_('K2_YOU_NEED_TO_LOGIN_FIRST'));
                         } else {
                             JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
                             return;
                         }
                     }
                     $languageFilter = $mainframe->getLanguageFilter();
                     $languageTag = JFactory::getLanguage()->getTag();
                     if ($languageFilter && $category->language != $languageTag && $category->language != '*') {
                         return;
                     }
                 } else {
                     if ($category->access > $user->get('aid', 0)) {
                         if ($user->guest) {
                             $uri = JFactory::getURI();
                             $url = 'index.php?option=com_user&view=login&return=' . base64_encode($uri->toString());
                             $mainframe->redirect(JRoute::_($url, false), JText::_('K2_YOU_NEED_TO_LOGIN_FIRST'));
                         } else {
                             JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
                             return;
                         }
                     }
                 }
                 //Merge params
                 $cparams = class_exists('JParameter') ? new JParameter($category->params) : new JRegistry($category->params);
                 if ($cparams->get('inheritFrom')) {
                     $masterCategory = JTable::getInstance('K2Category', 'Table');
                     $masterCategory->load($cparams->get('inheritFrom'));
                     $cparams = class_exists('JParameter') ? new JParameter($masterCategory->params) : new JRegistry($masterCategory->params);
                 }
                 $params->merge($cparams);
                 //Category link
                 $category->link = urldecode(JRoute::_(K2HelperRoute::getCategoryRoute($category->id . ':' . urlencode($category->alias))));
                 //Set featured flag
                 JRequest::setVar('featured', $params->get('catFeaturedItems'));
                 //Set title
                 $title = $category->name;
                 // Set ordering
                 if ($params->get('singleCatOrdering')) {
                     $ordering = $params->get('singleCatOrdering');
                 } else {
                     $ordering = $params->get('catOrdering');
                 }
                 break;
             case 'user':
                 //Get user
                 $id = JRequest::getInt('id');
                 $userObject = JFactory::getUser($id);
                 //Check user status
                 if ($userObject->block) {
                     JError::raiseError(404, JText::_('K2_USER_NOT_FOUND'));
                 }
                 //Set title
                 $title = $userObject->name;
                 // Set ordering
                 $ordering = $params->get('userOrdering');
                 break;
             case 'tag':
                 //set title
                 $title = JText::_('K2_DISPLAYING_ITEMS_BY_TAG') . ' ' . JRequest::getVar('tag');
                 // Set ordering
                 $ordering = $params->get('tagOrdering');
                 break;
             case 'search':
                 //Set title
                 $title = JText::_('K2_SEARCH_RESULTS_FOR') . ' ' . JRequest::getVar('searchword');
                 break;
             case 'date':
                 // Set title
                 if (JRequest::getInt('day')) {
                     $date = strtotime(JRequest::getInt('year') . '-' . JRequest::getInt('month') . '-' . JRequest::getInt('day'));
                     $dateFormat = K2_JVERSION == '15' ? '%A, %d %B %Y' : 'l, d F Y';
                     $title = JText::_('K2_ITEMS_FILTERED_BY_DATE') . ' ' . JHTML::_('date', $date, $dateFormat);
                 } else {
                     $date = strtotime(JRequest::getInt('year') . '-' . JRequest::getInt('month'));
                     $dateFormat = K2_JVERSION == '15' ? '%B %Y' : 'F Y';
                     $title = JText::_('K2_ITEMS_FILTERED_BY_DATE') . ' ' . JHTML::_('date', $date, $dateFormat);
                 }
                 // Set ordering
                 $ordering = 'rdate';
                 break;
             default:
                 //Set featured flag
                 JRequest::setVar('featured', $params->get('catFeaturedItems'));
                 //Set title
                 $title = $params->get('page_title');
                 // Set ordering
                 $ordering = $params->get('catOrdering');
                 break;
         }
         // Various Feed Validations
         $title = JFilterOutput::ampReplace($title);
         // Get items
         if (!isset($ordering)) {
             $items = $model->getData();
         } else {
             $items = $model->getData($ordering);
         }
     }
     // Prepare feed items
     //$model = &$this->getModel('itemlist');
     foreach ($items as $item) {
         $item = $model->prepareFeedItem($item);
         $item->title = $this->escape($item->title);
         $item->title = html_entity_decode($item->title);
         $feedItem = new JFeedItem();
         $feedItem->title = $item->title;
         $feedItem->link = $item->link;
         $feedItem->description = $item->description;
         $feedItem->date = $item->created;
         $feedItem->category = $item->category->name;
         $feedItem->author = $item->author->name;
         if ($params->get('feedBogusEmail')) {
             $feedItem->authorEmail = $params->get('feedBogusEmail');
         } else {
             if ($mainframe->getCfg('feed_email') == 'author') {
                 $feedItem->authorEmail = $item->author->email;
             } else {
                 $feedItem->authorEmail = $mainframe->getCfg('mailfrom');
             }
         }
         // Add item
         $document->addItem($feedItem);
     }
     // Set title
     $document = JFactory::getDocument();
     $menus = JSite::getMenu();
     $menu = $menus->getActive();
     if (is_object($menu)) {
         $menu_params = class_exists('JParameter') ? new JParameter($menu->params) : new JRegistry($menu->params);
         if (!$menu_params->get('page_title')) {
             $params->set('page_title', $title);
         }
     } else {
         $params->set('page_title', $title);
     }
     if (K2_JVERSION != '15') {
         if ($mainframe->getCfg('sitename_pagetitles', 0) == 1) {
             $title = JText::sprintf('JPAGETITLE', $mainframe->getCfg('sitename'), $params->get('page_title'));
             $params->set('page_title', $title);
         } elseif ($mainframe->getCfg('sitename_pagetitles', 0) == 2) {
             $title = JText::sprintf('JPAGETITLE', $params->get('page_title'), $mainframe->getCfg('sitename'));
             $params->set('page_title', $title);
         }
     }
     $document->setTitle($params->get('page_title'));
     // Prevent spammers from using the tag view
     if ($task == 'tag' && !count($items)) {
         $tag = JRequest::getString('tag');
         $db = JFactory::getDBO();
         $db->setQuery('SELECT id FROM #__k2_tags WHERE name = ' . $db->quote($tag));
         $tagID = $db->loadResult();
         if (!$tagID) {
             JError::raiseError(404, JText::_('K2_NOT_FOUND'));
             return false;
         }
     }
 }