Ejemplo n.º 1
0
    public static function getProfile(&$params)
    {

        $user = JFactory::getUser();
        $db = JFactory::getDBO();
        $query = "SELECT * FROM #__k2_users  WHERE userID=".(int)$user->id;
        $db->setQuery($query, 0, 1);
        $profile = $db->loadObject();

        if ($profile)
        {
            if ($profile->image != '')
                $profile->avatar = JURI::root().'media/k2/users/'.$profile->image;

            require_once (JPATH_SITE.DS.'components'.DS.'com_k2'.DS.'helpers'.DS.'permissions'.'.php');

            if (JRequest::getCmd('option') != 'com_k2')
                K2HelperPermissions::setPermissions();

            if (K2HelperPermissions::canAddItem())
                $profile->addLink = JRoute::_('index.php?option=com_k2&view=item&task=add&tmpl=component');

            return $profile;

        }

    }
Ejemplo n.º 2
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);
 }
Ejemplo n.º 3
0
 function display($tpl = null)
 {
     $mainframe = JFactory::getApplication();
     $user = JFactory::getUser();
     $document = JFactory::getDocument();
     $params = K2HelperUtilities::getParams('com_k2');
     $limitstart = JRequest::getInt('limitstart', 0);
     $view = JRequest::getWord('view');
     $task = JRequest::getWord('task');
     $db = JFactory::getDBO();
     $jnow = JFactory::getDate();
     $now = K2_JVERSION == '15' ? $jnow->toMySQL() : $jnow->toSql();
     $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();
     $item->event = new stdClass();
     // Does the item exists?
     if (!is_object($item) || !$item->id) {
         JError::raiseError(404, JText::_('K2_ITEM_NOT_FOUND'));
     }
     // Prepare item
     $item = $model->prepareItem($item, $view, $task);
     // Plugins
     $item = $model->execPlugins($item, $view, $task);
     // User K2 plugins
     $item->event->K2UserDisplay = '';
     if (isset($item->author) && is_object($item->author->profile) && isset($item->author->profile->id)) {
         $dispatcher = JDispatcher::getInstance();
         JPluginHelper::importPlugin('k2');
         $results = $dispatcher->trigger('onK2UserDisplay', array(&$item->author->profile, &$params, $limitstart));
         $item->event->K2UserDisplay = trim(implode("\n", $results));
         $item->author->profile->url = htmlspecialchars($item->author->profile->url, ENT_QUOTES, 'UTF-8');
     }
     // Access check
     if ($this->getLayout() == 'form') {
         JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
     }
     if (K2_JVERSION != '15') {
         if (!in_array($item->access, $user->getAuthorisedViewLevels()) || !in_array($item->category->access, $user->getAuthorisedViewLevels())) {
             if ($user->guest) {
                 $uri = JFactory::getURI();
                 $url = 'index.php?option=com_users&view=login&return=' . base64_encode($uri->toString());
                 $mainframe->enqueueMessage(JText::_('K2_YOU_NEED_TO_LOGIN_FIRST'), 'notice');
                 $mainframe->redirect(JRoute::_($url, false));
             } else {
                 JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
                 return;
             }
         }
     } else {
         if ($item->access > $user->get('aid', 0) || $item->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->enqueueMessage(JText::_('K2_YOU_NEED_TO_LOGIN_FIRST'), 'notice');
                 $mainframe->redirect(JRoute::_($url, false));
             } else {
                 JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
                 return;
             }
         }
     }
     // Published check
     if (!$item->published || $item->trash) {
         JError::raiseError(404, JText::_('K2_ITEM_NOT_FOUND'));
     }
     if ($item->publish_up != $nullDate && $item->publish_up > $now) {
         JError::raiseError(404, JText::_('K2_ITEM_NOT_FOUND'));
     }
     if ($item->publish_down != $nullDate && $item->publish_down < $now) {
         JError::raiseError(404, JText::_('K2_ITEM_NOT_FOUND'));
     }
     if (!$item->category->published || $item->category->trash) {
         JError::raiseError(404, JText::_('K2_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)) {
             $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 ($item->params->get('itemAuthorLatest') && $item->created_by_alias == '') {
         $model = $this->getModel('itemlist');
         $authorLatestItems = $model->getAuthorLatest($item->id, $item->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 ($item->params->get('itemRelated') && isset($item->tags) && count($item->tags)) {
         $model = $this->getModel('itemlist');
         $relatedItems = $model->getRelatedItems($item->id, $item->tags, $item->params);
         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 ($item->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->toString();
     // Email link
     if (K2_JVERSION != '15') {
         require_once JPATH_SITE . '/components/com_mailto/helpers/mailto.php';
         $template = $mainframe->getTemplate();
         $item->emailLink = JRoute::_('index.php?option=com_mailto&tmpl=component&template=' . $template . '&link=' . MailToHelper::addLink($item->absoluteURL));
     } else {
         require_once JPATH_SITE . DS . 'components' . DS . 'com_mailto' . DS . 'helpers' . DS . 'mailto.php';
         $item->emailLink = JRoute::_('index.php?option=com_mailto&tmpl=component&link=' . MailToHelper::addLink($item->absoluteURL));
     }
     // Twitter link (legacy code)
     if ($params->get('twitterUsername')) {
         $item->twitterURL = 'http://twitter.com/intent/tweet?text=' . urlencode($item->title) . '&amp;url=' . urlencode($item->absoluteURL) . '&amp;via=' . $params->get('twitterUsername');
     } else {
         $item->twitterURL = 'http://twitter.com/intent/tweet?text=' . urlencode($item->title) . '&amp;url=' . urlencode($item->absoluteURL);
     }
     // 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);
 }
Ejemplo n.º 4
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');
     //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);
             // State Check
             if (!$category->published || $category->trash) {
                 JError::raiseError(404, JText::_('K2_CATEGORY_NOT_FOUND'));
             }
             //Access check
             $user =& JFactory::getUser();
             if (K2_JVERSION == '16') {
                 if (!in_array($category->access, $user->authorisedLevels())) {
                     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'));
                 }
             }
             // Hide the add new item link if user cannot post in the specific category
             if (!K2HelperPermissions::canAddItem($id)) {
                 unset($this->addLink);
             }
             //Merge params
             $cparams = new JParameter($category->params);
             if ($cparams->get('inheritFrom')) {
                 $masterCategory =& JTable::getInstance('K2Category', 'Table');
                 $masterCategory->load($cparams->get('inheritFrom'));
                 $cparams = new JParameter($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 == '16') {
                 $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->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;
             // 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'));
             }
             //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));
             }
             $this->assignRef('user', $userObject);
             //Set layout
             $this->setLayout('user');
             //Set limit
             $limit = $params->get('userItemCount');
             //Set title
             $title = $userObject->name;
             // Set ordering
             $ordering = $params->get('userOrdering');
             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');
             break;
         case 'search':
             //Set layout
             $this->setLayout('generic');
             $tpl = JRequest::getCmd('tpl', null);
             //Set limit
             $limit = $params->get('genericItemCount');
             //Set title
             $title = JText::_('K2_SEARCH_RESULTS_FOR') . ' ' . JRequest::getVar('searchword');
             break;
         case 'date':
             //Set layout
             $this->setLayout('generic');
             //Set limit
             $limit = $params->get('genericItemCount');
             // 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 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');
             break;
     }
     //Set limit for model
     JRequest::setVar('limit', $limit);
     if (!isset($ordering)) {
         $items = $model->getData();
     } else {
         $items = $model->getData($ordering);
     }
     //Pagination
     jimport('joomla.html.pagination');
     $total = $model->getTotal();
     $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 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('K2ModelItem', '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));
     }
     //Pathway
     $pathway =& $mainframe->getPathWay();
     $pathway->addItem($title);
     //Feed link
     $config =& JFactory::getConfig();
     $menu =& JSite::getMenu();
     $default = $menu->getDefault();
     $active = $menu->getActive();
     if ($task == 'tag') {
         $link = K2HelperRoute::getTagRoute(JRequest::getVar('tag'));
     } else {
         $link = '';
     }
     if (!is_null($active) && $active->id == $default->id && $config->getValue('config.sef')) {
         $link .= '&Itemid=' . $active->id . '&format=feed&limitstart=';
     } else {
         $link .= '&format=feed&limitstart=';
     }
     $feed = JRoute::_($link);
     $this->assignRef('feed', $feed);
     //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);
     //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'));
     }
     $db =& JFactory::getDBO();
     $nullDate = $db->getNullDate();
     $this->assignRef('nullDate', $nullDate);
     parent::display($tpl);
 }
Ejemplo n.º 5
0
 function save($front = false)
 {
     $mainframe = JFactory::getApplication();
     jimport('joomla.filesystem.file');
     jimport('joomla.filesystem.folder');
     jimport('joomla.filesystem.archive');
     require_once JPATH_COMPONENT_ADMINISTRATOR . DS . 'lib' . DS . 'class.upload.php';
     $db = JFactory::getDBO();
     $user = JFactory::getUser();
     $row = JTable::getInstance('K2Item', 'Table');
     $params = JComponentHelper::getParams('com_k2');
     $nullDate = $db->getNullDate();
     if (!$row->bind(JRequest::get('post'))) {
         $mainframe->enqueueMessage($row->getError(), 'error');
         $mainframe->redirect('index.php?option=com_k2&view=items');
     }
     if ($front && $row->id == NULL) {
         JLoader::register('K2HelperPermissions', JPATH_SITE . DS . 'components' . DS . 'com_k2' . DS . 'helpers' . DS . 'permissions.php');
         if (!K2HelperPermissions::canAddItem($row->catid)) {
             $mainframe->enqueueMessage(JText::_('K2_YOU_ARE_NOT_ALLOWED_TO_POST_TO_THIS_CATEGORY_SAVE_FAILED'), 'error');
             $mainframe->redirect('index.php?option=com_k2&view=item&task=add&tmpl=component');
         }
     }
     $isNew = $row->id ? false : true;
     // If we are in front-end and the item is not new we need to get it's current published state.
     if (!$isNew && $front) {
         $id = JRequest::getInt('id');
         $currentRow = JTable::getInstance('K2Item', 'Table');
         $currentRow->load($id);
         $isAlreadyPublished = $currentRow->published;
         $currentFeaturedState = $currentRow->featured;
     }
     if ($params->get('mergeEditors')) {
         $text = JRequest::getVar('text', '', 'post', 'string', 2);
         if ($params->get('xssFiltering')) {
             $filter = new JFilterInput(array(), array(), 1, 1, 0);
             $text = $filter->clean($text);
         }
         $pattern = '#<hr\\s+id=("|\')system-readmore("|\')\\s*\\/*>#i';
         $tagPos = preg_match($pattern, $text);
         if ($tagPos == 0) {
             $row->introtext = $text;
             $row->fulltext = '';
         } else {
             list($row->introtext, $row->fulltext) = preg_split($pattern, $text, 2);
         }
     } else {
         $row->introtext = JRequest::getVar('introtext', '', 'post', 'string', 2);
         $row->fulltext = JRequest::getVar('fulltext', '', 'post', 'string', 2);
         if ($params->get('xssFiltering')) {
             $filter = new JFilterInput(array(), array(), 1, 1, 0);
             $row->introtext = $filter->clean($row->introtext);
             $row->fulltext = $filter->clean($row->fulltext);
         }
     }
     if ($row->id) {
         $datenow = JFactory::getDate();
         $row->modified = K2_JVERSION == '15' ? $datenow->toMySQL() : $datenow->toSql();
         $row->modified_by = $user->get('id');
     } else {
         $row->ordering = $row->getNextOrder("catid = {$row->catid} AND trash = 0");
         if ($row->featured) {
             $row->featured_ordering = $row->getNextOrder("featured = 1 AND trash = 0", 'featured_ordering');
         }
     }
     $row->created_by = $row->created_by ? $row->created_by : $user->get('id');
     if ($front) {
         $K2Permissions = K2Permissions::getInstance();
         if (!$K2Permissions->permissions->get('editAll')) {
             $row->created_by = $user->get('id');
         }
     }
     if ($row->created && strlen(trim($row->created)) <= 10) {
         $row->created .= ' 00:00:00';
     }
     $config = JFactory::getConfig();
     $tzoffset = K2_JVERSION == '30' ? $config->get('offset') : $config->getValue('config.offset');
     $date = JFactory::getDate($row->created, $tzoffset);
     $row->created = K2_JVERSION == '15' ? $date->toMySQL() : $date->toSql();
     if (strlen(trim($row->publish_up)) <= 10) {
         $row->publish_up .= ' 00:00:00';
     }
     $date = JFactory::getDate($row->publish_up, $tzoffset);
     $row->publish_up = K2_JVERSION == '15' ? $date->toMySQL() : $date->toSql();
     if (trim($row->publish_down) == JText::_('K2_NEVER') || trim($row->publish_down) == '') {
         $row->publish_down = $nullDate;
     } else {
         if (strlen(trim($row->publish_down)) <= 10) {
             $row->publish_down .= ' 00:00:00';
         }
         $date = JFactory::getDate($row->publish_down, $tzoffset);
         $row->publish_down = K2_JVERSION == '15' ? $date->toMySQL() : $date->toSql();
     }
     $metadata = JRequest::getVar('meta', null, 'post', 'array');
     if (is_array($metadata)) {
         $txt = array();
         foreach ($metadata as $k => $v) {
             if ($k == 'description') {
                 $row->metadesc = $v;
             } elseif ($k == 'keywords') {
                 $row->metakey = $v;
             } else {
                 $txt[] = "{$k}={$v}";
             }
         }
         $row->metadata = implode("\n", $txt);
     }
     if (!$row->check()) {
         $mainframe->enqueueMessage($row->getError(), 'error');
         $mainframe->redirect('index.php?option=com_k2&view=item&cid=' . $row->id);
     }
     $dispatcher = JDispatcher::getInstance();
     JPluginHelper::importPlugin('k2');
     $result = $dispatcher->trigger('onBeforeK2Save', array(&$row, $isNew));
     if (in_array(false, $result, true)) {
         JError::raiseError(500, $row->getError());
         return false;
     }
     //Trigger the finder before save event
     $dispatcher = JDispatcher::getInstance();
     JPluginHelper::importPlugin('finder');
     $results = $dispatcher->trigger('onFinderBeforeSave', array('com_k2.item', $row, $isNew));
     // Try to save the video if there is no need to wait for item ID
     if (!JRequest::getBool('del_video')) {
         if (!isset($files['video'])) {
             if (JRequest::getVar('remoteVideo')) {
                 $fileurl = JRequest::getVar('remoteVideo');
                 $filetype = JFile::getExt($fileurl);
                 $row->video = '{' . $filetype . 'remote}' . $fileurl . '{/' . $filetype . 'remote}';
             }
             if (JRequest::getVar('videoID')) {
                 $provider = JRequest::getWord('videoProvider');
                 $videoID = JRequest::getVar('videoID');
                 $row->video = '{' . $provider . '}' . $videoID . '{/' . $provider . '}';
             }
             if (JRequest::getVar('embedVideo', '', 'post', 'string', JREQUEST_ALLOWRAW)) {
                 $row->video = JRequest::getVar('embedVideo', '', 'post', 'string', JREQUEST_ALLOWRAW);
             }
         }
     }
     // JoomFish! Front-end editing compatibility
     if ($mainframe->isSite() && JFile::exists(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_joomfish' . DS . 'joomfish.php')) {
         if (version_compare(phpversion(), '5.0') < 0) {
             $tmpRow = $row;
         } else {
             $tmpRow = clone $row;
         }
     }
     if (!$row->store()) {
         $mainframe->enqueueMessage($row->getError(), 'error');
         $mainframe->redirect('index.php?option=com_k2&view=items');
     }
     // JoomFish! Front-end editing compatibility
     if ($mainframe->isSite() && JFile::exists(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_joomfish' . DS . 'joomfish.php')) {
         $itemID = $row->id;
         $row = $tmpRow;
         $row->id = $itemID;
     }
     if (!$params->get('disableCompactOrdering')) {
         $row->reorder("catid = {$row->catid} AND trash = 0");
     }
     if ($row->featured && !$params->get('disableCompactOrdering')) {
         $row->reorder("featured = 1 AND trash = 0", 'featured_ordering');
     }
     $files = JRequest::get('files');
     //Image
     if ((int) $params->get('imageMemoryLimit')) {
         ini_set('memory_limit', (int) $params->get('imageMemoryLimit') . 'M');
     }
     $existingImage = JRequest::getVar('existingImage');
     if (($files['image']['error'] === 0 || $existingImage) && !JRequest::getBool('del_image')) {
         if ($files['image']['error'] === 0) {
             $image = $files['image'];
         } else {
             $image = JPATH_SITE . DS . JPath::clean($existingImage);
         }
         $handle = new Upload($image);
         $handle->allowed = array('image/*');
         if ($handle->uploaded) {
             //Image params
             $category = JTable::getInstance('K2Category', 'Table');
             $category->load($row->catid);
             $cparams = class_exists('JParameter') ? new JParameter($category->params) : new JRegistry($category->params);
             if ($cparams->get('inheritFrom')) {
                 $masterCategoryID = $cparams->get('inheritFrom');
                 $query = "SELECT * FROM #__k2_categories WHERE id=" . (int) $masterCategoryID;
                 $db->setQuery($query, 0, 1);
                 $masterCategory = $db->loadObject();
                 $cparams = class_exists('JParameter') ? new JParameter($masterCategory->params) : new JRegistry($masterCategory->params);
             }
             $params->merge($cparams);
             //Original image
             $savepath = JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'src';
             $handle->image_convert = 'jpg';
             $handle->jpeg_quality = 100;
             $handle->file_auto_rename = false;
             $handle->file_overwrite = true;
             $handle->file_new_name_body = md5("Image" . $row->id);
             $handle->Process($savepath);
             $filename = $handle->file_dst_name_body;
             $savepath = JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache';
             //XLarge image
             $handle->image_resize = true;
             $handle->image_ratio_y = true;
             $handle->image_convert = 'jpg';
             $handle->jpeg_quality = $params->get('imagesQuality');
             $handle->file_auto_rename = false;
             $handle->file_overwrite = true;
             $handle->file_new_name_body = $filename . '_XL';
             if (JRequest::getInt('itemImageXL')) {
                 $imageWidth = JRequest::getInt('itemImageXL');
             } else {
                 $imageWidth = $params->get('itemImageXL', '800');
             }
             $handle->image_x = $imageWidth;
             $handle->Process($savepath);
             //Large image
             $handle->image_resize = true;
             $handle->image_ratio_y = true;
             $handle->image_convert = 'jpg';
             $handle->jpeg_quality = $params->get('imagesQuality');
             $handle->file_auto_rename = false;
             $handle->file_overwrite = true;
             $handle->file_new_name_body = $filename . '_L';
             if (JRequest::getInt('itemImageL')) {
                 $imageWidth = JRequest::getInt('itemImageL');
             } else {
                 $imageWidth = $params->get('itemImageL', '600');
             }
             $handle->image_x = $imageWidth;
             $handle->Process($savepath);
             //Medium image
             $handle->image_resize = true;
             $handle->image_ratio_y = true;
             $handle->image_convert = 'jpg';
             $handle->jpeg_quality = $params->get('imagesQuality');
             $handle->file_auto_rename = false;
             $handle->file_overwrite = true;
             $handle->file_new_name_body = $filename . '_M';
             if (JRequest::getInt('itemImageM')) {
                 $imageWidth = JRequest::getInt('itemImageM');
             } else {
                 $imageWidth = $params->get('itemImageM', '400');
             }
             $handle->image_x = $imageWidth;
             $handle->Process($savepath);
             //Small image
             $handle->image_resize = true;
             $handle->image_ratio_y = true;
             $handle->image_convert = 'jpg';
             $handle->jpeg_quality = $params->get('imagesQuality');
             $handle->file_auto_rename = false;
             $handle->file_overwrite = true;
             $handle->file_new_name_body = $filename . '_S';
             if (JRequest::getInt('itemImageS')) {
                 $imageWidth = JRequest::getInt('itemImageS');
             } else {
                 $imageWidth = $params->get('itemImageS', '200');
             }
             $handle->image_x = $imageWidth;
             $handle->Process($savepath);
             //XSmall image
             $handle->image_resize = true;
             $handle->image_ratio_y = true;
             $handle->image_convert = 'jpg';
             $handle->jpeg_quality = $params->get('imagesQuality');
             $handle->file_auto_rename = false;
             $handle->file_overwrite = true;
             $handle->file_new_name_body = $filename . '_XS';
             if (JRequest::getInt('itemImageXS')) {
                 $imageWidth = JRequest::getInt('itemImageXS');
             } else {
                 $imageWidth = $params->get('itemImageXS', '100');
             }
             $handle->image_x = $imageWidth;
             $handle->Process($savepath);
             //Generic image
             $handle->image_resize = true;
             $handle->image_ratio_y = true;
             $handle->image_convert = 'jpg';
             $handle->jpeg_quality = $params->get('imagesQuality');
             $handle->file_auto_rename = false;
             $handle->file_overwrite = true;
             $handle->file_new_name_body = $filename . '_Generic';
             $imageWidth = $params->get('itemImageGeneric', '300');
             $handle->image_x = $imageWidth;
             $handle->Process($savepath);
             if ($files['image']['error'] === 0) {
                 $handle->Clean();
             }
         } else {
             $mainframe->enqueueMessage($handle->error, 'error');
             $mainframe->redirect('index.php?option=com_k2&view=items');
         }
     }
     if (JRequest::getBool('del_image')) {
         $current = JTable::getInstance('K2Item', 'Table');
         $current->load($row->id);
         $filename = md5("Image" . $current->id);
         if (JFile::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'src' . DS . $filename . '.jpg')) {
             JFile::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'src' . DS . $filename . '.jpg');
         }
         if (JFile::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_XS.jpg')) {
             JFile::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_XS.jpg');
         }
         if (JFile::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_S.jpg')) {
             JFile::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_S.jpg');
         }
         if (JFile::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_M.jpg')) {
             JFile::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_M.jpg');
         }
         if (JFile::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_L.jpg')) {
             JFile::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_L.jpg');
         }
         if (JFile::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_XL.jpg')) {
             JFile::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_XL.jpg');
         }
         if (JFile::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_Generic.jpg')) {
             JFile::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_Generic.jpg');
         }
         $row->image_caption = '';
         $row->image_credits = '';
     }
     //Attachments
     $attachments = JRequest::getVar('attachment_file', NULL, 'FILES', 'array');
     $attachments_names = JRequest::getVar('attachment_name', '', 'POST', 'array');
     $attachments_titles = JRequest::getVar('attachment_title', '', 'POST', 'array');
     $attachments_title_attributes = JRequest::getVar('attachment_title_attribute', '', 'POST', 'array');
     $attachments_existing_files = JRequest::getVar('attachment_existing_file', '', 'POST', 'array');
     $attachmentFiles = array();
     if (count($attachments)) {
         foreach ($attachments as $k => $l) {
             foreach ($l as $i => $v) {
                 if (!array_key_exists($i, $attachmentFiles)) {
                     $attachmentFiles[$i] = array();
                 }
                 $attachmentFiles[$i][$k] = $v;
             }
         }
         $path = $params->get('attachmentsFolder', NULL);
         if (is_null($path)) {
             $savepath = JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'attachments';
         } else {
             $savepath = $path;
         }
         $counter = 0;
         foreach ($attachmentFiles as $key => $file) {
             if ($file["tmp_name"] || $attachments_existing_files[$key]) {
                 if ($attachments_existing_files[$key]) {
                     $src = JPATH_SITE . DS . JPath::clean($attachments_existing_files[$key]);
                     $copyName = basename($src);
                     $dest = $savepath . DS . $copyName;
                     if (JFile::exists($dest)) {
                         $existingFileName = JFile::getName($dest);
                         $ext = JFile::getExt($existingFileName);
                         $basename = JFile::stripExt($existingFileName);
                         $newFilename = $basename . '_' . time() . '.' . $ext;
                         $copyName = $newFilename;
                         $dest = $savepath . DS . $newFilename;
                     }
                     JFile::copy($src, $dest);
                     $attachment = JTable::getInstance('K2Attachment', 'Table');
                     $attachment->itemID = $row->id;
                     $attachment->filename = $copyName;
                     $attachment->title = empty($attachments_titles[$counter]) ? $filename : $attachments_titles[$counter];
                     $attachment->titleAttribute = empty($attachments_title_attributes[$counter]) ? $filename : $attachments_title_attributes[$counter];
                     $attachment->store();
                 } else {
                     $handle = new Upload($file);
                     if ($handle->uploaded) {
                         $handle->file_auto_rename = true;
                         $handle->allowed[] = 'application/x-zip';
                         $handle->allowed[] = 'application/download';
                         $handle->Process($savepath);
                         $filename = $handle->file_dst_name;
                         $handle->Clean();
                         $attachment = JTable::getInstance('K2Attachment', 'Table');
                         $attachment->itemID = $row->id;
                         $attachment->filename = $filename;
                         $attachment->title = empty($attachments_titles[$counter]) ? $filename : $attachments_titles[$counter];
                         $attachment->titleAttribute = empty($attachments_title_attributes[$counter]) ? $filename : $attachments_title_attributes[$counter];
                         $attachment->store();
                     } else {
                         $mainframe->enqueueMessage($handle->error, 'error');
                         $mainframe->redirect('index.php?option=com_k2&view=items');
                     }
                 }
             }
             $counter++;
         }
     }
     //Gallery
     $flickrGallery = JRequest::getVar('flickrGallery');
     if ($flickrGallery) {
         $row->gallery = '{gallery}' . $flickrGallery . '{/gallery}';
     }
     if (isset($files['gallery']) && $files['gallery']['error'] == 0 && !JRequest::getBool('del_gallery')) {
         $handle = new Upload($files['gallery']);
         $handle->file_auto_rename = true;
         $savepath = JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'galleries';
         $handle->allowed = array("application/download", "application/rar", "application/x-rar-compressed", "application/arj", "application/gnutar", "application/x-bzip", "application/x-bzip2", "application/x-compressed", "application/x-gzip", "application/x-zip-compressed", "application/zip", "multipart/x-zip", "multipart/x-gzip", "application/x-unknown", "application/x-zip");
         if ($handle->uploaded) {
             $handle->Process($savepath);
             $handle->Clean();
             if (JFolder::exists($savepath . DS . $row->id)) {
                 JFolder::delete($savepath . DS . $row->id);
             }
             if (!JArchive::extract($savepath . DS . $handle->file_dst_name, $savepath . DS . $row->id)) {
                 $mainframe->enqueueMessage(JText::_('K2_GALLERY_UPLOAD_ERROR_CANNOT_EXTRACT_ARCHIVE'), 'error');
                 $mainframe->redirect('index.php?option=com_k2&view=items');
             } else {
                 $row->gallery = '{gallery}' . $row->id . '{/gallery}';
             }
             JFile::delete($savepath . DS . $handle->file_dst_name);
             $handle->Clean();
         } else {
             $mainframe->enqueueMessage($handle->error, 'error');
             $mainframe->redirect('index.php?option=com_k2&view=items');
         }
     }
     if (JRequest::getBool('del_gallery')) {
         $current = JTable::getInstance('K2Item', 'Table');
         $current->load($row->id);
         if (JFolder::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'galleries' . DS . $current->id)) {
             JFolder::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'galleries' . DS . $current->id);
         }
         $row->gallery = '';
     }
     //Video
     if (!JRequest::getBool('del_video')) {
         if (isset($files['video']) && $files['video']['error'] == 0) {
             $videoExtensions = array("flv", "mp4", "ogv", "webm", "f4v", "m4v", "3gp", "3g2", "mov", "mpeg", "mpg", "avi", "wmv", "divx");
             $audioExtensions = array("mp3", "aac", "m4a", "ogg", "wma");
             $validExtensions = array_merge($videoExtensions, $audioExtensions);
             $filetype = JFile::getExt($files['video']['name']);
             if (!in_array($filetype, $validExtensions)) {
                 $mainframe->enqueueMessage(JText::_('K2_INVALID_VIDEO_FILE'), 'error');
                 $mainframe->redirect('index.php?option=com_k2&view=items');
             }
             if (in_array($filetype, $videoExtensions)) {
                 $savepath = JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'videos';
             } else {
                 $savepath = JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'audio';
             }
             $filename = JFile::stripExt($files['video']['name']);
             JFile::upload($files['video']['tmp_name'], $savepath . DS . $row->id . '.' . $filetype);
             $filetype = JFile::getExt($files['video']['name']);
             $row->video = '{' . $filetype . '}' . $row->id . '{/' . $filetype . '}';
         }
     } else {
         $current = JTable::getInstance('K2Item', 'Table');
         $current->load($row->id);
         preg_match_all("#^{(.*?)}(.*?){#", $current->video, $matches, PREG_PATTERN_ORDER);
         $videotype = $matches[1][0];
         $videofile = $matches[2][0];
         if (in_array($videotype, $videoExtensions)) {
             if (JFile::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'videos' . DS . $videofile . '.' . $videotype)) {
                 JFile::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'videos' . DS . $videofile . '.' . $videotype);
             }
         }
         if (in_array($videotype, $audioExtensions)) {
             if (JFile::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'audio' . DS . $videofile . '.' . $videotype)) {
                 JFile::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'audio' . DS . $videofile . '.' . $videotype);
             }
         }
         $row->video = '';
         $row->video_caption = '';
         $row->video_credits = '';
     }
     //Extra fields
     $objects = array();
     $variables = JRequest::get('post', 2);
     foreach ($variables as $key => $value) {
         if ((bool) JString::stristr($key, 'K2ExtraField_')) {
             $object = new JObject();
             $object->set('id', JString::substr($key, 13));
             if (is_string($value)) {
                 $value = trim($value);
             }
             $object->set('value', $value);
             unset($object->_errors);
             $objects[] = $object;
         }
     }
     $csvFiles = JRequest::get('files');
     foreach ($csvFiles as $key => $file) {
         if ((bool) JString::stristr($key, 'K2ExtraField_')) {
             $object = new JObject();
             $object->set('id', JString::substr($key, 13));
             $csvFile = $file['tmp_name'][0];
             if (!empty($csvFile) && JFile::getExt($file['name'][0]) == 'csv') {
                 $handle = @fopen($csvFile, 'r');
                 $csvData = array();
                 while (($data = fgetcsv($handle, 1000)) !== FALSE) {
                     $csvData[] = $data;
                 }
                 fclose($handle);
                 $object->set('value', $csvData);
             } else {
                 require_once JPATH_COMPONENT_ADMINISTRATOR . DS . 'lib' . DS . 'JSON.php';
                 $json = new Services_JSON();
                 $object->set('value', $json->decode(JRequest::getVar('K2CSV_' . $object->id)));
                 if (JRequest::getBool('K2ResetCSV_' . $object->id)) {
                     $object->set('value', null);
                 }
             }
             unset($object->_errors);
             $objects[] = $object;
         }
     }
     require_once JPATH_COMPONENT_ADMINISTRATOR . DS . 'lib' . DS . 'JSON.php';
     $json = new Services_JSON();
     $row->extra_fields = $json->encode($objects);
     require_once JPATH_COMPONENT_ADMINISTRATOR . DS . 'models' . DS . 'extrafield.php';
     $extraFieldModel = K2Model::getInstance('ExtraField', 'K2Model');
     $row->extra_fields_search = '';
     foreach ($objects as $object) {
         $row->extra_fields_search .= $extraFieldModel->getSearchValue($object->id, $object->value);
         $row->extra_fields_search .= ' ';
     }
     //Tags
     if ($user->gid < 24 && $params->get('lockTags')) {
         $params->set('taggingSystem', 0);
     }
     $db = JFactory::getDBO();
     $query = "DELETE FROM #__k2_tags_xref WHERE itemID={intval({$row->id})}";
     $db->setQuery($query);
     $db->query();
     if ($params->get('taggingSystem')) {
         if ($user->gid < 24 && $params->get('lockTags')) {
             JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
         }
         $tags = JRequest::getVar('tags', NULL, 'POST', 'array');
         if (count($tags)) {
             $tags = array_unique($tags);
             foreach ($tags as $tag) {
                 $tag = JString::trim($tag);
                 if ($tag) {
                     $tagID = false;
                     $K2Tag = JTable::getInstance('K2Tag', 'Table');
                     $K2Tag->name = $tag;
                     // Tag has been filtred and does not exist
                     if ($K2Tag->check()) {
                         $K2Tag->published = 1;
                         if ($K2Tag->store()) {
                             $tagID = $K2Tag->id;
                         }
                     } else {
                         if ($K2Tag->name) {
                             $query = "SELECT id FROM #__k2_tags WHERE name=" . $db->Quote($K2Tag->name);
                             $db->setQuery($query);
                             $tagID = $db->loadResult();
                         }
                     }
                     if ($tagID) {
                         $query = "INSERT INTO #__k2_tags_xref (`id`, `tagID`, `itemID`) VALUES (NULL, {intval({$tagID})}, {intval({$row->id})})";
                         $db->setQuery($query);
                         $db->query();
                     }
                 }
             }
         }
     } else {
         $tags = JRequest::getVar('selectedTags', NULL, 'POST', 'array');
         if (count($tags)) {
             foreach ($tags as $tagID) {
                 $query = "INSERT INTO #__k2_tags_xref (`id`, `tagID`, `itemID`) VALUES (NULL, {intval({$tagID})}, {intval({$row->id})})";
                 $db->setQuery($query);
                 $db->query();
             }
         }
     }
     // If we are in front-end check publishing permissions properly.
     if ($front) {
         // New items require the "Publish items" permission.
         if ($isNew && $row->published && !K2HelperPermissions::canPublishItem($row->catid)) {
             $row->published = 0;
             $mainframe->enqueueMessage(JText::_('K2_YOU_DONT_HAVE_THE_PERMISSION_TO_PUBLISH_ITEMS'), 'notice');
         }
         // Existing items require either the "Publish items" or the "Allow editing of already published items" permission.
         if (!$isNew && $row->published) {
             $canEditPublished = $isAlreadyPublished && K2HelperPermissions::canEditPublished($row->catid);
             if (!K2HelperPermissions::canPublishItem($row->catid) && !$canEditPublished) {
                 $row->published = 0;
                 $mainframe->enqueueMessage(JText::_('K2_YOU_DONT_HAVE_THE_PERMISSION_TO_PUBLISH_ITEMS'), 'notice');
             }
         }
         // If user has cannot publish the item then also cannot make it featured
         if (!K2HelperPermissions::canPublishItem($row->catid)) {
             if ($isNew) {
                 $row->featured = 0;
             } else {
                 $row->featured = $currentFeaturedState;
             }
         }
     }
     $query = "UPDATE #__k2_items SET \n        video_caption = " . $db->Quote($row->video_caption) . ", \n        video_credits = " . $db->Quote($row->video_credits) . ", ";
     if (!is_null($row->video)) {
         $query .= " video = " . $db->Quote($row->video) . ", ";
     }
     if (!is_null($row->gallery)) {
         $query .= " gallery = " . $db->Quote($row->gallery) . ", ";
     }
     $query .= " extra_fields = " . $db->Quote($row->extra_fields) . ", \n        extra_fields_search = " . $db->Quote($row->extra_fields_search) . " ,\n        published = " . $db->Quote($row->published) . " \n        WHERE id = " . $row->id;
     $db->setQuery($query);
     if (!$db->query()) {
         $mainframe->enqueueMessage($db->getErrorMsg(), 'error');
         $mainframe->redirect('index.php?option=com_k2&view=items');
     }
     $row->checkin();
     $cache = JFactory::getCache('com_k2');
     $cache->clean();
     $dispatcher->trigger('onAfterK2Save', array(&$row, $isNew));
     JPluginHelper::importPlugin('content');
     if (K2_JVERSION != '15') {
         $dispatcher->trigger('onContentAfterSave', array('com_k2.item', &$row, $isNew));
     } else {
         $dispatcher->trigger('onAfterContentSave', array(&$row, $isNew));
     }
     //Trigger the finder after save event
     $dispatcher = JDispatcher::getInstance();
     JPluginHelper::importPlugin('finder');
     $results = $dispatcher->trigger('onFinderAfterSave', array('com_k2.item', $row, $isNew));
     switch (JRequest::getCmd('task')) {
         case 'apply':
             $msg = JText::_('K2_CHANGES_TO_ITEM_SAVED');
             $link = 'index.php?option=com_k2&view=item&cid=' . $row->id;
             break;
         case 'saveAndNew':
             $msg = JText::_('K2_ITEM_SAVED');
             $link = 'index.php?option=com_k2&view=item';
             break;
         case 'save':
         default:
             $msg = JText::_('K2_ITEM_SAVED');
             if ($front) {
                 $link = 'index.php?option=com_k2&view=item&task=edit&cid=' . $row->id . '&tmpl=component&Itemid=' . JRequest::getInt('Itemid');
             } else {
                 $link = 'index.php?option=com_k2&view=items';
             }
             break;
     }
     $mainframe->enqueueMessage($msg);
     $mainframe->redirect($link);
 }
Ejemplo n.º 6
0
    public function save($item, $front = false)
    {

        jimport('joomla.filesystem.file');
        jimport('joomla.filesystem.folder');
        jimport('joomla.filesystem.archive');
        require_once (JPATH_ADMINISTRATOR.'/components/com_k2/lib/class.upload.php');
        $db = JFactory::getDBO();
        $user = JFactory::getUser();
        $row = JTable::getInstance('K2Item', 'Table');
        $params = JComponentHelper::getParams('com_k2');
        $nullDate = $db->getNullDate();

        if (!$row->bind($item))
        {
            $this->setError($row->getError());
            return false;
        }

        $row->catid = (int)$row->catid;

        if ($front && $row->id == NULL)
        {
            JLoader::register('K2HelperPermissions', JPATH_SITE.DS.'components'.DS.'com_k2'.DS.'helpers'.DS.'permissions.php');
            if (!K2HelperPermissions::canAddItem($row->catid))
            {
                $this->setError(JText::_('K2_YOU_ARE_NOT_ALLOWED_TO_POST_TO_THIS_CATEGORY_SAVE_FAILED'));
                return false;
            }
        }

        ($row->id) ? $isNew = false : $isNew = true;

        if ($params->get('xssFiltering'))
        {
            $filter = new JFilterInput( array(), array(), 1, 1, 0);
            $item['articletext'] = $filter->clean($item['articletext']);
        }
        $pattern = '#<hr\s+id=("|\')system-readmore("|\')\s*\/*>#i';
        $tagPos = preg_match($pattern, $item['articletext']);
        if ($tagPos == 0)
        {
            $row->introtext = $item['articletext'];
            $row->fulltext = '';
        }
        else
        {
            list($row->introtext, $row->fulltext) = preg_split($pattern, $item['articletext'], 2);
        }

        if ($row->id)
        {
            $datenow = JFactory::getDate();
            $row->modified = $datenow->toSql();
            $row->modified_by = $user->get('id');
        }
        else
        {
            $row->ordering = $row->getNextOrder("catid = {$row->catid} AND trash = 0");
            if ($row->featured)
                $row->featured_ordering = $row->getNextOrder("featured = 1 AND trash = 0", 'featured_ordering');
        }

        $row->created_by = $row->created_by ? $row->created_by : $user->get('id');

        if ($front)
        {
            $K2Permissions = K2Permissions::getInstance();
            if (!$K2Permissions->permissions->get('editAll'))
            {
                $row->created_by = $user->get('id');
            }
        }

        if ($row->created && strlen(trim($row->created)) <= 10)
        {
            $row->created .= ' 00:00:00';
        }

        $config = JFactory::getConfig();
        $tzoffset = $config->get('config.offset');
        $date = JFactory::getDate($row->created, $tzoffset);
        $row->created = $date->toSql();

        if (strlen(trim($row->publish_up)) <= 10)
        {
            $row->publish_up .= ' 00:00:00';
        }

        $date = JFactory::getDate($row->publish_up, $tzoffset);
        $row->publish_up = $date->toSql();

        if (trim($row->publish_down) == JText::_('K2_NEVER') || trim($row->publish_down) == '')
        {
            $row->publish_down = $nullDate;
        }
        else
        {
            if (strlen(trim($row->publish_down)) <= 10)
            {
                $row->publish_down .= ' 00:00:00';
            }
            $date = JFactory::getDate($row->publish_down, $tzoffset);
            $row->publish_down = $date->toSql();
        }

        if (!$row->check())
        {
            $this->setError($row->getError());
            return false;
        }

        $dispatcher = JDispatcher::getInstance();
        JPluginHelper::importPlugin('k2');
        $result = $dispatcher->trigger('onBeforeK2Save', array(&$row, $isNew));
        if (in_array(false, $result, true))
        {
            $this->setError($row->getError());
            return false;
        }

        //Trigger the finder before save event
        $dispatcher = JDispatcher::getInstance();
        JPluginHelper::importPlugin('finder');
        $results = $dispatcher->trigger('onFinderBeforeSave', array('com_k2.item', $row, $isNew));

        if (!$row->store())
        {
            $this->setError($row->getError());
            return false;
        }

        if (!$params->get('disableCompactOrdering'))
        {
            $row->reorder("catid = {$row->catid} AND trash = 0");
        }
        if ($row->featured && !$params->get('disableCompactOrdering'))
        {
            $row->reorder("featured = 1 AND trash = 0", 'featured_ordering');
        }

        // Image copy
        $src = md5("Image".$item['ref_id']);        
        $target = md5("Image".$row->id);
        $sizes = array('XL', 'L', 'M', 'S', 'XS');
        $savepath = JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache';
        foreach($sizes as $size)
        {
            if(JFile::exists($savepath.DS.$src.'_'.$size.'.jpg') && !JFile::exists($savepath.DS.$target.'_'.$size.'.jpg'))
            {
                JFile::copy($savepath.DS.$src.'_'.$size.'.jpg', $savepath.DS.$target.'_'.$size.'.jpg');
            }
        }

        //Extra fields
        $objects = array();
        $variables = JRequest::get('post', 4);
        foreach ($variables as $key => $value)
        {
            if (( bool )JString::stristr($key, 'K2ExtraField_'))
            {
                $object = new JObject;
                $object->set('id', JString::substr($key, 13));
                $object->set('value', $value);
                unset($object->_errors);
                $objects[] = $object;
            }
        }

        $csvFiles = JRequest::get('files');
        foreach ($csvFiles as $key => $file)
        {
            if (( bool )JString::stristr($key, 'K2ExtraField_'))
            {
                $object = new JObject;
                $object->set('id', JString::substr($key, 13));
                $csvFile = $file['tmp_name'][0];
                if (!empty($csvFile) && JFile::getExt($file['name'][0]) == 'csv')
                {
                    $handle = @fopen($csvFile, 'r');
                    $csvData = array();
                    while (($data = fgetcsv($handle, 1000)) !== FALSE)
                    {
                        $csvData[] = $data;
                    }
                    fclose($handle);
                    $object->set('value', $csvData);
                }
                else
                {
                    require_once (JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'lib'.DS.'JSON.php');
                    $json = new Services_JSON;
                    $object->set('value', $json->decode(JRequest::getVar('K2CSV_'.$object->id)));
                    if (JRequest::getBool('K2ResetCSV_'.$object->id))
                        $object->set('value', null);
                }
                unset($object->_errors);
                $objects[] = $object;
            }
        }

        require_once (JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'lib'.DS.'JSON.php');
        $json = new Services_JSON;
        $row->extra_fields = $json->encode($objects);

        $row->extra_fields_search = '';

        foreach ($objects as $object)
        {
            $row->extra_fields_search .= $this->getSearchValue($object->id, $object->value);
            $row->extra_fields_search .= ' ';
        }

        $query = "DELETE FROM #__k2_tags_xref WHERE itemID={intval($row->id)}";
        $db->setQuery($query);
        $db->query();

        $tags = JRequest::getVar('tags', NULL, 'POST', 'array');
        if (count($tags))
        {
            $tags = array_unique($tags);
            foreach ($tags as $tag)
            {
                $tag = JString::str_ireplace('-', '', $tag);
                $query = "SELECT id FROM #__k2_tags WHERE name=".$db->Quote($tag);
                $db->setQuery($query);
                $tagID = $db->loadResult();
                if ($tagID)
                {
                    $query = "INSERT INTO #__k2_tags_xref (`id`, `tagID`, `itemID`) VALUES (NULL, {intval($tagID)}, {intval($row->id)})";
                    $db->setQuery($query);
                    $db->query();
                }
                else
                {
                    $K2Tag = JTable::getInstance('K2Tag', 'Table');
                    $K2Tag->name = $tag;
                    $K2Tag->published = 1;
                    $K2Tag->check();
                    $K2Tag->store();
                    $query = "INSERT INTO #__k2_tags_xref (`id`, `tagID`, `itemID`) VALUES (NULL, {intval($K2Tag->id)}, {intval($row->id)})";
                    $db->setQuery($query);
                    $db->query();
                }
            }
        }

        $files = JRequest::get('files');

        //Image
        if ((int)$params->get('imageMemoryLimit'))
        {
            ini_set('memory_limit', (int)$params->get('imageMemoryLimit').'M');
        }

        if ($front)
        {
            if (!K2HelperPermissions::canPublishItem($row->catid) && $row->published)
            {
                $row->published = 0;
                $this->setError(JText::_('K2_YOU_DONT_HAVE_THE_PERMISSION_TO_PUBLISH_ITEMS'));
            }
        }

        $query = "UPDATE #__k2_items SET video_caption = ".$db->Quote($row->video_caption).", video_credits = ".$db->Quote($row->video_credits).", ";

        if (!is_null($row->video))
        {
            $query .= " video = ".$db->Quote($row->video).", ";
        }
        if (!is_null($row->gallery))
        {
            $query .= " gallery = ".$db->Quote($row->gallery).", ";
        }
        $query .= " extra_fields = ".$db->Quote($row->extra_fields).", extra_fields_search = ".$db->Quote($row->extra_fields_search)." , published = ".$db->Quote($row->published)." WHERE id = ".$row->id;
        $db->setQuery($query);

        if (!$db->query())
        {
            $this->setError($db->getErrorMsg());
            return false;
        }

        $row->checkin();

        $cache = JFactory::getCache('com_k2');
        $cache->clean();

        //$dispatcher->trigger('onAfterK2Save', array(&$row, $isNew));
        $dispatcher->trigger('onContentAfterSave', array(&$row, $isNew));

        //Trigger the finder after save event
        $dispatcher = JDispatcher::getInstance();
        JPluginHelper::importPlugin('finder');
        $results = $dispatcher->trigger('onFinderAfterSave', array('com_k2.item', $row, $isNew));

        return $row->id;
    }
Ejemplo n.º 7
0
    function display($tpl = null)
    {
        $mainframe =& JFactory::getApplication();
        $user =& JFactory::getUser();
        $document =& JFactory::getDocument();
        $params =& K2HelperUtilities::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();
        // Does the item exists?
        if (!is_object($item) || !$item->id) {
            JError::raiseError(404, JText::_('K2_ITEM_NOT_FOUND'));
        }
        // Prepare item
        $item = $model->prepareItem($item, $view, $task);
        // Plugins
        $item = $model->execPlugins($item, $view, $task);
        // User K2 plugins
        $item->event->K2UserDisplay = '';
        if (isset($item->author) && is_object($item->author->profile) && isset($item->author->profile->id)) {
            $dispatcher =& JDispatcher::getInstance();
            JPluginHelper::importPlugin('k2');
            $results = $dispatcher->trigger('onK2UserDisplay', array(&$item->author->profile, &$params, $limitstart));
            $item->event->K2UserDisplay = trim(implode("\n", $results));
        }
        // Access check
        if ($this->getLayout() == 'form') {
            JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
        }
        if (K2_JVERSION == '16') {
            if (!in_array($item->access, $user->authorisedLevels()) || !in_array($item->category->access, $user->authorisedLevels())) {
                JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
            }
        } else {
            if ($item->access > $user->get('aid', 0) || $item->category->access > $user->get('aid', 0)) {
                JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
            }
        }
        // Published check
        if (!$item->published || $item->trash) {
            JError::raiseError(404, JText::_('K2_ITEM_NOT_FOUND'));
        }
        if ($item->publish_up != $nullDate && $item->publish_up > $now) {
            JError::raiseError(404, JText::_('K2_ITEM_NOT_FOUND'));
        }
        if ($item->publish_down != $nullDate && $item->publish_down < $now) {
            JError::raiseError(404, JText::_('K2_ITEM_NOT_FOUND'));
        }
        if (!$item->category->published || $item->category->trash) {
            JError::raiseError(404, JText::_('K2_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') . '"
							});
						}
						$K2(window).load(function() {
							showRecaptcha();
						});
						';
                        $document->addScriptDeclaration($js);
                    }
                }
                // Check for inline comment moderation
                if (!$user->guest && $user->id == $item->created_by && $params->get('inlineCommentsModeration')) {
                    $inlineCommentsModeration = true;
                    $commentsPublished = false;
                } else {
                    $inlineCommentsModeration = false;
                    $commentsPublished = true;
                }
                $this->assignRef('inlineCommentsModeration', $inlineCommentsModeration);
                // Flag spammer link
                $reportSpammerFlag = false;
                if (K2_JVERSION == '16') {
                    if ($user->authorise('core.admin', 'com_k2')) {
                        $reportSpammerFlag = true;
                        $document =& JFactory::getDocument();
                        $document->addScriptDeclaration('var K2Language = ["' . JText::_('K2_REPORT_USER_WARNING', true) . '"];');
                    }
                } else {
                    if ($user->gid > 24) {
                        $reportSpammerFlag = true;
                    }
                }
                $limit = $params->get('commentsLimit');
                $comments = $model->getItemComments($item->id, $limitstart, $limit, $commentsPublished);
                $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;
                    }
                    if ($reportSpammerFlag && $comments[$i]->userID > 0) {
                        $comments[$i]->reportUserLink = JRoute::_('index.php?option=com_k2&view=comments&task=reportSpammer&id=' . $comments[$i]->userID . '&format=raw');
                    } else {
                        $comments[$i]->reportUserLink = false;
                    }
                }
                $item->comments = $comments;
                jimport('joomla.html.pagination');
                $total = $item->numOfComments;
                $pagination = new JPagination($total, $limitstart, $limit);
            }
        }
        // Author's latest items
        if ($item->params->get('itemAuthorLatest') && $item->created_by_alias == '') {
            $model =& $this->getModel('itemlist');
            $authorLatestItems = $model->getAuthorLatest($item->id, $item->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 ($item->params->get('itemRelated') && isset($item->tags) && count($item->tags)) {
            $model =& $this->getModel('itemlist');
            $relatedItems = $model->getRelatedItems($item->id, $item->tags, $item->params);
            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 ($item->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->toString();
        // Email link
        if (K2_JVERSION == '16') {
            require_once JPATH_SITE . '/components/com_mailto/helpers/mailto.php';
            $template = $mainframe->getTemplate();
            $item->emailLink = JRoute::_('index.php?option=com_mailto&tmpl=component&template=' . $template . '&link=' . MailToHelper::addLink($item->absoluteURL));
        } else {
            require_once JPATH_SITE . DS . 'components' . DS . 'com_mailto' . DS . 'helpers' . DS . 'mailto.php';
            $item->emailLink = JRoute::_('index.php?option=com_mailto&tmpl=component&link=' . MailToHelper::addLink($item->absoluteURL));
        }
        // Twitter link (legacy code)
        if ($params->get('twitterUsername')) {
            $item->twitterURL = 'http://twitter.com/intent/tweet?text=' . urlencode($item->title) . '&amp;url=' . urlencode($item->absoluteURL) . '&amp;via=' . $params->get('twitterUsername');
        } else {
            $item->twitterURL = 'http://twitter.com/intent/tweet?text=' . urlencode($item->title) . '&amp;url=' . urlencode($item->absoluteURL);
        }
        // Social link
        $item->socialLink = urlencode($item->absoluteURL);
        // Set page title
        $menus =& JSite::getMenu();
        $menu = $menus->getActive();
        if (is_object($menu) && isset($menu->query['view']) && $menu->query['view'] == 'item' && isset($menu->query['id']) && $menu->query['id'] == $item->id) {
            $menu_params = new JParameter($menu->params);
            if (!$menu_params->get('page_title')) {
                $params->set('page_title', $item->cleanTitle);
            }
        } else {
            $params->set('page_title', $item->cleanTitle);
        }
        if (K2_JVERSION == '16') {
            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'));
        // Set pathway
        $menus =& JSite::getMenu();
        $menu = $menus->getActive();
        $pathway =& $mainframe->getPathWay();
        if ($menu) {
            if ($menu->query['view'] != 'item' || $menu->query['id'] != $item->id) {
                if (!isset($menu->query['task']) || $menu->query['task'] != 'category' || $menu->query['id'] != $item->catid) {
                    $pathway->addItem($item->category->name, $item->category->link);
                }
                $pathway->addItem($item->cleanTitle, '');
            }
        }
        // Set metadata
        if ($item->metadesc) {
            $document->setDescription($item->metadesc);
        } else {
            $metaDescItem = preg_replace("#{(.*?)}(.*?){/(.*?)}#s", '', $item->introtext . ' ' . $item->fulltext);
            $metaDescItem = K2HelperUtilities::characterLimit($metaDescItem, $params->get('metaDescLimit', 150));
            $metaDescItem = htmlentities($metaDescItem, ENT_QUOTES, 'utf-8');
            $document->setDescription($metaDescItem);
        }
        if ($item->metakey) {
            $document->setMetadata('keywords', $item->metakey);
        } else {
            if (isset($item->tags) && count($item->tags)) {
                $tmp = array();
                foreach ($item->tags as $tag) {
                    $tmp[] = $tag->name;
                }
                $document->setMetadata('keywords', implode(',', $tmp));
            }
        }
        // Menu metadata for Joomla! 1.6/1.7 (Overrides the current metadata if set)
        if (K2_JVERSION == '16') {
            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'));
        }
        if ($mainframe->getCfg('MetaTitle') == '1') {
            $document->setMetadata('title', $item->title);
        }
        if ($mainframe->getCfg('MetaAuthor') == '1' && isset($item->author->name)) {
            $document->setMetadata('author', $item->author->name);
        }
        $mdata = new JParameter($item->metadata);
        $mdata = $mdata->toArray();
        foreach ($mdata as $k => $v) {
            if ($k == 'robots' || $k == 'author') {
                if ($v) {
                    $document->setMetadata($k, $v);
                }
            }
        }
        // Load Facebook meta tag for item image
        $facebookImage = 'image' . $params->get('facebookImage', 'Small');
        if ($item->{$facebookImage}) {
            $document->setMetaData('image', substr(JURI::root(), 0, -1) . str_replace(JURI::root(true), '', $item->{$facebookImage}));
        }
        // 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);
    }
Ejemplo n.º 8
0
    function edit()
    {
        $mainframe =& JFactory::getApplication();
        jimport('joomla.filesystem.file');
        jimport('joomla.html.pane');
        $db =& JFactory::getDBO();
        JHTML::_('behavior.mootools');
        $document =& JFactory::getDocument();
        $document->addScript(JURI::root() . 'administrator/components/com_k2/lib/Autocompleter.js');
        $document->addScript(JURI::root() . 'administrator/components/com_k2/lib/observer.js');
        $document->addScript(JURI::root() . 'administrator/components/com_k2/lib/simpletabs_1.3.js');
        //$document->addScript(JURI::root().'administrator/components/com_k2/js/k2.js'); // Core JS
        $document->addScript(JURI::root() . 'administrator/components/com_k2/js/k2.mootools.js');
        // Mootools based JS
        $document->addCustomTag('
        
<!-- K2 by JoomlaWorks (start) -->
		
	<!-- Load Khepri styling -->
	<link rel="stylesheet" href="' . JURI::root() . 'administrator/templates/system/css/system.css" type="text/css" />
	<link href="' . JURI::root() . 'administrator/templates/khepri/css/template.css" rel="stylesheet" type="text/css" />
	<!--[if IE 7]>
	<link href="' . JURI::root() . 'administrator/templates/khepri/css/ie7.css" rel="stylesheet" type="text/css" />
	<![endif]-->
	<!--[if lte IE 6]>
	<link href="' . JURI::root() . 'administrator/templates/khepri/css/ie6.css" rel="stylesheet" type="text/css" />
	<![endif]-->
	<link rel="stylesheet" type="text/css" href="' . JURI::root() . 'administrator/templates/khepri/css/rounded.css" />
	
	<!-- Load K2 styling -->
	<link href="' . JURI::root() . 'administrator/components/com_k2/css/k2.css" rel="stylesheet" type="text/css" />
	<!--[if IE 7]>
	<link href="' . JURI::root() . 'administrator/components/com_k2/css/k2_ie7.css" rel="stylesheet" type="text/css" />
	<![endif]-->
	<!--[if lte IE 6]>
	<link href="' . JURI::root() . 'administrator/components/com_k2/css/k2_ie6.css" rel="stylesheet" type="text/css" />
	<![endif]-->
		
<!-- K2 by JoomlaWorks (end) -->

		');
        JRequest::setVar('tmpl', 'component');
        require_once JPATH_COMPONENT_ADMINISTRATOR . DS . 'models' . DS . 'item.php';
        $model = new K2ModelItem();
        $task = JRequest::getCmd('task');
        $user =& JFactory::getUser();
        if ($task == 'edit') {
            $item = $model->getData();
            JFilterOutput::objectHTMLSafe($item, ENT_QUOTES, 'video');
            if (!K2HelperPermissions::canEditItem($item->created_by, $item->catid)) {
                JError::raiseError(403, JText::_("ALERTNOTAUTH"));
            }
            if (JTable::isCheckedOut($user->get('id'), $item->checked_out)) {
                $msg = JText::sprintf('DESCBEINGEDITTED', JText::_('The item'), $item->title);
                $mainframe->redirect('index.php?option=com_k2&view=item&id=' . $item->id . '&tmpl=component', $msg);
            }
        } elseif ($task == 'add') {
            if (!K2HelperPermissions::canAddItem()) {
                JError::raiseError(403, JText::_("ALERTNOTAUTH"));
            }
            JTable::addIncludePath(JPATH_COMPONENT . DS . 'tables');
            $item =& JTable::getInstance('K2Item', 'Table');
            $createdate =& JFactory::getDate();
            $item->published = 1;
            $item->publish_up = $createdate->toUnix();
            $item->publish_down = JText::_('Never');
            $item->created = $createdate->toUnix();
            $item->modified = $db->getNullDate();
        }
        if ($item->id) {
            $item->checkout($user->get('id'));
        }
        $item->created = JHTML::_('date', $item->created, '%Y-%m-%d %H:%M:%S');
        $item->publish_up = JHTML::_('date', $item->publish_up, '%Y-%m-%d %H:%M:%S');
        if (JHTML::_('date', $item->publish_down, '%Y') <= 1969 || $item->publish_down == $db->getNullDate()) {
            $item->publish_down = JText::_('Never');
        } else {
            $item->publish_down = JHTML::_('date', $item->publish_down, '%Y-%m-%d %H:%M:%S');
        }
        $params =& JComponentHelper::getParams('com_k2');
        $wysiwyg =& JFactory::getEditor();
        if ($params->get("mergeEditors")) {
            if (JString::strlen($item->fulltext) > 1) {
                $textValue = $item->introtext . "<hr id=\"system-readmore\" />" . $item->fulltext;
            } else {
                $textValue = $item->introtext;
            }
            $text = $wysiwyg->display('text', $textValue, '100%', '400', '40', '5', array('pagebreak'));
            $this->assignRef('text', $text);
        } else {
            $introtext = $wysiwyg->display('introtext', $item->introtext, '100%', '400', '40', '5', array('pagebreak', 'readmore'));
            $this->assignRef('introtext', $introtext);
            $fulltext = $wysiwyg->display('fulltext', $item->fulltext, '100%', '400', '40', '5', array('pagebreak', 'readmore'));
            $this->assignRef('fulltext', $fulltext);
        }
        $lists = array();
        $lists['published'] = JHTML::_('select.booleanlist', 'published', 'class="inputbox"', $item->published);
        $lists['access'] = JHTML::_('list.accesslevel', $item);
        $query = "SELECT ordering AS value, title AS text FROM #__k2_items WHERE catid={$item->catid}";
        $lists['ordering'] = JHTML::_('list.specificordering', $item, $item->id, $query);
        require_once JPATH_COMPONENT_ADMINISTRATOR . DS . 'models' . DS . 'categories.php';
        $categoriesModel = new K2ModelCategories();
        $categories = $categoriesModel->categoriesTree();
        $lists['catid'] = JHTML::_('select.genericlist', $categories, 'catid', 'class="inputbox"', 'value', 'text', $item->catid);
        $lists['checkSIG'] = $model->checkSIG();
        $lists['checkAllVideos'] = $model->checkAllVideos();
        $remoteVideo = false;
        $providerVideo = false;
        $embedVideo = false;
        $options['startOffset'] = 0;
        if (stristr($item->video, 'remote}') !== false) {
            $remoteVideo = true;
            $options['startOffset'] = 1;
        }
        $providers = $model->getVideoProviders();
        if (count($providers)) {
            foreach ($providers as $provider) {
                $providersOptions[] = JHTML::_('select.option', $provider, $provider);
                if (stristr($item->video, "{{$provider}}") !== false) {
                    $providerVideo = true;
                    $options['startOffset'] = 2;
                }
            }
        }
        if (JString::substr($item->video, 0, 1) !== '{') {
            $embedVideo = true;
            $options['startOffset'] = 3;
        }
        $lists['uploadedVideo'] = !$remoteVideo && !$providerVideo && !$embedVideo ? true : false;
        if ($lists['uploadedVideo']) {
            $options['startOffset'] = 0;
        }
        $lists['remoteVideo'] = $remoteVideo ? preg_replace('%\\{[a-z0-9-_]*\\}(.*)\\{/[a-z0-9-_]*\\}%i', '\\1', $item->video) : '';
        $lists['remoteVideoType'] = $remoteVideo ? preg_replace('%\\{([a-z0-9-_]*)\\}.*\\{/[a-z0-9-_]*\\}%i', '\\1', $item->video) : '';
        $lists['providerVideo'] = $providerVideo ? preg_replace('%\\{[a-z0-9-_]*\\}(.*)\\{/[a-z0-9-_]*\\}%i', '\\1', $item->video) : '';
        $lists['providerVideoType'] = $providerVideo ? preg_replace('%\\{([a-z0-9-_]*)\\}.*\\{/[a-z0-9-_]*\\}%i', '\\1', $item->video) : '';
        $lists['embedVideo'] = $embedVideo ? $item->video : '';
        if (count($providers)) {
            $lists['providers'] = JHTML::_('select.genericlist', $providersOptions, 'videoProvider', '', 'value', 'text', $lists['providerVideoType']);
        }
        JPluginHelper::importPlugin('content', 'jw_sigpro');
        JPluginHelper::importPlugin('content', 'jw_sig');
        JPluginHelper::importPlugin('content', 'jw_allvideos');
        $dispatcher =& JDispatcher::getInstance();
        $params->set('galleries_rootfolder', 'media/k2/galleries');
        $params->set('thb_width', '150');
        $params->set('thb_height', '120');
        $params->set('popup_engine', 'mootools_slimbox');
        $params->set('enabledownload', '0');
        $item->text = $item->gallery;
        $dispatcher->trigger('onPrepareContent', array(&$item, &$params, null));
        $item->gallery = $item->text;
        if (!$embedVideo) {
            $params->set('vfolder', 'media/k2/videos');
            $item->text = $item->video;
            $dispatcher->trigger('onPrepareContent', array(&$item, &$params, null));
            $item->video = $item->text;
        } else {
            $item->video = '<div>' . $item->video . '</div>';
        }
        if (isset($item->created_by)) {
            $author =& JUser::getInstance($item->created_by);
            $item->author = $author->name;
        }
        if (isset($item->modified_by)) {
            $moderator =& JUser::getInstance($item->modified_by);
            $item->moderator = $moderator->name;
        }
        if ($task == 'edit') {
            $item->editor = $item->author;
        } else {
            $item->editor = $user->name;
        }
        require_once JPATH_COMPONENT_ADMINISTRATOR . DS . 'models' . DS . 'categories.php';
        $categoriesModel = new K2ModelCategories();
        $categories_option[] = JHTML::_('select.option', 0, JText::_('- Select category -'));
        $categories = $categoriesModel->categoriesTree();
        if (($task == 'add' || $task == 'edit') && !$user->authorize('com_k2', 'add', 'category', 'all')) {
            for ($i = 0; $i < sizeof($categories); $i++) {
                if (!$user->authorize('com_k2', 'add', 'category', $categories[$i]->value)) {
                    $categories[$i]->disable = true;
                }
            }
        }
        $categories_options = @array_merge($categories_option, $categories);
        $lists['categories'] = JHTML::_('select.genericlist', $categories_options, 'catid', '', 'value', 'text', $item->catid);
        JTable::addIncludePath(JPATH_COMPONENT . DS . 'tables');
        $category =& JTable::getInstance('K2Category', 'Table');
        $category->load($item->catid);
        require_once JPATH_COMPONENT_ADMINISTRATOR . DS . 'models' . DS . 'extrafield.php';
        $extraFieldModel = new K2ModelExtraField();
        if ($category->extraFieldsGroup) {
            $extraFields = $extraFieldModel->getExtraFieldsByGroup($category->extraFieldsGroup);
        } else {
            $extraFields = NULL;
        }
        for ($i = 0; $i < sizeof($extraFields); $i++) {
            $extraFields[$i]->element = $extraFieldModel->renderExtraField($extraFields[$i], $item->id);
        }
        if ($item->id) {
            $item->attachments = $model->getAttachments($item->id);
        } else {
            $item->attachments = NULL;
        }
        $tags = $model->getAvailableTags($item->id);
        $lists['tags'] = JHTML::_('select.genericlist', $tags, 'tags', 'multiple="multiple" size="10" ', 'id', 'name');
        if (isset($item->id)) {
            $item->tags = $model->getCurrentTags($item->id);
            $lists['selectedTags'] = JHTML::_('select.genericlist', $item->tags, 'selectedTags[]', 'multiple="multiple" size="10" ', 'id', 'name');
        } else {
            $lists['selectedTags'] = '<select size="10" multiple="multiple" id="selectedTags" name="selectedTags[]"></select>';
        }
        if (JFile::exists(JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . md5("Image" . $item->id) . '_L.jpg')) {
            $item->image = JURI::root() . 'media/k2/items/cache/' . md5("Image" . $item->id) . '_L.jpg';
        }
        if (JFile::exists(JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . md5("Image" . $item->id) . '_S.jpg')) {
            $item->thumb = JURI::root() . 'media/k2/items/cache/' . md5("Image" . $item->id) . '_S.jpg';
        }
        $lists['metadata'] = new JParameter($item->metadata);
        JPluginHelper::importPlugin('k2');
        $dispatcher =& JDispatcher::getInstance();
        $K2PluginsItemContent = $dispatcher->trigger('onRenderAdminForm', array(&$item, 'item', 'content'));
        $this->assignRef('K2PluginsItemContent', $K2PluginsItemContent);
        $K2PluginsItemImage = $dispatcher->trigger('onRenderAdminForm', array(&$item, 'item', 'image'));
        $this->assignRef('K2PluginsItemImage', $K2PluginsItemImage);
        $K2PluginsItemGallery = $dispatcher->trigger('onRenderAdminForm', array(&$item, 'item', 'gallery'));
        $this->assignRef('K2PluginsItemGallery', $K2PluginsItemGallery);
        $K2PluginsItemVideo = $dispatcher->trigger('onRenderAdminForm', array(&$item, 'item', 'video'));
        $this->assignRef('K2PluginsItemVideo', $K2PluginsItemVideo);
        $K2PluginsItemExtraFields = $dispatcher->trigger('onRenderAdminForm', array(&$item, 'item', 'extra-fields'));
        $this->assignRef('K2PluginsItemExtraFields', $K2PluginsItemExtraFields);
        $K2PluginsItemAttachments = $dispatcher->trigger('onRenderAdminForm', array(&$item, 'item', 'attachments'));
        $this->assignRef('K2PluginsItemAttachments', $K2PluginsItemAttachments);
        $K2PluginsItemOther = $dispatcher->trigger('onRenderAdminForm', array(&$item, 'item', 'other'));
        $this->assignRef('K2PluginsItemOther', $K2PluginsItemOther);
        $form = new JParameter('', JPATH_COMPONENT_ADMINISTRATOR . DS . 'models' . DS . 'item.xml');
        $form->loadINI($item->params);
        $this->assignRef('form', $form);
        $this->assignRef('extraFields', $extraFields);
        $this->assignRef('options', $options);
        $this->assignRef('row', $item);
        $this->assignRef('lists', $lists);
        $this->assignRef('params', $params);
        parent::display();
    }
Ejemplo n.º 9
0
 function display($tpl = null)
 {
     $mainframe =& JFactory::getApplication();
     $params =& JComponentHelper::getParams('com_k2');
     $model =& $this->getModel('itemlist');
     $limitstart = JRequest::getInt('limitstart');
     $view = JRequest::getWord('view');
     $task = JRequest::getWord('task');
     //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);
             //Access check
             $user =& JFactory::getUser();
             if ($category->access > $user->get('aid', 0)) {
                 JError::raiseError(403, JText::_("ALERTNOTAUTH"));
             }
             if (!$category->published || $category->trash) {
                 JError::raiseError(404, JText::_("Category not found"));
             }
             //Merge params
             $cparams = new JParameter($category->params);
             if ($cparams->get('inheritFrom')) {
                 $masterCategory =& JTable::getInstance('K2Category', 'Table');
                 $masterCategory->load($cparams->get('inheritFrom'));
                 $cparams = new JParameter($masterCategory->params);
             }
             $params->merge($cparams);
             //Category link
             $category->link = urldecode(JRoute::_(K2HelperRoute::getCategoryRoute($category->id . ':' . urlencode($category->alias))));
             //Category image
             if (!empty($category->image)) {
                 $category->image = JURI::root() . 'media/k2/categories/' . $category->image;
             } else {
                 if ($params->get('catImageDefault')) {
                     $category->image = JURI::root() . 'components/com_k2/images/placeholder/category.png';
                 }
             }
             //Category plugins
             $dispatcher =& JDispatcher::getInstance();
             JPluginHelper::importPlugin('content');
             $category->text = $category->description;
             $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 childs
             $ordering = $params->get('subCatOrdering');
             $childs = $model->getCategoryFirstChilds($id, $ordering);
             if (count($childs)) {
                 foreach ($childs as $child) {
                     if ($params->get('subCatTitleItemCounter')) {
                         $child->numOfItems = $model->countCategoryItems($child->id);
                     }
                     if (!empty($child->image)) {
                         $child->image = JURI::root() . 'media/k2/categories/' . $child->image;
                     } else {
                         if ($params->get('catImageDefault')) {
                             $child->image = JURI::root() . 'components/com_k2/images/placeholder/category.png';
                         }
                     }
                     $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);
             break;
         case 'user':
             //Get user
             $id = JRequest::getInt('id');
             $user =& JFactory::getUser($id);
             //Check user status
             if ($user->block) {
                 JError::raiseError(404, JText::_('User not found'));
             }
             //Get K2 user profile
             $user->profile = $model->getUserProfile();
             //User image
             $user->avatar = K2HelperUtilities::getAvatar($user->id, $user->email, $params->get('userImageWidth'));
             //User K2 plugins
             $user->event->K2UserDisplay = '';
             if (is_object($user->profile) && $user->profile->id > 0) {
                 $dispatcher =& JDispatcher::getInstance();
                 JPluginHelper::importPlugin('k2');
                 $results = $dispatcher->trigger('onK2UserDisplay', array(&$user->profile, &$params, $limitstart));
                 $user->event->K2UserDisplay = trim(implode("\n", $results));
             }
             $this->assignRef('user', $user);
             $db =& JFactory::getDBO();
             $nullDate = $db->getNullDate();
             $date =& JFactory::getDate();
             $now = $date->toMySQL();
             $this->assignRef('nullDate', $nullDate);
             $this->assignRef('now', $now);
             //Set layout
             $this->setLayout('user');
             //Set limit
             $limit = $params->get('userItemCount');
             //Set title
             $title = $user->name;
             $user->name = htmlspecialchars($user->name, ENT_QUOTES);
             break;
         case 'tag':
             //Set layout
             $this->setLayout('generic');
             //Set limit
             $limit = $params->get('genericItemCount');
             //set title
             $title = JText::_('Displaying items by tag:') . ' ' . JRequest::getVar('tag');
             break;
         case 'search':
             //Set layout
             $this->setLayout('generic');
             //Set limit
             $limit = $params->get('genericItemCount');
             //Set title
             $title = JText::_('Search results for:') . ' ' . JRequest::getVar('searchword');
             break;
         case 'date':
             //Set layout
             $this->setLayout('generic');
             //Set limit
             $limit = $params->get('genericItemCount');
             //Set title
             if (JRequest::getInt('day')) {
                 $date = strtotime(JRequest::getInt('year') . '-' . JRequest::getInt('month') . '-' . JRequest::getInt('day'));
                 $title = JText::_('Items filtered by date:') . ' ' . JHTML::_('date', $date, '%A, %d %B %Y');
             } else {
                 $date = strtotime(JRequest::getInt('year') . '-' . JRequest::getInt('month'));
                 $title = JText::_('Items filtered by date:') . ' ' . JHTML::_('date', $date, '%B %Y');
             }
             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');
             break;
     }
     //Set limit for model
     if (!$limit) {
         $limit = 10;
     }
     JRequest::setVar('limit', $limit);
     //Get ordering
     if ($task == 'tag') {
         $ordering = $params->get('tagOrdering');
     } else {
         $ordering = $params->get('catOrdering');
     }
     //Get items
     $items = $model->getData($ordering);
     //Pagination
     jimport('joomla.html.pagination');
     $total = $model->getTotal();
     $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';
             }
         }
         if ($user->guest) {
             $hits = $items[$i]->hits;
             $items[$i]->hits = 0;
             $items[$i] = $cache->call(array('K2ModelItem', '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();
     $menus =& JSite::getMenu();
     $menu = $menus->getActive();
     if (is_object($menu)) {
         $menu_params = new JParameter($menu->params);
         if (!$menu_params->get('page_title')) {
             $params->set('page_title', $title);
         }
     } else {
         $params->set('page_title', $title);
     }
     $document->setTitle($params->get('page_title'));
     //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 =& JSite::getMenu();
     $default = $menu->getDefault();
     $active = $menu->getActive();
     if ($task == 'tag') {
         $link = K2HelperRoute::getTagRoute(JRequest::getVar('tag'));
     } else {
         $link = '';
     }
     if (!is_null($active) && $active->id == $default->id && $config->getValue('config.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 ($params->get('feedLink', 1)) {
         $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);
     //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'));
     }
     parent::display($tpl);
 }
Ejemplo n.º 10
0
 function display($tpl = null)
 {
     $mainframe = JFactory::getApplication();
     $db = JFactory::getDBO();
     $view = JRequest::getCmd('view');
     jimport('joomla.filesystem.file');
     jimport('joomla.html.pane');
     JHTML::_('behavior.keepalive');
     JHTML::_('behavior.modal');
     JRequest::setVar('hidemainmenu', 1);
     $document = JFactory::getDocument();
     $document->addScript(JURI::root(true) . '/media/k2/assets/js/nicEdit.js?v=2.6.8');
     //var K2SitePath = '".JURI::root(true)."/';
     $js = "\n\t\t\t\t\tvar K2BasePath = '" . JURI::base(true) . "/';\n\t\t\t\t\tvar K2Language = [\n\t\t\t\t\t\t'" . JText::_('K2_REMOVE', true) . "',\n\t\t\t\t\t\t'" . JText::_('K2_LINK_TITLE_OPTIONAL', true) . "',\n\t\t\t\t\t\t'" . JText::_('K2_LINK_TITLE_ATTRIBUTE_OPTIONAL', true) . "',\n\t\t\t\t\t\t'" . JText::_('K2_ARE_YOU_SURE', true) . "',\n\t\t\t\t\t\t'" . JText::_('K2_YOU_ARE_NOT_ALLOWED_TO_POST_TO_THIS_CATEGORY', true) . "',\n\t\t\t\t\t\t'" . JText::_('K2_OR_SELECT_A_FILE_ON_THE_SERVER', true) . "'\n\t\t\t\t\t]\n\t\t\t\t";
     $document->addScriptDeclaration($js);
     K2Model::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . DS . 'models');
     $model = K2Model::getInstance('Item', 'K2Model', array('table_path' => JPATH_COMPONENT_ADMINISTRATOR . DS . 'tables'));
     $item = $model->getData();
     JFilterOutput::objectHTMLSafe($item, ENT_QUOTES, array('video', 'params', 'plugins'));
     $user = JFactory::getUser();
     // Permissions check on frontend
     if ($mainframe->isSite()) {
         JLoader::register('K2HelperPermissions', JPATH_COMPONENT . DS . 'helpers' . DS . 'permissions.php');
         $task = JRequest::getCmd('task');
         if ($task == 'edit' && !K2HelperPermissions::canEditItem($item->created_by, $item->catid)) {
             JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
         }
         if ($task == 'add' && !K2HelperPermissions::canAddItem()) {
             JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
         }
         // Get permissions
         $K2Permissions = K2Permissions::getInstance();
         $this->assignRef('permissions', $K2Permissions->permissions);
         // Build permissions message
         $permissionsLabels = array();
         if ($this->permissions->get('add')) {
             $permissionsLabels[] = JText::_('K2_ADD_ITEMS');
         }
         if ($this->permissions->get('editOwn')) {
             $permissionsLabels[] = JText::_('K2_EDIT_OWN_ITEMS');
         }
         if ($this->permissions->get('editAll')) {
             $permissionsLabels[] = JText::_('K2_EDIT_ANY_ITEM');
         }
         if ($this->permissions->get('publish')) {
             $permissionsLabels[] = JText::_('K2_PUBLISH_ITEMS');
         }
         if ($this->permissions->get('editPublished')) {
             $permissionsLabels[] = JText::_('K2_ALLOW_EDITING_OF_ALREADY_PUBLISHED_ITEMS');
         }
         $permissionsMessage = JText::_('K2_YOU_ARE_ALLOWED_TO') . ' ' . implode(', ', $permissionsLabels);
         $this->assignRef('permissionsMessage', $permissionsMessage);
     }
     if ($item->isCheckedOut($user->get('id'), $item->checked_out)) {
         $message = JText::_('K2_THE_ITEM') . ': ' . $item->title . ' ' . JText::_('K2_IS_CURRENTLY_BEING_EDITED_BY_ANOTHER_ADMINISTRATOR');
         $url = $mainframe->isSite() ? 'index.php?option=com_k2&view=item&id=' . $item->id . '&tmpl=component' : 'index.php?option=com_k2';
         $mainframe->enqueueMessage($message);
         $mainframe->redirect($url);
     }
     if ($item->id) {
         $item->checkout($user->get('id'));
     } else {
         $item->published = 1;
         $item->publish_down = $db->getNullDate();
         $item->modified = $db->getNullDate();
         $date = JFactory::getDate();
         $now = K2_JVERSION == '15' ? $date->toMySQL() : $date->toSql();
         $item->created = $now;
         $item->publish_up = $item->created;
     }
     $lists = array();
     if (version_compare(JVERSION, '1.6.0', 'ge')) {
         $dateFormat = 'Y-m-d H:i:s';
     } else {
         $dateFormat = '%Y-%m-%d %H:%M:%S';
     }
     $created = $item->created;
     $publishUp = $item->publish_up;
     $publishDown = $item->publish_down;
     $created = JHTML::_('date', $item->created, $dateFormat);
     $publishUp = JHTML::_('date', $item->publish_up, $dateFormat);
     if ((int) $item->publish_down) {
         $publishDown = JHTML::_('date', $item->publish_down, $dateFormat);
     } else {
         $publishDown = '';
     }
     // Set up calendars
     $lists['createdCalendar'] = JHTML::_('calendar', $created, 'created', 'created');
     $lists['publish_up'] = JHTML::_('calendar', $publishUp, 'publish_up', 'publish_up');
     $lists['publish_down'] = JHTML::_('calendar', $publishDown, 'publish_down', 'publish_down');
     if ($item->id) {
         $lists['created'] = JHTML::_('date', $item->created, JText::_('DATE_FORMAT_LC2'));
     } else {
         $lists['created'] = JText::_('K2_NEW_DOCUMENT');
     }
     if ($item->modified == $db->getNullDate() || !$item->id) {
         $lists['modified'] = JText::_('K2_NEVER');
     } else {
         $lists['modified'] = JHTML::_('date', $item->modified, JText::_('DATE_FORMAT_LC2'));
     }
     $params = JComponentHelper::getParams('com_k2');
     $wysiwyg = JFactory::getEditor();
     $onSave = '';
     if ($params->get("mergeEditors")) {
         if (JString::strlen($item->fulltext) > 1) {
             $textValue = $item->introtext . "<hr id=\"system-readmore\" />" . $item->fulltext;
         } else {
             $textValue = $item->introtext;
         }
         $text = $wysiwyg->display('text', $textValue, '100%', '400px', '', '');
         $this->assignRef('text', $text);
         if (K2_JVERSION == '30') {
             $onSave = $wysiwyg->save('text');
         }
     } else {
         $introtext = $wysiwyg->display('introtext', $item->introtext, '100%', '400px', '', '', array('readmore'));
         $this->assignRef('introtext', $introtext);
         $fulltext = $wysiwyg->display('fulltext', $item->fulltext, '100%', '400px', '', '', array('readmore'));
         $this->assignRef('fulltext', $fulltext);
         if (K2_JVERSION == '30') {
             $onSave = $wysiwyg->save('introtext');
             $onSave .= $wysiwyg->save('fulltext');
         }
     }
     $document->addScriptDeclaration("function onK2EditorSave(){ " . $onSave . " }");
     $lists['published'] = JHTML::_('select.booleanlist', 'published', 'class="inputbox"', $item->published);
     $lists['featured'] = JHTML::_('select.booleanlist', 'featured', 'class="inputbox"', $item->featured);
     $lists['access'] = version_compare(JVERSION, '3.0', 'ge') ? JHTML::_('access.level', 'access', $item->access) : JHTML::_('list.accesslevel', $item);
     $query = "SELECT ordering AS value, title AS text FROM #__k2_items WHERE catid={$item->catid}";
     $lists['ordering'] = version_compare(JVERSION, '3.0', 'ge') ? NUll : JHTML::_('list.specificordering', $item, $item->id, $query);
     if (!$item->id) {
         $item->catid = $mainframe->getUserStateFromRequest('com_k2itemsfilter_category', 'catid', 0, 'int');
     }
     require_once JPATH_ADMINISTRATOR . '/components/com_k2/models/categories.php';
     $categoriesModel = K2Model::getInstance('Categories', 'K2Model');
     $categories = $categoriesModel->categoriesTree();
     $lists['catid'] = JHTML::_('select.genericlist', $categories, 'catid', 'class="inputbox"', 'value', 'text', $item->catid);
     if (version_compare(JVERSION, '1.6.0', 'ge')) {
         $languages = JHTML::_('contentlanguage.existing', true, true);
         $lists['language'] = JHTML::_('select.genericlist', $languages, 'language', '', 'value', 'text', $item->language);
     }
     $lists['checkSIG'] = $model->checkSIG();
     $lists['checkAllVideos'] = $model->checkAllVideos();
     $remoteVideo = false;
     $providerVideo = false;
     $embedVideo = false;
     if (stristr($item->video, 'remote}') !== false) {
         $remoteVideo = true;
         $options['startOffset'] = 1;
     }
     $providers = $model->getVideoProviders();
     if (count($providers)) {
         foreach ($providers as $provider) {
             $providersOptions[] = JHTML::_('select.option', $provider, ucfirst($provider));
             if (stristr($item->video, "{{$provider}}") !== false) {
                 $providerVideo = true;
                 $options['startOffset'] = 2;
             }
         }
     }
     if (JString::substr($item->video, 0, 1) !== '{') {
         $embedVideo = true;
         $options['startOffset'] = 3;
     }
     $lists['uploadedVideo'] = !$remoteVideo && !$providerVideo && !$embedVideo ? true : false;
     if ($lists['uploadedVideo'] || $item->video == '') {
         $options['startOffset'] = 0;
     }
     $document->addScriptDeclaration("var K2ActiveVideoTab = " . $options['startOffset']);
     $lists['remoteVideo'] = $remoteVideo ? preg_replace('%\\{[a-z0-9-_]*\\}(.*)\\{/[a-z0-9-_]*\\}%i', '\\1', $item->video) : '';
     $lists['remoteVideoType'] = $remoteVideo ? preg_replace('%\\{([a-z0-9-_]*)\\}.*\\{/[a-z0-9-_]*\\}%i', '\\1', $item->video) : '';
     $lists['providerVideo'] = $providerVideo ? preg_replace('%\\{[a-z0-9-_]*\\}(.*)\\{/[a-z0-9-_]*\\}%i', '\\1', $item->video) : '';
     $lists['providerVideoType'] = $providerVideo ? preg_replace('%\\{([a-z0-9-_]*)\\}.*\\{/[a-z0-9-_]*\\}%i', '\\1', $item->video) : '';
     $lists['embedVideo'] = $embedVideo ? $item->video : '';
     if (isset($providersOptions)) {
         $lists['providers'] = JHTML::_('select.genericlist', $providersOptions, 'videoProvider', '', 'value', 'text', $lists['providerVideoType']);
     }
     JPluginHelper::importPlugin('content', 'jw_sigpro');
     JPluginHelper::importPlugin('content', 'jw_allvideos');
     $dispatcher = JDispatcher::getInstance();
     // Detect gallery type
     if (JString::strpos($item->gallery, 'http://')) {
         $item->galleryType = 'flickr';
         $item->galleryValue = JString::substr($item->gallery, 9);
         $item->galleryValue = JString::substr($item->galleryValue, 0, -10);
     } else {
         $item->galleryType = 'server';
         $item->galleryValue = '';
     }
     $params->set('galleries_rootfolder', 'media/k2/galleries');
     $item->text = $item->gallery;
     if (K2_JVERSION == '15') {
         $dispatcher->trigger('onPrepareContent', array(&$item, &$params, null));
     } else {
         $dispatcher->trigger('onContentPrepare', array('com_k2.' . $view, &$item, &$params, null));
     }
     $item->gallery = $item->text;
     if (!$embedVideo) {
         $params->set('vfolder', 'media/k2/videos');
         $params->set('afolder', 'media/k2/audio');
         if (JString::strpos($item->video, 'remote}')) {
             preg_match("#}(.*?){/#s", $item->video, $matches);
             if (JString::substr($matches[1], 0, 7) != 'http://') {
                 $item->video = str_replace($matches[1], JURI::root() . $matches[1], $item->video);
             }
         }
         $item->text = $item->video;
         if (K2_JVERSION == '15') {
             $dispatcher->trigger('onPrepareContent', array(&$item, &$params, null));
         } else {
             $dispatcher->trigger('onContentPrepare', array('com_k2.' . $view, &$item, &$params, null));
         }
         $item->video = $item->text;
     } else {
         // no nothing
     }
     if (isset($item->created_by)) {
         $author = JUser::getInstance($item->created_by);
         $item->author = $author->name;
     } else {
         $item->author = $user->name;
     }
     if (isset($item->modified_by)) {
         $moderator = JUser::getInstance($item->modified_by);
         $item->moderator = $moderator->name;
     }
     if ($item->id) {
         $active = $item->created_by;
     } else {
         $active = $user->id;
     }
     $lists['authors'] = JHTML::_('list.users', 'created_by', $active, false);
     $categories_option[] = JHTML::_('select.option', 0, JText::_('K2_SELECT_CATEGORY'));
     $categories = $categoriesModel->categoriesTree(NUll, true, false);
     if ($mainframe->isSite()) {
         JLoader::register('K2HelperPermissions', JPATH_SITE . DS . 'components' . DS . 'com_k2' . DS . 'helpers' . DS . 'permissions.php');
         if (($task == 'add' || $task == 'edit') && !K2HelperPermissions::canAddToAll()) {
             for ($i = 0; $i < sizeof($categories); $i++) {
                 if (!K2HelperPermissions::canAddItem($categories[$i]->value) && $task == 'add') {
                     $categories[$i]->disable = true;
                 }
                 if (!K2HelperPermissions::canEditItem($item->created_by, $categories[$i]->value) && $task == 'edit') {
                     $categories[$i]->disable = true;
                 }
             }
         }
     }
     $categories_options = @array_merge($categories_option, $categories);
     $lists['categories'] = JHTML::_('select.genericlist', $categories_options, 'catid', '', 'value', 'text', $item->catid);
     JTable::addIncludePath(JPATH_COMPONENT . DS . 'tables');
     $category = JTable::getInstance('K2Category', 'Table');
     $category->load($item->catid);
     $extraFieldModel = K2Model::getInstance('ExtraField', 'K2Model');
     if ($category->id) {
         $extraFields = $extraFieldModel->getExtraFieldsByGroup($category->extraFieldsGroup);
     } else {
         $extraFields = NULL;
     }
     for ($i = 0; $i < sizeof($extraFields); $i++) {
         $extraFields[$i]->element = $extraFieldModel->renderExtraField($extraFields[$i], $item->id);
     }
     if ($item->id) {
         $item->attachments = $model->getAttachments($item->id);
         $rating = $model->getRating();
         if (is_null($rating)) {
             $item->ratingSum = 0;
             $item->ratingCount = 0;
         } else {
             $item->ratingSum = (int) $rating->rating_sum;
             $item->ratingCount = (int) $rating->rating_count;
         }
     } else {
         $item->attachments = NULL;
         $item->ratingSum = 0;
         $item->ratingCount = 0;
     }
     if ($user->gid < 24 && $params->get('lockTags')) {
         $params->set('taggingSystem', 0);
     }
     $tags = $model->getAvailableTags($item->id);
     $lists['tags'] = JHTML::_('select.genericlist', $tags, 'tags', 'multiple="multiple" size="10" ', 'id', 'name');
     if (isset($item->id)) {
         $item->tags = $model->getCurrentTags($item->id);
         $lists['selectedTags'] = JHTML::_('select.genericlist', $item->tags, 'selectedTags[]', 'multiple="multiple" size="10" ', 'id', 'name');
     } else {
         $lists['selectedTags'] = '<select size="10" multiple="multiple" id="selectedTags" name="selectedTags[]"></select>';
     }
     $lists['metadata'] = class_exists('JParameter') ? new JParameter($item->metadata) : new JRegistry($item->metadata);
     $date = JFactory::getDate($item->modified);
     $timestamp = '?t=' . $date->toUnix();
     if (JFile::exists(JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . md5("Image" . $item->id) . '_L.jpg')) {
         $item->image = JURI::root() . 'media/k2/items/cache/' . md5("Image" . $item->id) . '_L.jpg' . $timestamp;
     }
     if (JFile::exists(JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . md5("Image" . $item->id) . '_S.jpg')) {
         $item->thumb = JURI::root() . 'media/k2/items/cache/' . md5("Image" . $item->id) . '_S.jpg' . $timestamp;
     }
     JPluginHelper::importPlugin('k2');
     $dispatcher = JDispatcher::getInstance();
     $K2PluginsItemContent = $dispatcher->trigger('onRenderAdminForm', array(&$item, 'item', 'content'));
     $this->assignRef('K2PluginsItemContent', $K2PluginsItemContent);
     $K2PluginsItemImage = $dispatcher->trigger('onRenderAdminForm', array(&$item, 'item', 'image'));
     $this->assignRef('K2PluginsItemImage', $K2PluginsItemImage);
     $K2PluginsItemGallery = $dispatcher->trigger('onRenderAdminForm', array(&$item, 'item', 'gallery'));
     $this->assignRef('K2PluginsItemGallery', $K2PluginsItemGallery);
     $K2PluginsItemVideo = $dispatcher->trigger('onRenderAdminForm', array(&$item, 'item', 'video'));
     $this->assignRef('K2PluginsItemVideo', $K2PluginsItemVideo);
     $K2PluginsItemExtraFields = $dispatcher->trigger('onRenderAdminForm', array(&$item, 'item', 'extra-fields'));
     $this->assignRef('K2PluginsItemExtraFields', $K2PluginsItemExtraFields);
     $K2PluginsItemAttachments = $dispatcher->trigger('onRenderAdminForm', array(&$item, 'item', 'attachments'));
     $this->assignRef('K2PluginsItemAttachments', $K2PluginsItemAttachments);
     $K2PluginsItemOther = $dispatcher->trigger('onRenderAdminForm', array(&$item, 'item', 'other'));
     $this->assignRef('K2PluginsItemOther', $K2PluginsItemOther);
     if (version_compare(JVERSION, '1.6.0', 'ge')) {
         jimport('joomla.form.form');
         $form = JForm::getInstance('itemForm', JPATH_COMPONENT_ADMINISTRATOR . DS . 'models' . DS . 'item.xml');
         $values = array('params' => json_decode($item->params));
         $form->bind($values);
     } else {
         $form = new JParameter('', JPATH_COMPONENT_ADMINISTRATOR . DS . 'models' . DS . 'item.xml');
         $form->loadINI($item->params);
     }
     $this->assignRef('form', $form);
     $nullDate = $db->getNullDate();
     $this->assignRef('nullDate', $nullDate);
     $this->assignRef('extraFields', $extraFields);
     $this->assignRef('options', $options);
     $this->assignRef('row', $item);
     $this->assignRef('lists', $lists);
     $this->assignRef('params', $params);
     $this->assignRef('user', $user);
     JRequest::getInt('cid') ? $title = JText::_('K2_EDIT_ITEM') : ($title = JText::_('K2_ADD_ITEM'));
     $this->assignRef('title', $title);
     $this->assignRef('mainframe', $mainframe);
     if ($mainframe->isAdmin()) {
         $this->params->set('showImageTab', true);
         $this->params->set('showImageGalleryTab', true);
         $this->params->set('showVideoTab', true);
         $this->params->set('showExtraFieldsTab', true);
         $this->params->set('showAttachmentsTab', true);
         $this->params->set('showK2Plugins', true);
         JToolBarHelper::title($title, 'k2.png');
         JToolBarHelper::save();
         $saveNewIcon = version_compare(JVERSION, '2.5.0', 'ge') ? 'save-new.png' : 'save.png';
         JToolBarHelper::custom('saveAndNew', $saveNewIcon, 'save_f2.png', 'K2_SAVE_AND_NEW', false);
         JToolBarHelper::apply();
         JToolBarHelper::cancel();
     }
     // ACE ACL integration
     $definedConstants = get_defined_constants();
     if (!empty($definedConstants['ACEACL']) && AceaclApi::authorize('permissions', 'com_aceacl')) {
         $aceAclFlag = true;
     } else {
         $aceAclFlag = false;
     }
     $this->assignRef('aceAclFlag', $aceAclFlag);
     // SIG PRO v3 integration
     if (JPluginHelper::isEnabled('k2', 'jw_sigpro')) {
         $sigPro = true;
         $sigProFolder = $this->row->id ? $this->row->id : uniqid();
         $this->assignRef('sigProFolder', $sigProFolder);
     } else {
         $sigPro = false;
     }
     $this->assignRef('sigPro', $sigPro);
     parent::display($tpl);
 }
Ejemplo n.º 11
0
 function checkPermissions()
 {
     $view = JRequest::getCmd('view');
     if ($view != 'item') {
         return;
     }
     $task = JRequest::getCmd('task');
     switch ($task) {
         case 'add':
             if (!K2HelperPermissions::canAddItem()) {
                 JError::raiseError(403, JText::_("ALERTNOTAUTH"));
             }
             break;
         case 'edit':
         case 'deleteAttachment':
         case 'checkin':
             $cid = JRequest::getInt('cid');
             if (!$cid) {
                 JError::raiseError(403, JText::_("ALERTNOTAUTH"));
             }
             JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . DS . 'tables');
             $item =& JTable::getInstance('K2Item', 'Table');
             $item->load($cid);
             if (!K2HelperPermissions::canEditItem($item->created_by, $item->catid)) {
                 JError::raiseError(403, JText::_("ALERTNOTAUTH"));
             }
             break;
         case 'save':
             $cid = JRequest::getInt('id');
             if ($cid) {
                 JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . DS . 'tables');
                 $item =& JTable::getInstance('K2Item', 'Table');
                 $item->load($cid);
                 if (!K2HelperPermissions::canEditItem($item->created_by, $item->catid)) {
                     JError::raiseError(403, JText::_("ALERTNOTAUTH"));
                 }
             } else {
                 if (!K2HelperPermissions::canAddItem()) {
                     JError::raiseError(403, JText::_("ALERTNOTAUTH"));
                 }
             }
             break;
         case 'tag':
             if (!K2HelperPermissions::canAddTag()) {
                 JError::raiseError(403, JText::_("ALERTNOTAUTH"));
             }
             break;
         case 'extraFields':
             if (!K2HelperPermissions::canRenderExtraFields()) {
                 JError::raiseError(403, JText::_("ALERTNOTAUTH"));
             }
             break;
     }
 }
Ejemplo n.º 12
0
 function users()
 {
     $itemID = JRequest::getInt('itemID');
     JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . DS . 'tables');
     $item =& JTable::getInstance('K2Item', 'Table');
     $item->load($itemID);
     if (!K2HelperPermissions::canAddItem() && !K2HelperPermissions::canEditItem($item->created_by, $item->catid)) {
         JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
     }
     $K2Permissions =& K2Permissions::getInstance();
     if (!$K2Permissions->permissions->get('editAll')) {
         JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
     }
     JRequest::setVar('tmpl', 'component');
     $mainframe =& JFactory::getApplication();
     $params =& JComponentHelper::getParams('com_k2');
     $language =& JFactory::getLanguage();
     $language->load('com_k2', JPATH_ADMINISTRATOR);
     $document =& JFactory::getDocument();
     if (version_compare(JVERSION, '1.6.0', 'ge')) {
         JHtml::_('behavior.framework');
     } else {
         JHTML::_('behavior.mootools');
     }
     // CSS
     $document->addStyleSheet(JURI::root(true) . '/media/k2/assets/css/k2.css?v=2.5.7');
     // JS
     $jQueryHandling = $params->get('jQueryHandling', '1.7remote');
     if ($jQueryHandling && strpos($jQueryHandling, 'remote') == true) {
         $document->addScript('http://ajax.googleapis.com/ajax/libs/jquery/' . str_replace('remote', '', $jQueryHandling) . '/jquery.min.js');
         $document->addScript('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js');
     } elseif ($jQueryHandling && strpos($jQueryHandling, 'remote') == false) {
         $document->addScript(JURI::root(true) . '/media/k2/assets/js/jquery-' . $jQueryHandling . '.min.js');
         $document->addScript(JURI::root(true) . '/media/k2/assets/js/jquery-ui-1.8.16.custom.min.js');
     }
     $document->addScript(JURI::root(true) . '/media/k2/assets/js/k2.js?v=2.5.7');
     $this->addViewPath(JPATH_COMPONENT_ADMINISTRATOR . DS . 'views');
     $this->addModelPath(JPATH_COMPONENT_ADMINISTRATOR . DS . 'models');
     $view =& $this->getView('users', 'html');
     $view->addTemplatePath(JPATH_COMPONENT_ADMINISTRATOR . DS . 'views' . DS . 'users' . DS . 'tmpl');
     $view->setLayout('element');
     $view->display();
 }
Ejemplo n.º 13
0
    function display($tpl = null)
    {
        $mainframe = JFactory::getApplication();
        $user = JFactory::getUser();
        $document = JFactory::getDocument();
        $params = K2HelperUtilities::getParams('com_k2');
        $limitstart = JRequest::getInt('limitstart', 0);
        $view = JRequest::getWord('view');
        $task = JRequest::getWord('task');
        $db = JFactory::getDBO();
        $jnow = JFactory::getDate();
        $now = K2_JVERSION == '15' ? $jnow->toMySQL() : $jnow->toSql();
        $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();
        // Does the item exists?
        if (!is_object($item) || !$item->id) {
            JError::raiseError(404, JText::_('K2_ITEM_NOT_FOUND'));
        }
        // Prepare item
        $item = $model->prepareItem($item, $view, $task);
        // Plugins
        $item = $model->execPlugins($item, $view, $task);
        // User K2 plugins
        $item->event->K2UserDisplay = '';
        if (isset($item->author) && is_object($item->author->profile) && isset($item->author->profile->id)) {
            $dispatcher = JDispatcher::getInstance();
            JPluginHelper::importPlugin('k2');
            $results = $dispatcher->trigger('onK2UserDisplay', array(&$item->author->profile, &$params, $limitstart));
            $item->event->K2UserDisplay = trim(implode("\n", $results));
            $item->author->profile->url = htmlspecialchars($item->author->profile->url, ENT_QUOTES, 'UTF-8');
        }
        // Access check
        if ($this->getLayout() == 'form') {
            JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
        }
        if (K2_JVERSION != '15') {
            if (!in_array($item->access, $user->getAuthorisedViewLevels()) || !in_array($item->category->access, $user->getAuthorisedViewLevels())) {
                if ($user->guest) {
                    $uri = JFactory::getURI();
                    $url = 'index.php?option=com_users&view=login&return=' . base64_encode($uri->toString());
                    $mainframe->enqueueMessage(JText::_('K2_YOU_NEED_TO_LOGIN_FIRST'), 'notice');
                    $mainframe->redirect(JRoute::_($url, false));
                } else {
                    JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
                    return;
                }
            }
        } else {
            if ($item->access > $user->get('aid', 0) || $item->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->enqueueMessage(JText::_('K2_YOU_NEED_TO_LOGIN_FIRST'), 'notice');
                    $mainframe->redirect(JRoute::_($url, false));
                } else {
                    JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
                    return;
                }
            }
        }
        // Published check
        if (!$item->published || $item->trash) {
            JError::raiseError(404, JText::_('K2_ITEM_NOT_FOUND'));
        }
        if ($item->publish_up != $nullDate && $item->publish_up > $now) {
            JError::raiseError(404, JText::_('K2_ITEM_NOT_FOUND'));
        }
        if ($item->publish_down != $nullDate && $item->publish_down < $now) {
            JError::raiseError(404, JText::_('K2_ITEM_NOT_FOUND'));
        }
        if (!$item->category->published || $item->category->trash) {
            JError::raiseError(404, JText::_('K2_ITEM_NOT_FOUND'));
        }
        // Increase hits counter
        $model->hit($item->id);
        // Set default image
        K2HelperUtilities::setDefaultImage($item, $view);
        // Pass the old parameter to the view in order to avoid layout changes
        if ($params->get('antispam') == 'recaptcha' || $params->get('antispam') == 'both') {
            $params->set('recaptcha', true);
            $item->params->set('recaptcha', true);
        } else {
            $params->set('recaptcha', false);
            $item->params->set('recaptcha', false);
        }
        // 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 ($params->get('recaptcha') && ($user->guest || $params->get('recaptchaForRegistered', 1))) {
                        $document->addScript('https://www.google.com/recaptcha/api/js/recaptcha_ajax.js');
                        $js = '
						function showRecaptcha(){
							Recaptcha.create("' . $item->params->get('recaptcha_public_key') . '", "recaptcha", {
								theme: "' . $item->params->get('recaptcha_theme', 'clean') . '"
							});
						}
						$K2(window).load(function() {
							showRecaptcha();
						});
						';
                        $document->addScriptDeclaration($js);
                    }
                }
                // Check for inline comment moderation
                if (!$user->guest && $user->id == $item->created_by && $params->get('inlineCommentsModeration')) {
                    $inlineCommentsModeration = true;
                    $commentsPublished = false;
                } else {
                    $inlineCommentsModeration = false;
                    $commentsPublished = true;
                }
                $this->assignRef('inlineCommentsModeration', $inlineCommentsModeration);
                // Flag spammer link
                $reportSpammerFlag = false;
                if (K2_JVERSION != '15') {
                    if ($user->authorise('core.admin', 'com_k2')) {
                        $reportSpammerFlag = true;
                        $document = JFactory::getDocument();
                        $document->addScriptDeclaration('var K2Language = ["' . JText::_('K2_REPORT_USER_WARNING', true) . '"];');
                    }
                } else {
                    if ($user->gid > 24) {
                        $reportSpammerFlag = true;
                    }
                }
                $limit = $params->get('commentsLimit');
                $comments = $model->getItemComments($item->id, $limitstart, $limit, $commentsPublished);
                for ($i = 0; $i < sizeof($comments); $i++) {
                    $comments[$i]->commentText = nl2br($comments[$i]->commentText);
                    // Convert URLs to links properly
                    $comments[$i]->commentText = preg_replace("/([^\\w\\/])(www\\.[a-z0-9\\-]+\\.[a-z0-9\\-]+)/i", "\$1http://\$2", $comments[$i]->commentText);
                    $comments[$i]->commentText = preg_replace("/([\\w]+:\\/\\/[\\w-?&;#~=\\.\\/\\@]+[\\w\\/])/i", "<a target=\"_blank\" rel=\"nofollow\" href=\"\$1\">\$1</A>", $comments[$i]->commentText);
                    $comments[$i]->commentText = preg_replace("/([\\w-?&;#~=\\.\\/]+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?))/i", "<a href=\"mailto:\$1\">\$1</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;
                    }
                    if ($reportSpammerFlag && $comments[$i]->userID > 0) {
                        $comments[$i]->reportUserLink = JRoute::_('index.php?option=com_k2&view=comments&task=reportSpammer&id=' . $comments[$i]->userID . '&format=raw');
                    } else {
                        $comments[$i]->reportUserLink = false;
                    }
                }
                $item->comments = $comments;
                if (!isset($item->numOfComments)) {
                    $item->numOfComments = 0;
                }
                jimport('joomla.html.pagination');
                $total = $item->numOfComments;
                $pagination = new JPagination($total, $limitstart, $limit);
            }
        }
        // Author's latest items
        if ($item->params->get('itemAuthorLatest') && $item->created_by_alias == '') {
            $model = $this->getModel('itemlist');
            $authorLatestItems = $model->getAuthorLatest($item->id, $item->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 ($item->params->get('itemRelated') && isset($item->tags) && count($item->tags)) {
            $model = $this->getModel('itemlist');
            $relatedItems = $model->getRelatedItems($item->id, $item->tags, $item->params);
            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 ($item->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;
                $date = JFactory::getDate($item->modified);
                $timestamp = '?t=' . $date->toUnix();
                if (JFile::exists(JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . md5("Image" . $nextItem->id) . '_XS.jpg')) {
                    $item->nextImageXSmall = JURI::base(true) . '/media/k2/items/cache/' . md5("Image" . $nextItem->id) . '_XS.jpg' . $timestamp;
                }
                if (JFile::exists(JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . md5("Image" . $nextItem->id) . '_S.jpg')) {
                    $item->nextImageSmall = JURI::base(true) . '/media/k2/items/cache/' . md5("Image" . $nextItem->id) . '_S.jpg' . $timestamp;
                }
                if (JFile::exists(JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . md5("Image" . $nextItem->id) . '_M.jpg')) {
                    $item->nextImageMedium = JURI::base(true) . '/media/k2/items/cache/' . md5("Image" . $nextItem->id) . '_M.jpg' . $timestamp;
                }
                if (JFile::exists(JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . md5("Image" . $nextItem->id) . '_L.jpg')) {
                    $item->nextImageLarge = JURI::base(true) . '/media/k2/items/cache/' . md5("Image" . $nextItem->id) . '_L.jpg' . $timestamp;
                }
                if (JFile::exists(JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . md5("Image" . $nextItem->id) . '_XL.jpg')) {
                    $item->nextImageXLarge = JURI::base(true) . '/media/k2/items/cache/' . md5("Image" . $nextItem->id) . '_XL.jpg' . $timestamp;
                }
                if (JFile::exists(JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . md5("Image" . $nextItem->id) . '_Generic.jpg')) {
                    $item->nextImageGeneric = JURI::base(true) . '/media/k2/items/cache/' . md5("Image" . $nextItem->id) . '_Generic.jpg' . $timestamp;
                }
            }
            $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;
                $date = JFactory::getDate($item->modified);
                $timestamp = '?t=' . $date->toUnix();
                if (JFile::exists(JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . md5("Image" . $previousItem->id) . '_XS.jpg')) {
                    $item->previousImageXSmall = JURI::base(true) . '/media/k2/items/cache/' . md5("Image" . $previousItem->id) . '_XS.jpg' . $timestamp;
                }
                if (JFile::exists(JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . md5("Image" . $previousItem->id) . '_S.jpg')) {
                    $item->previousImageSmall = JURI::base(true) . '/media/k2/items/cache/' . md5("Image" . $previousItem->id) . '_S.jpg' . $timestamp;
                }
                if (JFile::exists(JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . md5("Image" . $previousItem->id) . '_M.jpg')) {
                    $item->previousImageMedium = JURI::base(true) . '/media/k2/items/cache/' . md5("Image" . $previousItem->id) . '_M.jpg' . $timestamp;
                }
                if (JFile::exists(JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . md5("Image" . $previousItem->id) . '_L.jpg')) {
                    $item->previousImageLarge = JURI::base(true) . '/media/k2/items/cache/' . md5("Image" . $previousItem->id) . '_L.jpg' . $timestamp;
                }
                if (JFile::exists(JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . md5("Image" . $previousItem->id) . '_XL.jpg')) {
                    $item->previousImageXLarge = JURI::base(true) . '/media/k2/items/cache/' . md5("Image" . $previousItem->id) . '_XL.jpg' . $timestamp;
                }
                if (JFile::exists(JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . md5("Image" . $previousItem->id) . '_Generic.jpg')) {
                    $item->previousImageGeneric = JURI::base(true) . '/media/k2/items/cache/' . md5("Image" . $previousItem->id) . '_Generic.jpg' . $timestamp;
                }
            }
        }
        // Absolute URL
        $uri = JURI::getInstance();
        $item->absoluteURL = $uri->toString();
        // Email link
        if (K2_JVERSION != '15') {
            require_once JPATH_SITE . '/components/com_mailto/helpers/mailto.php';
            $template = $mainframe->getTemplate();
            $item->emailLink = JRoute::_('index.php?option=com_mailto&tmpl=component&template=' . $template . '&link=' . MailToHelper::addLink($item->absoluteURL));
        } else {
            require_once JPATH_SITE . DS . 'components' . DS . 'com_mailto' . DS . 'helpers' . DS . 'mailto.php';
            $item->emailLink = JRoute::_('index.php?option=com_mailto&tmpl=component&link=' . MailToHelper::addLink($item->absoluteURL));
        }
        // Twitter link (legacy code)
        if ($params->get('twitterUsername')) {
            $item->twitterURL = 'http://twitter.com/intent/tweet?text=' . urlencode($item->title) . '&amp;url=' . urlencode($item->absoluteURL) . '&amp;via=' . $params->get('twitterUsername');
        } else {
            $item->twitterURL = 'http://twitter.com/intent/tweet?text=' . urlencode($item->title) . '&amp;url=' . urlencode($item->absoluteURL);
        }
        // Social link
        $item->socialLink = urlencode($item->absoluteURL);
        // Set page title
        $menus = $mainframe->getMenu();
        $menu = $menus->getActive();
        if (is_object($menu) && isset($menu->query['view']) && $menu->query['view'] == 'item' && isset($menu->query['id']) && $menu->query['id'] == $item->id) {
            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', $item->cleanTitle);
            }
        } else {
            $params->set('page_title', $item->cleanTitle);
        }
        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'));
        // Set pathway
        $menus = $mainframe->getMenu();
        $menu = $menus->getActive();
        $pathway = $mainframe->getPathWay();
        if ($menu) {
            if (isset($menu->query['view']) && ($menu->query['view'] != 'item' || $menu->query['id'] != $item->id)) {
                if (!isset($menu->query['task']) || $menu->query['task'] != 'category' || $menu->query['id'] != $item->catid) {
                    $pathway->addItem($item->category->name, $item->category->link);
                }
                $pathway->addItem($item->cleanTitle, '');
            }
        }
        // Set metadata
        if ($item->metadesc) {
            $document->setDescription(K2_JVERSION == '15' ? htmlspecialchars($item->metadesc, ENT_QUOTES, 'UTF-8') : $item->metadesc);
        } else {
            $metaDescItem = preg_replace("#{(.*?)}(.*?){/(.*?)}#s", '', $item->introtext . ' ' . $item->fulltext);
            $metaDescItem = strip_tags($metaDescItem);
            $metaDescItem = K2HelperUtilities::characterLimit($metaDescItem, $params->get('metaDescLimit', 150));
            $document->setDescription(K2_JVERSION == '15' ? $metaDescItem : html_entity_decode($metaDescItem));
        }
        if ($item->metakey) {
            $document->setMetadata('keywords', $item->metakey);
        } else {
            if (isset($item->tags) && count($item->tags)) {
                $tmp = array();
                foreach ($item->tags as $tag) {
                    $tmp[] = $tag->name;
                }
                $document->setMetadata('keywords', implode(',', $tmp));
            }
        }
        // Menu metadata for Joomla! 2.5+ (overrides the current metadata if set)
        if (K2_JVERSION != '15') {
            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'));
        }
        if ($mainframe->getCfg('MetaTitle') == '1') {
            $document->setMetadata('title', $item->cleanTitle);
        }
        if ($mainframe->getCfg('MetaAuthor') == '1' && isset($item->author->name)) {
            $document->setMetadata('author', $item->author->name);
        }
        $mdata = class_exists('JParameter') ? new JParameter($item->metadata) : new JRegistry($item->metadata);
        $mdata = $mdata->toArray();
        foreach ($mdata as $k => $v) {
            if ($k == 'robots' || $k == 'author') {
                if ($v) {
                    $document->setMetadata($k, $v);
                }
            }
        }
        // Set Facebook meta data
        $document = JFactory::getDocument();
        $uri = JURI::getInstance();
        $document->setMetaData('og:url', $uri->toString());
        $document->setMetaData('og:title', K2_JVERSION == '15' ? htmlspecialchars($document->getTitle(), ENT_QUOTES, 'UTF-8') : $document->getTitle());
        $document->setMetaData('og:type', 'article');
        $facebookImage = 'image' . $params->get('facebookImage', 'Small');
        if ($item->{$facebookImage}) {
            $parts = parse_url($item->{$facebookImage});
            if (JFile::exists(JPATH_SITE . $parts['path'])) {
                $image = substr(JURI::root(), 0, -1) . str_replace(JURI::root(true), '', $item->{$facebookImage});
                $document->setMetaData('og:image', $image);
                $document->setMetaData('image', $image);
            }
        }
        $document->setMetaData('og:description', strip_tags($document->getDescription()));
        // 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);
    }
Ejemplo n.º 14
0
 /**
  * This method is copied from admin/com_k2/models/item.php 
  * Modifications have been made
  * Changed all $mainframe redirects
  * Removed the check for extra fields, we don't want to override them
  */
 function save($front = false)
 {
     $mainframe =& JFactory::getApplication();
     jimport('joomla.filesystem.file');
     jimport('joomla.filesystem.folder');
     jimport('joomla.filesystem.archive');
     require_once JPATH_ADMINISTRATOR . '/components/com_k2' . DS . 'lib' . DS . 'class.upload.php';
     $db =& JFactory::getDBO();
     $user =& JFactory::getUser();
     $row =& JTable::getInstance('K2Item', 'Table');
     $params =& JComponentHelper::getParams('com_k2');
     $nullDate = $db->getNullDate();
     if (!$row->bind(JRequest::get('post'))) {
         $this->setError($row->getError());
         return false;
     }
     if ($front && $row->id == NULL) {
         JLoader::register('K2HelperPermissions', JPATH_SITE . DS . 'components' . DS . 'com_k2' . DS . 'helpers' . DS . 'permissions.php');
         if (!K2HelperPermissions::canAddItem($row->catid)) {
             $this->setError(JText::_('K2_YOU_ARE_NOT_ALLOWED_TO_POST_TO_THIS_CATEGORY_SAVE_FAILED'));
             return false;
         }
     }
     $row->id ? $isNew = false : ($isNew = true);
     if ($params->get('mergeEditors')) {
         $text = JRequest::getVar('text', '', 'post', 'string', 2);
         if ($params->get('xssFiltering')) {
             $filter = new JFilterInput(array(), array(), 1, 1, 0);
             $text = $filter->clean($text);
         }
         $pattern = '#<hr\\s+id=("|\')system-readmore("|\')\\s*\\/*>#i';
         $tagPos = preg_match($pattern, $text);
         if ($tagPos == 0) {
             $row->introtext = $text;
             $row->fulltext = '';
         } else {
             list($row->introtext, $row->fulltext) = preg_split($pattern, $text, 2);
         }
     } else {
         $row->introtext = JRequest::getVar('introtext', '', 'post', 'string', 2);
         $row->fulltext = JRequest::getVar('fulltext', '', 'post', 'string', 2);
         if ($params->get('xssFiltering')) {
             $filter = new JFilterInput(array(), array(), 1, 1, 0);
             $row->introtext = $filter->clean($row->introtext);
             $row->fulltext = $filter->clean($row->fulltext);
         }
     }
     if ($row->id) {
         $datenow =& JFactory::getDate();
         $row->modified = $datenow->toMySQL();
         $row->modified_by = $user->get('id');
     } else {
         $row->ordering = $row->getNextOrder("catid = {$row->catid} AND trash = 0");
         if ($row->featured) {
             $row->featured_ordering = $row->getNextOrder("featured = 1 AND trash = 0", 'featured_ordering');
         }
     }
     $row->created_by = $row->created_by ? $row->created_by : $user->get('id');
     if ($front) {
         $K2Permissions =& K2Permissions::getInstance();
         if (!$K2Permissions->permissions->get('editAll')) {
             $row->created_by = $user->get('id');
         }
     }
     if ($row->created && strlen(trim($row->created)) <= 10) {
         $row->created .= ' 00:00:00';
     }
     $config =& JFactory::getConfig();
     $tzoffset = $config->getValue('config.offset');
     $date =& JFactory::getDate($row->created, $tzoffset);
     $row->created = $date->toMySQL();
     if (strlen(trim($row->publish_up)) <= 10) {
         $row->publish_up .= ' 00:00:00';
     }
     $date =& JFactory::getDate($row->publish_up, $tzoffset);
     $row->publish_up = $date->toMySQL();
     if (trim($row->publish_down) == JText::_('K2_NEVER') || trim($row->publish_down) == '') {
         $row->publish_down = $nullDate;
     } else {
         if (strlen(trim($row->publish_down)) <= 10) {
             $row->publish_down .= ' 00:00:00';
         }
         $date =& JFactory::getDate($row->publish_down, $tzoffset);
         $row->publish_down = $date->toMySQL();
     }
     $metadata = JRequest::getVar('meta', null, 'post', 'array');
     if (is_array($metadata)) {
         $txt = array();
         foreach ($metadata as $k => $v) {
             if ($k == 'description') {
                 $row->metadesc = $v;
             } elseif ($k == 'keywords') {
                 $row->metakey = $v;
             } else {
                 $txt[] = "{$k}={$v}";
             }
         }
         $row->metadata = implode("\n", $txt);
     }
     if (!$row->check()) {
         $mainframe->redirect('index.php?option=com_k2&view=item&cid=' . $row->id, $row->getError(), 'error');
     }
     $dispatcher =& JDispatcher::getInstance();
     JPluginHelper::importPlugin('k2');
     $result = $dispatcher->trigger('onBeforeK2Save', array(&$row, $isNew));
     if (in_array(false, $result, true)) {
         $this->setError($row->getError());
         return false;
     }
     // JoomFish! Front-end editing compatibility
     if ($mainframe->isSite() && JFolder::exists(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_joomfish' . DS . 'contentelements')) {
         if (version_compare(phpversion(), '5.0') < 0) {
             $tmpRow = $row;
         } else {
             $tmpRow = clone $row;
         }
     }
     if (!$row->store()) {
         $this->setError($row->getError());
         return false;
     }
     // JoomFish! Front-end editing compatibility
     if ($mainframe->isSite() && JFolder::exists(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_joomfish' . DS . 'contentelements')) {
         $itemID = $row->id;
         $row = $tmpRow;
         $row->id = $itemID;
     }
     if (!$params->get('disableCompactOrdering')) {
         $row->reorder("catid = {$row->catid} AND trash = 0");
     }
     if ($row->featured && !$params->get('disableCompactOrdering')) {
         $row->reorder("featured = 1 AND trash = 0", 'featured_ordering');
     }
     $files = JRequest::get('files');
     //Image
     if ((int) $params->get('imageMemoryLimit')) {
         ini_set('memory_limit', (int) $params->get('imageMemoryLimit') . 'M');
     }
     $existingImage = JRequest::getVar('existingImage');
     if ((@$files['image']['error'] === 0 || $existingImage) && !JRequest::getBool('del_image')) {
         if ($files['image']['error'] === 0) {
             $image = $files['image'];
         } else {
             $image = JPATH_SITE . DS . JPath::clean($existingImage);
         }
         $handle = new Upload($image);
         $handle->allowed = array('image/*');
         if ($handle->uploaded) {
             //Image params
             $category =& JTable::getInstance('K2Category', 'Table');
             $category->load($row->catid);
             $cparams = new JParameter($category->params);
             if ($cparams->get('inheritFrom')) {
                 $masterCategoryID = $cparams->get('inheritFrom');
                 $query = "SELECT * FROM #__k2_categories WHERE id=" . (int) $masterCategoryID;
                 $db->setQuery($query, 0, 1);
                 $masterCategory = $db->loadObject();
                 $cparams = new JParameter($masterCategory->params);
             }
             $params->merge($cparams);
             //Original image
             $savepath = JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'src';
             $handle->image_convert = 'jpg';
             $handle->jpeg_quality = 100;
             $handle->file_auto_rename = false;
             $handle->file_overwrite = true;
             $handle->file_new_name_body = md5("Image" . $row->id);
             $handle->Process($savepath);
             $filename = $handle->file_dst_name_body;
             $savepath = JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache';
             //XLarge image
             $handle->image_resize = true;
             $handle->image_ratio_y = true;
             $handle->image_convert = 'jpg';
             $handle->jpeg_quality = $params->get('imagesQuality');
             $handle->file_auto_rename = false;
             $handle->file_overwrite = true;
             $handle->file_new_name_body = $filename . '_XL';
             if (JRequest::getInt('itemImageXL')) {
                 $imageWidth = JRequest::getInt('itemImageXL');
             } else {
                 $imageWidth = $params->get('itemImageXL', '800');
             }
             $handle->image_x = $imageWidth;
             $handle->Process($savepath);
             //Large image
             $handle->image_resize = true;
             $handle->image_ratio_y = true;
             $handle->image_convert = 'jpg';
             $handle->jpeg_quality = $params->get('imagesQuality');
             $handle->file_auto_rename = false;
             $handle->file_overwrite = true;
             $handle->file_new_name_body = $filename . '_L';
             if (JRequest::getInt('itemImageL')) {
                 $imageWidth = JRequest::getInt('itemImageL');
             } else {
                 $imageWidth = $params->get('itemImageL', '600');
             }
             $handle->image_x = $imageWidth;
             $handle->Process($savepath);
             //Medium image
             $handle->image_resize = true;
             $handle->image_ratio_y = true;
             $handle->image_convert = 'jpg';
             $handle->jpeg_quality = $params->get('imagesQuality');
             $handle->file_auto_rename = false;
             $handle->file_overwrite = true;
             $handle->file_new_name_body = $filename . '_M';
             if (JRequest::getInt('itemImageM')) {
                 $imageWidth = JRequest::getInt('itemImageM');
             } else {
                 $imageWidth = $params->get('itemImageM', '400');
             }
             $handle->image_x = $imageWidth;
             $handle->Process($savepath);
             //Small image
             $handle->image_resize = true;
             $handle->image_ratio_y = true;
             $handle->image_convert = 'jpg';
             $handle->jpeg_quality = $params->get('imagesQuality');
             $handle->file_auto_rename = false;
             $handle->file_overwrite = true;
             $handle->file_new_name_body = $filename . '_S';
             if (JRequest::getInt('itemImageS')) {
                 $imageWidth = JRequest::getInt('itemImageS');
             } else {
                 $imageWidth = $params->get('itemImageS', '200');
             }
             $handle->image_x = $imageWidth;
             $handle->Process($savepath);
             //XSmall image
             $handle->image_resize = true;
             $handle->image_ratio_y = true;
             $handle->image_convert = 'jpg';
             $handle->jpeg_quality = $params->get('imagesQuality');
             $handle->file_auto_rename = false;
             $handle->file_overwrite = true;
             $handle->file_new_name_body = $filename . '_XS';
             if (JRequest::getInt('itemImageXS')) {
                 $imageWidth = JRequest::getInt('itemImageXS');
             } else {
                 $imageWidth = $params->get('itemImageXS', '100');
             }
             $handle->image_x = $imageWidth;
             $handle->Process($savepath);
             //Generic image
             $handle->image_resize = true;
             $handle->image_ratio_y = true;
             $handle->image_convert = 'jpg';
             $handle->jpeg_quality = $params->get('imagesQuality');
             $handle->file_auto_rename = false;
             $handle->file_overwrite = true;
             $handle->file_new_name_body = $filename . '_Generic';
             $imageWidth = $params->get('itemImageGeneric', '300');
             $handle->image_x = $imageWidth;
             $handle->Process($savepath);
             if ($files['image']['error'] === 0) {
                 $handle->Clean();
             }
         } else {
             $this->setError($handle->error);
             return false;
         }
     }
     if (JRequest::getBool('del_image')) {
         $current =& JTable::getInstance('K2Item', 'Table');
         $current->load($row->id);
         $filename = md5("Image" . $current->id);
         if (JFile::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'src' . DS . $filename . '.jpg')) {
             JFile::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'src' . DS . $filename . '.jpg');
         }
         if (JFile::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_XS.jpg')) {
             JFile::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_XS.jpg');
         }
         if (JFile::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_S.jpg')) {
             JFile::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_S.jpg');
         }
         if (JFile::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_M.jpg')) {
             JFile::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_M.jpg');
         }
         if (JFile::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_L.jpg')) {
             JFile::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_L.jpg');
         }
         if (JFile::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_XL.jpg')) {
             JFile::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_XL.jpg');
         }
         if (JFile::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_Generic.jpg')) {
             JFile::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . $filename . '_Generic.jpg');
         }
         $row->image_caption = '';
         $row->image_credits = '';
     }
     //Attachments
     $attachments = JRequest::getVar('attachment_file', NULL, 'FILES', 'array');
     $attachments_names = JRequest::getVar('attachment_name', '', 'POST', 'array');
     $attachments_titles = JRequest::getVar('attachment_title', '', 'POST', 'array');
     $attachments_title_attributes = JRequest::getVar('attachment_title_attribute', '', 'POST', 'array');
     $attachments_existing_files = JRequest::getVar('attachment_existing_file', '', 'POST', 'array');
     $attachmentFiles = array();
     if (count($attachments)) {
         foreach ($attachments as $k => $l) {
             foreach ($l as $i => $v) {
                 if (!array_key_exists($i, $attachmentFiles)) {
                     $attachmentFiles[$i] = array();
                 }
                 $attachmentFiles[$i][$k] = $v;
             }
         }
         $path = $params->get('attachmentsFolder', NULL);
         if (is_null($path)) {
             $savepath = JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'attachments';
         } else {
             $savepath = $path;
         }
         $counter = 0;
         foreach ($attachmentFiles as $key => $file) {
             if ($file["tmp_name"] || $attachments_existing_files[$key]) {
                 if ($attachments_existing_files[$key]) {
                     $file = JPATH_SITE . DS . JPath::clean($attachments_existing_files[$key]);
                 }
                 $handle = new Upload($file);
                 if ($handle->uploaded) {
                     $handle->file_auto_rename = true;
                     $handle->allowed[] = 'application/x-zip';
                     $handle->allowed[] = 'application/download';
                     $handle->Process($savepath);
                     $filename = $handle->file_dst_name;
                     $handle->Clean();
                     $attachment =& JTable::getInstance('K2Attachment', 'Table');
                     $attachment->itemID = $row->id;
                     $attachment->filename = $filename;
                     $attachment->title = empty($attachments_titles[$counter]) ? $filename : $attachments_titles[$counter];
                     $attachment->titleAttribute = empty($attachments_title_attributes[$counter]) ? $filename : $attachments_title_attributes[$counter];
                     $attachment->store();
                 } else {
                     $this->setError($handle->error);
                     return false;
                 }
             }
             $counter++;
         }
     }
     //Gallery
     $flickrGallery = JRequest::getVar('flickrGallery');
     if ($flickrGallery) {
         $row->gallery = '{gallery}' . $flickrGallery . '{/gallery}';
     }
     if (isset($files['gallery']) && $files['gallery']['error'] == 0 && !JRequest::getBool('del_gallery')) {
         $handle = new Upload($files['gallery']);
         $handle->file_auto_rename = true;
         $savepath = JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'galleries';
         $handle->allowed = array("application/download", "application/rar", "application/x-rar-compressed", "application/arj", "application/gnutar", "application/x-bzip", "application/x-bzip2", "application/x-compressed", "application/x-gzip", "application/x-zip-compressed", "application/zip", "multipart/x-zip", "multipart/x-gzip", "application/x-unknown", "application/x-zip");
         if ($handle->uploaded) {
             $handle->Process($savepath);
             $handle->Clean();
             if (JFolder::exists($savepath . DS . $row->id)) {
                 JFolder::delete($savepath . DS . $row->id);
             }
             if (!JArchive::extract($savepath . DS . $handle->file_dst_name, $savepath . DS . $row->id)) {
                 $this->setError(JText::_('K2_GALLERY_UPLOAD_ERROR_CANNOT_EXTRACT_ARCHIVE'));
                 return false;
             } else {
                 $row->gallery = '{gallery}' . $row->id . '{/gallery}';
             }
             JFile::delete($savepath . DS . $handle->file_dst_name);
             $handle->Clean();
         } else {
             $this->setError($handle->error);
             return false;
         }
     }
     if (JRequest::getBool('del_gallery')) {
         $current =& JTable::getInstance('K2Item', 'Table');
         $current->load($row->id);
         if (JFolder::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'galleries' . DS . $current->id)) {
             JFolder::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'galleries' . DS . $current->id);
         }
         $row->gallery = '';
     }
     //Video
     if (!JRequest::getBool('del_video')) {
         if (isset($files['video']) && $files['video']['error'] == 0) {
             $videoExtensions = array("flv", "mp4", "ogv", "webm", "f4v", "m4v", "3gp", "3g2", "mov", "mpeg", "mpg", "avi", "wmv", "divx");
             $audioExtensions = array("mp3", "aac", "m4a", "ogg", "wma");
             $validExtensions = array_merge($videoExtensions, $audioExtensions);
             $filetype = JFile::getExt($files['video']['name']);
             if (!in_array($filetype, $validExtensions)) {
                 $this->setError(JText::_('K2_INVALID_VIDEO_FILE'));
                 return false;
             }
             if (in_array($filetype, $videoExtensions)) {
                 $savepath = JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'videos';
             } else {
                 $savepath = JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'audio';
             }
             $filename = JFile::stripExt($files['video']['name']);
             JFile::upload($files['video']['tmp_name'], $savepath . DS . $row->id . '.' . $filetype);
             $filetype = JFile::getExt($files['video']['name']);
             $row->video = '{' . $filetype . '}' . $row->id . '{/' . $filetype . '}';
         } else {
             if (JRequest::getVar('remoteVideo')) {
                 $fileurl = JRequest::getVar('remoteVideo');
                 $filetype = JFile::getExt($fileurl);
                 $row->video = '{' . $filetype . 'remote}' . $fileurl . '{/' . $filetype . 'remote}';
             }
             if (JRequest::getVar('videoID')) {
                 $provider = JRequest::getWord('videoProvider');
                 $videoID = JRequest::getVar('videoID');
                 $row->video = '{' . $provider . '}' . $videoID . '{/' . $provider . '}';
             }
             if (JRequest::getVar('embedVideo', '', 'post', 'string', JREQUEST_ALLOWRAW)) {
                 $row->video = JRequest::getVar('embedVideo', '', 'post', 'string', JREQUEST_ALLOWRAW);
             }
         }
     } else {
         $current =& JTable::getInstance('K2Item', 'Table');
         $current->load($row->id);
         preg_match_all("#^{(.*?)}(.*?){#", $current->video, $matches, PREG_PATTERN_ORDER);
         $videotype = $matches[1][0];
         $videofile = $matches[2][0];
         if (in_array($videotype, $videoExtensions)) {
             if (JFile::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'videos' . DS . $videofile . '.' . $videotype)) {
                 JFile::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'videos' . DS . $videofile . '.' . $videotype);
             }
         }
         if (in_array($videotype, $audioExtensions)) {
             if (JFile::exists(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'audio' . DS . $videofile . '.' . $videotype)) {
                 JFile::delete(JPATH_ROOT . DS . 'media' . DS . 'k2' . DS . 'audio' . DS . $videofile . '.' . $videotype);
             }
         }
         $row->video = '';
         $row->video_caption = '';
         $row->video_credits = '';
     }
     //Tags
     if (@$user->gid < 24 && $params->get('lockTags')) {
         $params->set('taggingSystem', 0);
     }
     $db =& JFactory::getDBO();
     $query = "DELETE FROM #__k2_tags_xref WHERE itemID={intval({$row->id})}";
     $db->setQuery($query);
     $db->query();
     if ($params->get('taggingSystem')) {
         if (@$user->gid < 24 && $params->get('lockTags')) {
             JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
         }
         $tags = JRequest::getVar('tags', NULL, 'POST', 'array');
         if (count($tags)) {
             $tags = array_unique($tags);
             foreach ($tags as $tag) {
                 $tag = str_replace('-', '', $tag);
                 $query = "SELECT id FROM #__k2_tags WHERE name=" . $db->Quote($tag);
                 $db->setQuery($query);
                 $tagID = $db->loadResult();
                 if ($tagID) {
                     $query = "INSERT INTO #__k2_tags_xref (`id`, `tagID`, `itemID`) VALUES (NULL, {intval({$tagID})}, {intval({$row->id})})";
                     $db->setQuery($query);
                     $db->query();
                 } else {
                     $K2Tag =& JTable::getInstance('K2Tag', 'Table');
                     $K2Tag->name = $tag;
                     $K2Tag->published = 1;
                     $K2Tag->check();
                     $K2Tag->store();
                     $query = "INSERT INTO #__k2_tags_xref (`id`, `tagID`, `itemID`) VALUES (NULL, {intval({$K2Tag->id})}, {intval({$row->id})})";
                     $db->setQuery($query);
                     $db->query();
                 }
             }
         }
     } else {
         $tags = JRequest::getVar('selectedTags', NULL, 'POST', 'array');
         if (count($tags)) {
             foreach ($tags as $tagID) {
                 $query = "INSERT INTO #__k2_tags_xref (`id`, `tagID`, `itemID`) VALUES (NULL, {intval({$tagID})}, {intval({$row->id})})";
                 $db->setQuery($query);
                 $db->query();
             }
         }
     }
     if ($front) {
         if (!K2HelperPermissions::canPublishItem($row->catid) && $row->published) {
             $row->published = 0;
             $mainframe->enqueueMessage(JText::_('K2_YOU_DONT_HAVE_THE_PERMISSION_TO_PUBLISH_ITEMS'), 'notice');
         }
     }
     if (!$row->store()) {
         $this->setError($row->getError());
         return false;
     }
     $cache =& JFactory::getCache('com_k2');
     $cache->clean();
     $dispatcher->trigger('onAfterK2Save', array(&$row, $isNew));
     return $row;
 }
Ejemplo n.º 15
0
    $row->load($folder);
    $isNew = is_null($row->id);
    if ($view == 'galleries') {
        if ($task == 'create') {
            if ($isNew && !K2HelperPermissions::canAddItem()) {
                $canAccess = false;
            }
            if (!$isNew && !K2HelperPermissions::canEditItem($row->created_by, $row->catid)) {
                $canAccess = false;
            }
        } else {
            $canAccess = false;
        }
    } else {
        if ($view == 'gallery') {
            if ($isNew && !K2HelperPermissions::canAddItem()) {
                $canAccess = false;
            }
            if (!$isNew && !K2HelperPermissions::canEditItem($row->created_by, $row->catid)) {
                $canAccess = false;
            }
        }
    }
    if (!$canAccess) {
        JError::raiseWarning(403, JText::_('JERROR_ALERTNOAUTHOR'));
        $application->redirect('index.php');
    }
}
// Bootstrap
if (JFile::exists(JPATH_COMPONENT_ADMINISTRATOR . '/controllers/' . $view . '.php')) {
    JRequest::setVar('view', $view);
Ejemplo n.º 16
0
 function users()
 {
     $itemID = JRequest::getInt('itemID');
     JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . DS . 'tables');
     $item = JTable::getInstance('K2Item', 'Table');
     $item->load($itemID);
     if (!K2HelperPermissions::canAddItem() && !K2HelperPermissions::canEditItem($item->created_by, $item->catid)) {
         JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
     }
     $K2Permissions = K2Permissions::getInstance();
     if (!$K2Permissions->permissions->get('editAll')) {
         JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
     }
     JRequest::setVar('tmpl', 'component');
     $mainframe = JFactory::getApplication();
     $params = JComponentHelper::getParams('com_k2');
     $language = JFactory::getLanguage();
     $language->load('com_k2', JPATH_ADMINISTRATOR);
     $document = JFactory::getDocument();
     if (version_compare(JVERSION, '1.6.0', 'ge')) {
         JHtml::_('behavior.framework');
     } else {
         JHTML::_('behavior.mootools');
     }
     // CSS
     $document->addStyleSheet(JURI::root(true) . '/media/k2/assets/css/k2.css?v=2.6.8');
     // JS
     K2HelperHTML::loadjQuery(true);
     $document->addScript(JURI::root(true) . '/media/k2/assets/js/k2.js?v=2.6.8&amp;sitepath=' . JURI::root(true) . '/');
     $this->addViewPath(JPATH_COMPONENT_ADMINISTRATOR . DS . 'views');
     $this->addModelPath(JPATH_COMPONENT_ADMINISTRATOR . DS . 'models');
     $view = $this->getView('users', 'html');
     $view->addTemplatePath(JPATH_COMPONENT_ADMINISTRATOR . DS . 'views' . DS . 'users' . DS . 'tmpl');
     $view->setLayout('element');
     $view->display();
 }
Ejemplo n.º 17
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);
    }
Ejemplo n.º 18
0
 public static function checkPermissions()
 {
     $view = JRequest::getCmd('view');
     if ($view != 'item') {
         return;
     }
     $task = JRequest::getCmd('task');
     $user = JFactory::getUser();
     if ($user->guest && ($task == 'add' || $task == 'edit')) {
         $mainframe = JFactory::getApplication();
         $uri = JURI::getInstance();
         $return = base64_encode($uri->toString());
         $mainframe->enqueueMessage(JText::_('K2_YOU_NEED_TO_LOGIN_FIRST'), 'notice');
         if (K2_JVERSION == '15') {
             $mainframe->redirect('index.php?option=com_user&view=login&return=' . $return . '&tmpl=component');
         } else {
             $mainframe->redirect('index.php?option=com_users&view=login&return=' . $return . '&tmpl=component');
         }
     }
     switch ($task) {
         case 'add':
             if (!K2HelperPermissions::canAddItem()) {
                 JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
             }
             break;
         case 'edit':
         case 'deleteAttachment':
         case 'checkin':
             $cid = JRequest::getInt('cid');
             if (!$cid) {
                 JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
             }
             JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . DS . 'tables');
             $item = JTable::getInstance('K2Item', 'Table');
             $item->load($cid);
             if (!K2HelperPermissions::canEditItem($item->created_by, $item->catid)) {
                 JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
             }
             break;
         case 'save':
             $cid = JRequest::getInt('id');
             if ($cid) {
                 JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . DS . 'tables');
                 $item = JTable::getInstance('K2Item', 'Table');
                 $item->load($cid);
                 if (!K2HelperPermissions::canEditItem($item->created_by, $item->catid)) {
                     JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
                 }
             } else {
                 if (!K2HelperPermissions::canAddItem()) {
                     JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
                 }
             }
             break;
         case 'tag':
             if (!K2HelperPermissions::canAddTag()) {
                 JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
             }
             break;
         case 'extraFields':
             if (!K2HelperPermissions::canRenderExtraFields()) {
                 JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
             }
             break;
     }
 }