/**
  * Method to get the associations for a given item
  *
  * @param   integer  $id    Id of the item
  * @param   string   $view  Name of the view
  *
  * @return  array   Array of associations for the item
  *
  * @since  3.0
  */
 public static function getAssociations($id = 0, $view = null)
 {
     jimport('helper.route', JPATH_COMPONENT_SITE);
     $app = JFactory::getApplication();
     $jinput = $app->input;
     $view = is_null($view) ? $jinput->get('view') : $view;
     $id = empty($id) ? $jinput->getInt('id') : $id;
     if ($view == 'item') {
         if ($id) {
             //$associations = JLanguageAssociations::getAssociations('com_content', '#__content', 'com_content.item', $id);
             $associations = FlexicontentHelperAssociation::getItemAssociations($id);
             $return = array();
             foreach ($associations as $tag => $item) {
                 $return[$tag] = FlexicontentHelperRoute::getItemRoute($item->id, $item->catid, 0, $item);
             }
             return $return;
         }
     } else {
         if ($view == 'category') {
             $cid = $jinput->getInt('cid');
             if ($cid) {
                 $associations = FlexicontentHelperAssociation::getCatAssociations($cid);
                 $return = array();
                 foreach ($associations as $tag => $item) {
                     $return[$tag] = FlexicontentHelperRoute::getCategoryRoute($item->catid, 0, array(), $item);
                 }
                 return $return;
             }
         }
     }
     return array();
 }
Exemple #2
0
 public static function getLoc(&$params)
 {
     $catid = $params->get('catid');
     $fieldaddressid = $params->get('fieldaddressid');
     //var_dump ($catid);
     global $globalcats;
     //var_dump ($globalcats);
     $catlist = !empty($globalcats[$catid]->descendants) ? $globalcats[$catid]->descendants : $catid;
     $catids_join = 'JOIN #__flexicontent_cats_item_relations AS rel ON rel.itemid = a.id ';
     //var_dump ($catlist);
     $catids_where = ' rel.catid IN (' . $catlist . ') ';
     //var_dump ($catids_where);
     // recupere la connexion à la BD
     if (!empty($fieldaddressid)) {
         $count = $params->get('count');
         $forced_itemid = $params->get('forced_itemid', '');
         $db = JFactory::getDbo();
         $queryLoc = 'SELECT a.id, a.title, b.field_id, b.value , a.catid FROM #__content  AS a LEFT JOIN #__flexicontent_fields_item_relations AS b ON a.id = b.item_id ' . $catids_join . ' WHERE b.field_id = ' . $fieldaddressid . ' AND ' . $catids_where . ' AND state = 1 ORDER BY title ' . $count;
         //var_dump ($queryLoc);
         $db->setQuery($queryLoc);
         $itemsLoc = $db->loadObjectList();
         //var_dump ($itemsLoc);
         foreach ($itemsLoc as &$itemLoc) {
             $id = $itemLoc->id;
             //$itemLoc->link = JRoute::_( FlexicontentHelperRoute::getItemRoute($id, $catid ) );
             $itemLoc->link = JRoute::_(FlexicontentHelperRoute::getItemRoute($itemLoc->id, $itemLoc->catid, $forced_itemid, $itemLoc));
         }
         return $itemsLoc;
     } else {
         echo JText::_('FLEXI_GOOGLEMAP_ADRESSFORGOT');
     }
 }
 function getObjectLink($id)
 {
     require_once JPATH_ROOT . DS . 'components' . DS . 'com_flexicontent' . DS . 'helpers' . DS . 'route.php';
     $db =& JFactory::getDBO();
     $query = 'SELECT CASE WHEN CHAR_LENGTH(i.alias) THEN CONCAT_WS(\':\', i.id, i.alias) ELSE i.id END as slug,' . ' CASE WHEN CHAR_LENGTH(c.alias) THEN CONCAT_WS(\':\', c.id, c.alias) ELSE c.id END as categoryslug' . ' FROM #__content AS i' . ' LEFT JOIN #__categories AS c ON c.id = i.catid' . ' WHERE i.id = ' . $id;
     $db->setQuery($query);
     $row = $db->loadObject();
     $link = JRoute::_(FlexicontentHelperRoute::getItemRoute($row->slug, $row->categoryslug));
     return $link;
 }
 function getObjectInfo($id, $language = null)
 {
     $info = new JCommentsObjectInfo();
     $routerHelper = JPATH_ROOT . '/components/com_flexicontent/helpers/route.php';
     if (is_file($routerHelper)) {
         require_once $routerHelper;
         $db = JFactory::getDBO();
         $query = 'SELECT i.id, i.title, i.access, i.created_by ' . ' , CASE WHEN CHAR_LENGTH(i.alias) THEN CONCAT_WS(\':\', i.id, i.alias) ELSE i.id END as slug' . ' , CASE WHEN CHAR_LENGTH(c.alias) THEN CONCAT_WS(\':\', c.id, c.alias) ELSE c.id END as catslug' . ' FROM #__content AS i' . ' LEFT JOIN #__categories AS c ON c.id = i.catid' . ' WHERE i.id = ' . $id;
         $db->setQuery($query);
         $row = $db->loadObject();
         if (!empty($row)) {
             $info->title = $row->title;
             $info->access = $row->access;
             $info->userid = $row->created_by;
             $info->link = JRoute::_(FlexicontentHelperRoute::getItemRoute($row->slug, $row->catslug));
         }
     }
     return $info;
 }
 function sendNotificationEmails(&$notify_vars, &$params, $manual_approval_request = 0)
 {
     $needs_version_reviewal = $notify_vars->needs_version_reviewal;
     $needs_publication_approval = $notify_vars->needs_publication_approval;
     $isnew = $notify_vars->isnew;
     $notify_emails = $notify_vars->notify_emails;
     $notify_text = $notify_vars->notify_text;
     $before_cats = $notify_vars->before_cats;
     $after_cats = $notify_vars->after_cats;
     $oitem = $notify_vars->original_item;
     if (!count($notify_emails)) {
         return true;
     }
     $app = JFactory::getApplication();
     $db = JFactory::getDBO();
     $user = JFactory::getUser();
     $use_versioning = $this->_cparams->get('use_versioning', 1);
     // Get category titles of categories add / removed from the item
     if (!$isnew) {
         $cats_added_ids = array_diff(array_keys($after_cats), array_keys($before_cats));
         foreach ($cats_added_ids as $cats_added_id) {
             $cats_added_titles[] = $after_cats[$cats_added_id]->title;
         }
         $cats_removed_ids = array_diff(array_keys($before_cats), array_keys($after_cats));
         foreach ($cats_removed_ids as $cats_removed_id) {
             $cats_removed_titles[] = $before_cats[$cats_removed_id]->title;
         }
         $cats_altered = count($cats_added_ids) + count($cats_removed_ids);
         $after_maincat = $this->get('catid');
     }
     // Get category titles in the case of new item or categories unchanged
     if ($isnew || !$cats_altered) {
         foreach ($after_cats as $after_cat) {
             $cats_titles[] = $after_cat->title;
         }
     }
     // **************
     // CREATE SUBJECT
     // **************
     $srvname = preg_replace('#www\\.#', '', $_SERVER['SERVER_NAME']);
     $url = parse_url($srvname);
     $domain = !empty($url["host"]) ? $url["host"] : $url["path"];
     $subject = '[' . $domain . '] - ';
     if (!$manual_approval_request) {
         // (a) ADD INFO of being new or updated
         $subject .= JText::_($isnew ? 'FLEXI_NF_NEW_CONTENT_SUBMITTED' : 'FLEXI_NF_EXISTING_CONTENT_UPDATED') . " ";
         // (b) ADD INFO about editor's name and username (or being guest)
         $subject .= !$user->id ? JText::sprintf('FLEXI_NF_BY_GUEST') : JText::sprintf('FLEXI_NF_BY_USER', $user->get('name'), $user->get('username'));
         // (c) (new items) ADD INFO for content needing publication approval
         if ($isnew) {
             $subject .= ": ";
             $subject .= JText::_($needs_publication_approval ? 'FLEXI_NF_NEEDS_PUBLICATION_APPROVAL' : 'FLEXI_NF_NO_APPROVAL_NEEDED');
         }
         // (d) (existing items with versioning) ADD INFO for content needing version reviewal
         if (!$isnew && $use_versioning) {
             $subject .= ": ";
             $subject .= JText::_($needs_version_reviewal ? 'FLEXI_NF_NEEDS_VERSION_REVIEWAL' : 'FLEXI_NF_NO_REVIEWAL_NEEDED');
         }
     } else {
         $subject .= JText::_('FLEXI_APPROVAL_REQUEST');
     }
     // *******************
     // CREATE MESSAGE BODY
     // *******************
     $nf_extra_properties = $params->get('nf_extra_properties', array('creator', 'modifier', 'created', 'modified', 'viewlink', 'editlinkfe', 'editlinkbe', 'introtext', 'fulltext'));
     $nf_extra_properties = FLEXIUtilities::paramToArray($nf_extra_properties);
     // ADD INFO for item title
     $body = '<u>' . JText::_('FLEXI_NF_CONTENT_TITLE') . "</u>: ";
     if (!$isnew) {
         $_changed = $oitem->title != $this->get('title');
         $body .= " [ " . JText::_($_changed ? 'FLEXI_NF_MODIFIED' : 'FLEXI_NF_UNCHANGED') . " ] : <br/>\r\n";
         $body .= !$_changed ? "" : $oitem->title . " &nbsp; ==> &nbsp; ";
     }
     $body .= $this->get('title') . "<br/>\r\n<br/>\r\n";
     // ADD INFO about state
     $state_names = array(1 => 'FLEXI_PUBLISHED', -5 => 'FLEXI_IN_PROGRESS', 0 => 'FLEXI_UNPUBLISHED', -3 => 'FLEXI_PENDING', -4 => 'FLEXI_TO_WRITE', FLEXI_J16GE ? 2 : -1 => 'FLEXI_ARCHIVED', -2 => 'FLEXI_TRASHED');
     $body .= '<u>' . JText::_('FLEXI_NF_CONTENT_STATE') . "</u>: ";
     if (!$isnew) {
         $_changed = $oitem->state != $this->get('state');
         $body .= " [ " . JText::_($_changed ? 'FLEXI_NF_MODIFIED' : 'FLEXI_NF_UNCHANGED') . " ] : <br/>\r\n";
         $body .= !$_changed ? "" : JText::_($state_names[$oitem->state]) . " &nbsp; ==> &nbsp; ";
     }
     $body .= JText::_($state_names[$this->get('state')]) . "<br/><br/>\r\n";
     // ADD INFO for author / modifier
     if (in_array('creator', $nf_extra_properties)) {
         $body .= '<u>' . JText::_('FLEXI_NF_CREATOR_LONG') . "</u>: ";
         if (!$isnew) {
             $_changed = $oitem->created_by != $this->get('created_by');
             $body .= " [ " . JText::_($_changed ? 'FLEXI_NF_MODIFIED' : 'FLEXI_NF_UNCHANGED') . " ] : <br/>\r\n";
             $body .= !$_changed ? "" : $oitem->creator . " &nbsp; ==> &nbsp; ";
         }
         $body .= $this->get('creator') . "<br/>\r\n";
     }
     if (in_array('modifier', $nf_extra_properties) && !$isnew) {
         $body .= '<u>' . JText::_('FLEXI_NF_MODIFIER_LONG') . "</u>: ";
         $body .= $this->get('modifier') . "<br/>\r\n";
     }
     $body .= "<br/>\r\n";
     // ADD INFO about creation / modification times. Use site's timezone !! we must
     // (a) set timezone to be site's timezone then
     // (b) call $date_OBJECT->format()  with s local flag parameter set to true
     $tz_offset = JFactory::getApplication()->getCfg('offset');
     if (FLEXI_J16GE) {
         $tz = new DateTimeZone($tz_offset);
     }
     $tz_offset_str = FLEXI_J16GE ? $tz->getOffset(new JDate()) / 3600 : $tz_offset;
     $tz_offset_str = ' &nbsp; (UTC+' . $tz_offset_str . ') ';
     if (in_array('created', $nf_extra_properties)) {
         $date_created = JFactory::getDate($this->get('created'));
         if (FLEXI_J16GE) {
             $date_created->setTimezone($tz);
         } else {
             $date_created->setOffset($tz_offset);
         }
         $body .= '<u>' . JText::_('FLEXI_NF_CREATION_TIME') . "</u>: ";
         $body .= FLEXI_J16GE ? $date_created->format($format = 'D, d M Y H:i:s', $local = true) : $date_created->toFormat($format = '%Y-%m-%d %H:%M:%S');
         $body .= $tz_offset_str . "<br/>\r\n";
     }
     if (in_array('modified', $nf_extra_properties) && !$isnew) {
         $date_modified = JFactory::getDate($this->get('modified'));
         if (FLEXI_J16GE) {
             $date_modified->setTimezone($tz);
         } else {
             $date_modified->setOffset($tz_offset);
         }
         $body .= '<u>' . JText::_('FLEXI_NF_MODIFICATION_TIME') . "</u>: ";
         $body .= FLEXI_J16GE ? $date_modified->format($format = 'D, d M Y H:i:s', $local = true) : $date_modified->toFormat($format = '%Y-%m-%d %H:%M:%S');
         $body .= $tz_offset_str . "<br/>\r\n";
     }
     $body .= "<br/>\r\n";
     // ADD INFO about category assignments
     $body .= '<u>' . JText::_('FLEXI_NF_CATEGORIES_ASSIGNMENTS') . '</u>';
     if (!$isnew) {
         $body .= " [ " . JText::_($cats_altered ? 'FLEXI_NF_MODIFIED' : 'FLEXI_NF_UNCHANGED') . " ] : <br/>\r\n";
     } else {
         $body .= " : <br/>\r\n";
     }
     foreach ($cats_titles as $i => $cats_title) {
         $body .= " &nbsp; " . ($i + 1) . ". " . $cats_title . "<br/>\r\n";
     }
     // ADD INFO for category assignments added or removed
     if (!empty($cats_added_titles) && count($cats_added_titles)) {
         $body .= '<u>' . JText::_('FLEXI_NF_ITEM_CATEGORIES_ADDED') . "</u> : <br/>\r\n";
         foreach ($cats_added_titles as $i => $cats_title) {
             $body .= " &nbsp; " . ($i + 1) . ". " . $cats_title . "<br/>\r\n";
         }
     }
     if (!empty($cats_removed_titles) && count($cats_removed_titles)) {
         $body .= '<u>' . JText::_('FLEXI_NF_ITEM_CATEGORIES_REMOVED') . "</u> : <br/>\r\n";
         foreach ($cats_removed_titles as $i => $cats_title) {
             $body .= " &nbsp; " . ($i + 1) . ". " . $cats_title . "<br/>\r\n";
         }
     }
     $body .= "<br/>\r\n<br/>\r\n";
     $lang = '&lang=' . substr($this->get('language'), 0, 2);
     // ADD INFO for custom notify text
     $subject .= ' ' . JText::_($notify_text);
     // ADD INFO for view/edit link
     if (in_array('viewlink', $nf_extra_properties)) {
         $body .= '<u>' . JText::_('FLEXI_NF_VIEW_IN_FRONTEND') . "</u> : <br/>\r\n &nbsp; ";
         $link = JRoute::_(JURI::root(false) . FlexicontentHelperRoute::getItemRoute($this->get('id'), $this->get('catid')) . $lang);
         $body .= '<a href="' . $link . '" target="_blank">' . $link . "</a><br/>\r\n<br/>\r\n";
         // THIS IS BOGUS *** for unicode menu aliases
         //$body .= $link . "<br/>\r\n<br/>\r\n";
     }
     if (in_array('editlinkfe', $nf_extra_properties)) {
         $body .= '<u>' . JText::_('FLEXI_NF_EDIT_IN_FRONTEND') . "</u> : <br/>\r\n &nbsp; ";
         $link = JRoute::_(JURI::root(false) . 'index.php?option=com_flexicontent&view=' . FLEXI_ITEMVIEW . '&cid=' . $this->get('catid') . '&id=' . $this->get('id') . '&task=edit');
         $body .= '<a href="' . $link . '" target="_blank">' . $link . "</a><br/>\r\n<br/>\r\n";
         // THIS IS BOGUS *** for unicode menu aliases
         //$body .= $link . "<br/>\r\n<br/>\r\n";
     }
     if (in_array('editlinkbe', $nf_extra_properties)) {
         $body .= '<u>' . JText::_('FLEXI_NF_EDIT_IN_BACKEND') . "</u> : <br/>\r\n &nbsp; ";
         $fc_ctrl_task = FLEXI_J16GE ? 'task=items.edit' : 'controller=items&task=edit';
         $link = JRoute::_(JURI::root(false) . 'administrator/index.php?option=com_flexicontent&' . $fc_ctrl_task . '&cid=' . $this->get('id'));
         $body .= '<a href="' . $link . '" target="_blank">' . $link . "</a><br/>\r\n<br/>\r\n";
         // THIS IS BOGUS *** for unicode menu aliases
         //$body .= $link . "<br/>\r\n<br/>\r\n";
     }
     // ADD INFO for introtext/fulltext
     if ($params->get('nf_add_introtext')) {
         //echo "<pre>"; print_r($this->_item); exit;
         $body .= "<br/><br/>\r\n";
         $body .= "*************************************************************** <br/>\r\n";
         $body .= JText::_('FLEXI_NF_INTROTEXT_LONG') . "<br/>\r\n";
         $body .= "*************************************************************** <br/>\r\n";
         $body .= flexicontent_html::striptagsandcut($this->get('introtext'), 200);
     }
     if ($params->get('nf_add_fulltext')) {
         $body .= "<br/><br/>\r\n";
         $body .= "*************************************************************** <br/>\r\n";
         $body .= JText::_('FLEXI_NF_FULLTEXT_LONG') . "<br/>\r\n";
         $body .= "*************************************************************** <br/>\r\n";
         $body .= flexicontent_html::striptagsandcut($this->get('fulltext'), 200);
     }
     // **********
     // Send email
     // **********
     $from = $app->getCfg('mailfrom');
     $fromname = $app->getCfg('fromname');
     $recipient = $params->get('nf_send_as_bcc', 0) ? array($from) : $notify_emails;
     $html_mode = true;
     $cc = null;
     $bcc = $params->get('nf_send_as_bcc', 0) ? $notify_emails : null;
     $attachment = null;
     $replyto = null;
     $replytoname = null;
     if (!FLEXI_J16GE) {
         jimport('joomla.utilities.utility');
     }
     $send_result = FLEXI_J16GE ? JFactory::getMailer()->sendMail($from, $fromname, $recipient, $subject, $body, $html_mode, $cc, $bcc, $attachment, $replyto, $replytoname) : JUtility::sendMail($from, $fromname, $recipient, $subject, $body, $html_mode, $cc, $bcc, $attachment, $replyto, $replytoname);
     $debug_str = "" . "<br/>FROM: {$from}" . "<br/>FROMNAME:  {$fromname} <br/>" . "<br/>RECIPIENTS: " . implode(",", $recipient) . "<br/>BCC: " . ($bcc ? implode(",", $bcc) : '') . "<br/>" . "<br/>SUBJECT: {$subject} <br/>" . "<br/><br/>**********<br/>BODY<br/>**********<br/> {$body} <br/>";
     if ($send_result) {
         // OK
         if ($params->get('nf_enable_debug', 0)) {
             $app->enqueueMessage("Sending WORKFLOW notification emails SUCCESS", 'message');
             $app->enqueueMessage($debug_str, 'message');
         }
     } else {
         // NOT OK
         if ($params->get('nf_enable_debug', 0)) {
             $app->enqueueMessage("Sending WORKFLOW notification emails FAILED", 'warning');
             $app->enqueueMessage($debug_str, 'message');
         }
     }
     return $send_result;
 }
Exemple #6
0
 public function getLinks($args)
 {
     $view = isset($args->view) ? $args->view : '';
     if (!($view = 'category')) {
         return array();
     }
     require_once JPATH_SITE . DS . 'components' . DS . 'com_flexicontent' . DS . 'helpers' . DS . 'route.php';
     $items = array();
     $CategoryId = $args->cid;
     //adding categoryes
     $db =& JFactory::getDBO();
     $query = $db->getQuery(true);
     $query->clear();
     $query->select('id, title, lft, CASE WHEN CHAR_LENGTH(alias) THEN CONCAT_WS(\':\', id, alias) ELSE id END as slug');
     $query->from('#__categories');
     $query->where('published = 1 AND extension = \'com_content\' AND parent_id = ' . $CategoryId);
     $query->order('lft ASC');
     $db->setQuery($query);
     $categories = $db->loadObjectList();
     foreach ($categories as $category) {
         $items[] = array('url' => FlexicontentHelperRoute::getCategoryRoute($category->slug), 'id' => 'index.php?option=com_flexicontent_items&view=category&cid=' . $category->id, 'name' => $category->title, 'class' => 'folderflexiitems');
     }
     //adding items
     $query->clear();
     $query->select(' i.id as iid, i.title AS ititle, c.id as catid,' . ' CASE WHEN CHAR_LENGTH(i.alias) THEN CONCAT_WS(\':\', i.id, i.alias) ELSE i.id END as slug,' . ' CASE WHEN CHAR_LENGTH(c.alias) THEN CONCAT_WS(\':\', c.id, c.alias) ELSE c.id END as catslug');
     $query->from('#__content AS i' . ' LEFT JOIN #__flexicontent_cats_item_relations AS rel ON rel.itemid = i.id ' . ' LEFT JOIN #__categories AS c ON c.id = rel.catid ');
     $query->where('c.id = ' . $CategoryId);
     $query->order('i.title ASC');
     $db->setQuery($query);
     $contents = $db->loadObjectList();
     foreach ($contents as $content) {
         $items[] = array('url' => FlexicontentHelperRoute::getItemRoute($content->slug, $content->catslug), 'id' => 'index.php?option=com_flexicontent_items&view=category&cid=' . $category->id . '&id=' . $content->iid, 'name' => $content->ititle . '(id=' . $content->iid . ')', 'class' => 'fileflexiitems');
     }
     return $items;
 }
 private function _replaceContent(&$results, $i)
 {
     $acypluginsHelper = acymailing_get('helper.acyplugins');
     $tag = $acypluginsHelper->extractTag($results[1][$i]);
     $tag->id = intval($tag->id);
     if (!ACYMAILING_J16) {
         $query = 'SELECT a.*,b.name as authorname, c.alias as catalias, c.title as cattitle, s.alias as secalias, s.title as sectitle FROM ' . acymailing_table('content', false) . ' as a ';
         $query .= 'LEFT JOIN ' . acymailing_table('users', false) . ' as b ON a.created_by = b.id ';
         $query .= ' LEFT JOIN ' . acymailing_table('categories', false) . ' AS c ON c.id = a.catid ';
         $query .= ' LEFT JOIN ' . acymailing_table('sections', false) . ' AS s ON s.id = a.sectionid ';
         $query .= 'WHERE a.id = ' . $tag->id . ' LIMIT 1';
     } else {
         $query = 'SELECT a.*,b.name as authorname, c.alias as catalias, c.title as cattitle FROM ' . acymailing_table('content', false) . ' as a ';
         $query .= 'LEFT JOIN ' . acymailing_table('users', false) . ' as b ON a.created_by = b.id ';
         $query .= ' LEFT JOIN ' . acymailing_table('categories', false) . ' AS c ON c.id = a.catid ';
         $query .= 'WHERE a.id = ' . $tag->id . ' LIMIT 1';
     }
     $db = JFactory::getDBO();
     $db->setQuery($query);
     $article = $db->loadObject();
     $result = '';
     if (empty($article)) {
         $app = JFactory::getApplication();
         if ($app->isAdmin()) {
             $app->enqueueMessage('The article "' . $tag->id . '" could not be loaded', 'notice');
         }
         return $result;
     }
     if (!empty($tag->lang)) {
         $langid = (int) substr($tag->lang, strpos($tag->lang, ',') + 1);
         if (!empty($langid)) {
             $query = "SELECT reference_field, value FROM " . (ACYMAILING_J16 && file_exists(JPATH_SITE . DS . 'components' . DS . 'com_falang') ? '`#__falang_content`' : '`#__jf_content`') . " WHERE `published` = 1 AND `reference_table` = 'content' AND `language_id` = {$langid} AND `reference_id` = " . $tag->id;
             $db->setQuery($query);
             $translations = $db->loadObjectList();
             if (!empty($translations)) {
                 foreach ($translations as $oneTranslation) {
                     if (!empty($oneTranslation->value)) {
                         $translatedfield = $oneTranslation->reference_field;
                         $article->{$translatedfield} = $oneTranslation->value;
                     }
                 }
             }
         }
     }
     $acypluginsHelper = acymailing_get('helper.acyplugins');
     $acypluginsHelper->cleanHtml($article->introtext);
     $acypluginsHelper->cleanHtml($article->fulltext);
     if ($this->params->get('integration') == 'jreviews' and !empty($article->images)) {
         $firstpict = explode('|', trim(reset(explode("\n", $article->images))) . '|||||||');
         if (!empty($firstpict[0])) {
             $picturePath = file_exists(ACYMAILING_ROOT . 'images' . DS . 'stories' . DS . str_replace('/', DS, $firstpict[0])) ? ACYMAILING_LIVE . 'images/stories/' . $firstpict[0] : ACYMAILING_LIVE . 'images/' . $firstpict[0];
             $myPict = '<img src="' . $picturePath . '" alt="" hspace="5" style="margin:5px" align="left" border="' . intval($firstpict[5]) . '" />';
             $article->introtext = $myPict . $article->introtext;
         }
     }
     $completeId = $article->id;
     $completeCat = $article->catid;
     if (!empty($article->alias)) {
         $completeId .= ':' . $article->alias;
     }
     if (!empty($article->catalias)) {
         $completeCat .= ':' . $article->catalias;
     }
     if (empty($tag->itemid)) {
         if (!ACYMAILING_J16) {
             $completeSec = $article->sectionid;
             if (!empty($article->secalias)) {
                 $completeSec .= ':' . $article->secalias;
             }
             if ($this->params->get('integration') == 'flexicontent' && class_exists('FlexicontentHelperRoute')) {
                 $link = FlexicontentHelperRoute::getItemRoute($completeId, $completeCat, $completeSec);
             } else {
                 $link = ContentHelperRoute::getArticleRoute($completeId, $completeCat, $completeSec);
             }
         } else {
             if ($this->params->get('integration') == 'flexicontent' && class_exists('FlexicontentHelperRoute')) {
                 $link = FlexicontentHelperRoute::getItemRoute($completeId, $completeCat);
             } else {
                 $link = ContentHelperRoute::getArticleRoute($completeId, $completeCat);
             }
         }
     } else {
         $link = 'index.php?option=com_content&view=article&id=' . $completeId . '&catid=' . $completeCat;
     }
     if ($this->params->get('integration') == 'flexicontent' && !class_exists('FlexicontentHelperRoute')) {
         $link = 'index.php?option=com_flexicontent&view=items&id=' . $completeId;
     } elseif ($this->params->get('integration') == 'jaggyblog') {
         $link = 'index.php?option=com_jaggyblog&task=viewpost&id=' . $completeId;
     }
     if (!empty($tag->itemid)) {
         $link .= '&Itemid=' . $tag->itemid;
     }
     if (!empty($tag->lang)) {
         $link .= (strpos($link, '?') ? '&' : '?') . 'lang=' . substr($tag->lang, 0, strpos($tag->lang, ','));
     }
     if (!empty($tag->autologin)) {
         $link .= (strpos($link, '?') ? '&' : '?') . 'user={usertag:username|urlencode}&passw={usertag:password|urlencode}';
     }
     if (empty($tag->lang) && !empty($article->language) && $article->language != '*') {
         if (!isset($this->langcodes[$article->language])) {
             $db->setQuery('SELECT sef FROM #__languages WHERE lang_code = ' . $db->Quote($article->language) . ' ORDER BY `published` DESC LIMIT 1');
             $this->langcodes[$article->language] = $db->loadResult();
             if (empty($this->langcodes[$article->language])) {
                 $this->langcodes[$article->language] = $article->language;
             }
         }
         $link .= (strpos($link, '?') ? '&' : '?') . 'lang=' . $this->langcodes[$article->language];
     }
     $link = acymailing_frontendLink($link);
     $styleTitle = '';
     $styleTitleEnd = '';
     if ($tag->type != "title") {
         $styleTitle = '<h2 class="acymailing_title">';
         $styleTitleEnd = '</h2>';
     }
     if (empty($tag->notitle)) {
         if (!empty($tag->link)) {
             $result .= '<a href="' . $link . '" ';
             if ($tag->type != "title") {
                 $result .= 'style="text-decoration:none" name="content-' . $article->id . '" ';
             }
             $result .= 'target="_blank" >' . $styleTitle . $article->title . $styleTitleEnd . '</a>';
         } else {
             $result .= $styleTitle . $article->title . $styleTitleEnd;
         }
     }
     if (!empty($tag->author)) {
         $authorName = empty($article->created_by_alias) ? $article->authorname : $article->created_by_alias;
         if ($tag->type == 'title') {
             $result .= '<br/>';
         }
         $result .= '<span class="authorname">' . $authorName . '</span><br/>';
     }
     if (!empty($tag->created)) {
         if ($tag->type == 'title') {
             $result .= '<br/>';
         }
         $dateFormat = empty($tag->dateformat) ? JText::_('DATE_FORMAT_LC2') : $tag->dateformat;
         $result .= '<span class="createddate">' . JHTML::_('date', $article->created, $dateFormat) . '</span><br/>';
     }
     if (!isset($tag->pict) and $tag->type != 'title') {
         if ($this->params->get('removepictures', 'never') == 'always' || ($this->params->get('removepictures', 'never') == 'intro' and $tag->type == "intro")) {
             $tag->pict = 0;
         } else {
             $tag->pict = 1;
         }
     }
     if (strpos($article->introtext, 'jseblod') !== false and file_exists(ACYMAILING_ROOT . 'plugins' . DS . 'content' . DS . 'cckjseblod.php')) {
         global $mainframe;
         include_once ACYMAILING_ROOT . 'plugins' . DS . 'content' . DS . 'cckjseblod.php';
         if (function_exists('plgContentCCKjSeblod')) {
             $paramsContent = JComponentHelper::getParams('com_content');
             $article->text = $article->introtext . $article->fulltext;
             plgContentCCKjSeblod($article, $paramsContent);
             $article->introtext = $article->text;
             $article->fulltext = '';
         }
     }
     if ($tag->type != "title") {
         $contentText = '';
         if ($tag->type == "intro") {
             $forceReadMore = false;
             $wordwrap = $this->params->get('wordwrap', 0);
             if (!empty($wordwrap) and empty($article->fulltext)) {
                 $tagToKeep = '<br>';
                 if (!isset($tag->pict) || $tag->pict != '0') {
                     $tagToKeep .= '<img>';
                 }
                 $newintrotext = strip_tags($article->introtext, $tagToKeep);
                 $numChar = strlen($newintrotext);
                 if ($numChar > $wordwrap) {
                     $stop = strlen($newintrotext);
                     for ($i = $wordwrap; $i < $numChar; $i++) {
                         if ($newintrotext[$i] == " ") {
                             $stop = $i;
                             $forceReadMore = true;
                             break;
                         }
                     }
                     $article->introtext = substr($newintrotext, 0, $stop) . '...';
                 }
             }
         }
         if (empty($article->fulltext) or $tag->type != "text") {
             $contentText .= $article->introtext;
         }
         if ($tag->type != "intro" and !empty($article->fulltext)) {
             if ($tag->type != "text" && !empty($article->introtext) && !preg_match('#^<[div|p]#i', trim($article->fulltext))) {
                 $contentText .= '<br />';
             }
             $contentText .= $article->fulltext;
         }
         $contentText = $acypluginsHelper->wrapText($contentText, $tag);
         if (!empty($tag->clean)) {
             $contentText = strip_tags($contentText, '<p><br><span><ul><li><h1><h2><h3><h4><a>');
         }
         if (ACYMAILING_J16 && !empty($article->images) && !empty($tag->pict)) {
             $picthtml = '';
             $images = json_decode($article->images);
             $pictVar = $tag->type == 'intro' ? 'image_intro' : 'image_fulltext';
             $floatVar = $tag->type == 'intro' ? 'float_intro' : 'float_fulltext';
             if (!empty($images->{$pictVar})) {
                 if ($images->{$floatVar} != 'right') {
                     $images->{$floatVar} = 'left';
                 }
                 $style = 'float:' . $images->{$floatVar} . ';padding-' . ($images->{$floatVar} == 'right' ? 'left' : 'right') . ':10px;padding-bottom:10px;';
                 if (!empty($tag->link)) {
                     $picthtml .= '<a href="' . $link . '" style="text-decoration:none" >';
                 }
                 $alt = '';
                 $altVar = $pictVar . '_alt';
                 if (!empty($images->{$altVar})) {
                     $alt = $images->{$altVar};
                 }
                 $picthtml .= '<img style="' . $style . '" alt="' . $alt . '" border="0" src="' . JURI::root() . $images->{$pictVar} . '" />';
                 if (!empty($tag->link)) {
                     $picthtml .= '</a>';
                 }
                 $contentText = $picthtml . $contentText;
             }
         }
         $result .= $contentText;
         if (file_exists(JPATH_SITE . DS . 'plugins' . DS . 'attachments') && empty($tag->noattach)) {
             $db->setQuery('SELECT display_name, url, filename FROM #__attachments WHERE parent_id = ' . intval($tag->id));
             $attachments = $db->loadObjectList();
             if (!empty($attachments)) {
                 $result .= '<br/>' . JText::_('ATTACHED_FILES') . ' :';
                 foreach ($attachments as $oneAttachment) {
                     $result .= '<br/><a href="' . $oneAttachment->url . '">' . (empty($oneAttachment->display_name) ? $oneAttachment->filename : $oneAttachment->display_name) . '</a>';
                 }
             }
         }
         if ($tag->type == "intro") {
             if (empty($tag->noreadmore) and (!empty($article->fulltext) or $forceReadMore)) {
                 $readMoreText = empty($tag->readmore) ? $this->readmore : $tag->readmore;
                 $result .= '<a style="text-decoration:none;" target="_blank" href="' . $link . '"><span class="acymailing_readmore">' . $readMoreText . '</span></a>';
             }
         }
         if (!empty($tag->share)) {
             $links = array();
             $shareOpt = explode(',', $tag->share);
             foreach ($shareOpt as $socialNetwork) {
                 $knownNetwork = true;
                 $socialNetwork = strtolower(trim($socialNetwork));
                 if ($socialNetwork == 'facebook') {
                     $linkShare = 'http://www.facebook.com/sharer.php?u=' . urlencode($link) . '&t=' . urlencode($article->title);
                     $picSrc = file_exists(ACYMAILING_MEDIA . 'plugins' . DS . 'facebook.png') ? 'media/com_acymailing/plugins/facebook.png' : 'media/com_acymailing/images/facebookshare.png';
                     $altText = 'Facebook';
                 } elseif ($socialNetwork == 'twitter') {
                     $text = JText::sprintf('SHARE_TEXT', $link);
                     $linkShare = 'http://twitter.com/home?status=' . urlencode($text);
                     $picSrc = file_exists(ACYMAILING_MEDIA . 'plugins' . DS . 'twitter.png') ? 'media/com_acymailing/plugins/twitter.png' : 'media/com_acymailing/images/twittershare.png';
                     $altText = 'Twitter';
                 } elseif ($socialNetwork == 'linkedin') {
                     $linkShare = 'http://www.linkedin.com/shareArticle?mini=true&url=' . urlencode($link) . '&title=' . urlencode($article->title);
                     $picSrc = file_exists(ACYMAILING_MEDIA . 'plugins' . DS . 'linkedin.png') ? 'media/com_acymailing/plugins/linkedin.png' : 'media/com_acymailing/images/linkedin.png';
                     $altText = 'LinkedIn';
                 } elseif ($socialNetwork == 'hyves') {
                     $linkShare = 'http://www.hyves-share.nl/button/respect/?hc_hint=1&url=' . urlencode($link) . '&title=' . urlencode($article->title);
                     $picSrc = file_exists(ACYMAILING_MEDIA . 'plugins' . DS . 'hyves.png') ? 'media/com_acymailing/plugins/hyves.png' : 'media/com_acymailing/images/hyvesshare.png';
                     $altText = 'Hyves';
                 } elseif ($socialNetwork == 'google') {
                     $linkShare = 'https://plus.google.com/share?url=' . urlencode($link);
                     $picSrc = file_exists(ACYMAILING_MEDIA . 'plugins' . DS . 'google.png') ? 'media/com_acymailing/plugins/google.png' : 'media/com_acymailing/images/google_plusshare.png';
                     $altText = 'Google+';
                 } elseif ($socialNetwork == 'mailto') {
                     $linkShare = 'mailto:?subject=' . urlencode($article->title) . '&body=' . urlencode($article->title . ' (' . $link . ')');
                     $picSrc = file_exists(ACYMAILING_MEDIA . 'plugins' . DS . 'mailto.png') ? 'media/com_acymailing/plugins/mailto.png' : 'media/com_acymailing/images/mailto.png';
                     $altText = 'MailTo';
                 } else {
                     $knownNetwork = false;
                     acymailing_display('Network not found: ' . $socialNetwork . '. Availables networks are facebook, twitter, linkedin, hyves, google and mailto.', 'warning');
                 }
                 if ($knownNetwork) {
                     array_push($links, '<a target="_blank" href="' . $linkShare . '" title="' . JText::sprintf('SOCIAL_SHARE', $altText) . '"><img alt="' . $altText . '" src="' . $picSrc . '" /></a>');
                 }
             }
             $result .= '<br/>' . (!empty($tag->sharetxt) ? $tag->sharetxt . ' ' : '') . implode(' ', $links);
         }
         $result = '<table cellspacing="0" cellpadding="0" border="0" width="100%"><tr><td class="cat_' . @$article->catid . '" ><div class="acymailing_content" style="clear:both" >' . $result . '</div></td></tr></table>';
     }
     if (!empty($tag->theme)) {
         if (preg_match('#<img[^>]*>#Uis', $article->introtext . $article->fulltext, $pregresult)) {
             $cleanContent = strip_tags($result, '<p><br><span><ul><li><h1><h2><h3><h4><a>');
             $tdwidth = (empty($tag->maxwidth) ? $this->params->get('maxwidth', 150) : $tag->maxwidth) + 20;
             $result = '<div class="acymailing_content" style="clear:both"><table cellspacing="0" width="500" cellpadding="0" border="0" ><tr><td class="contentpicture" width="' . $tdwidth . '" valign="top" align="center"><a href="' . $link . '" target="_blank" style="border:0px;text-decoration:none">' . $pregresult[0] . '</a></td><td class="contenttext">' . $cleanContent . '</td></tr></table></div>';
         }
     }
     if (!empty($tag->cattitle) && $this->currentcatid != $article->catid) {
         $this->currentcatid = $article->catid;
         $result = '<h3 class="cattitle">' . $article->cattitle . '</h3>' . $result;
     }
     if (file_exists(ACYMAILING_MEDIA . 'plugins' . DS . 'tagcontent_html.php')) {
         ob_start();
         require ACYMAILING_MEDIA . 'plugins' . DS . 'tagcontent_html.php';
         $result = ob_get_clean();
     } elseif (file_exists(ACYMAILING_MEDIA . 'plugins' . DS . 'tagcontent.php')) {
         ob_start();
         require ACYMAILING_MEDIA . 'plugins' . DS . 'tagcontent.php';
         $result = ob_get_clean();
     }
     $result = $acypluginsHelper->removeJS($result);
     if (isset($tag->pict)) {
         $pictureHelper = acymailing_get('helper.acypict');
         $pictureHelper->maxHeight = empty($tag->maxheight) ? $this->params->get('maxheight', 150) : $tag->maxheight;
         $pictureHelper->maxWidth = empty($tag->maxwidth) ? $this->params->get('maxwidth', 150) : $tag->maxwidth;
         if ($tag->pict == '0') {
             $result = $pictureHelper->removePictures($result);
         } elseif ($tag->pict == 'resized') {
             if ($pictureHelper->available()) {
                 $result = $pictureHelper->resizePictures($result);
             } elseif ($app->isAdmin()) {
                 $app->enqueueMessage($pictureHelper->error, 'notice');
             }
         }
     }
     if (!empty($tag->maxchar) && strlen(strip_tags($result)) > $tag->maxchar) {
         $result = strip_tags($result);
         for ($i = $tag->maxchar; $i > 0; $i--) {
             if ($result[$i] == ' ') {
                 break;
             }
         }
         if (!empty($i)) {
             $result = substr($result, 0, $i) . @$tag->textafter;
         }
     }
     return $result;
 }
 function _generateToc(&$row, $index)
 {
     $display_method = $this->params->get('display_method', 1);
     $limitstart = JRequest::getInt('limitstart', 0);
     $result = new stdClass();
     if (0 == $index && $this->texts[$index] != "") {
         //$result->title	= $this->params->get('intro_text') != "" ? $this->params->get('intro_text') : $this->article->title ;
         $result->title = ' - ' . JText::_($this->params->get('custom_introtext', 'FLEXIBREAK_INTRO_TEXT')) . ' - ';
         $result->name = $result->id = 'start';
         $result->link = JRoute::_(FlexicontentHelperRoute::getItemRoute($row->slug, $row->catid, 0, $row) . '&showall=&limitstart=');
         $this->pagescount++;
     } else {
         if ($this->texts[0] == "") {
             $attrs = JUtility::parseAttributes($this->pages[$index][0]);
         } else {
             $attrs = JUtility::parseAttributes($this->pages[$index - 1][0]);
         }
         $result->title = isset($attrs['title']) ? $attrs['title'] : 'unknown';
         $result->name = isset($attrs['name']) ? $attrs['name'] : preg_replace('/[ \\t]+/u', '', $result->title);
         $result->link = JRoute::_(FlexicontentHelperRoute::getItemRoute($row->slug, $row->catid, 0, $row) . '&showall=&limitstart=' . $index);
         $result->id = $result->name ? $result->name : 'start';
     }
     $curr_index = $this->texts[0] == "" ? $index + 1 : $index;
     if (!isset($this->_text)) {
         $this->_text = '';
     }
     switch ($display_method) {
         case 0:
             $this->_text .= '<a id="' . $result->id . '_toc_page"></a>' . $this->texts[$curr_index];
             // add an anchor link for scrolling
             break;
         case 1:
             $this->_text .= '<div class="articlePage" id="' . $result->id . '"> ' . $this->texts[$curr_index] . '</div>';
             break;
         case 2:
             if ($limitstart == $curr_index) {
                 $this->_text .= $this->texts[$curr_index];
             }
             break;
     }
     return $result;
 }
 /**
  * Creates the page's display
  *
  * @since 1.0
  */
 function display($tpl = null)
 {
     // check for form layout
     if ($this->getLayout() == 'form' || in_array(JRequest::getVar('task'), array('add', 'edit'))) {
         // Important set layout to be form since various category view SEF links have this variable set
         $this->setLayout('form');
         $this->_displayForm($tpl);
         return;
     } else {
         $this->setLayout('item');
     }
     // Get Content Types with no category links in item view pathways, and for unroutable (non-linkable) categories
     global $globalnoroute, $globalnopath, $globalcats;
     if (!is_array($globalnopath)) {
         $globalnopath = array();
     }
     if (!is_array($globalnoroute)) {
         $globalnoroute = array();
     }
     //initialize variables
     $dispatcher = JDispatcher::getInstance();
     $app = JFactory::getApplication();
     $session = JFactory::getSession();
     $document = JFactory::getDocument();
     $menus = $app->getMenu();
     $menu = $menus->getActive();
     $uri = JFactory::getURI();
     $user = JFactory::getUser();
     $aid = JAccess::getAuthorisedViewLevels($user->id);
     $db = JFactory::getDBO();
     $nullDate = $db->getNullDate();
     // ******************************************************
     // Get item, model and create form (that loads item data)
     // ******************************************************
     // Get model
     $model = $this->getModel();
     $cid = $model->_cid ? $model->_cid : $model->get('catid');
     // Get current category id
     // Decide version to load
     $version = JRequest::getVar('version', 0, 'request', 'int');
     // Load specific item version (non-zero), 0 version: is unversioned data, -1 version: is latest version (=default for edit form)
     $preview = JRequest::getVar('preview', 0, 'request', 'int');
     // Preview versioned data FLAG ... if previewing and version is not set then ... we load version -1 (=latest version)
     $version = $preview && !$version ? -1 : $version;
     // Allow iLayout from HTTP request, this will be checked during loading item parameters
     $model->setItemLayout('__request__');
     // Try to load existing item, an 404 error will be raised if item is not found. Also value 2 for check_view_access
     // indicates to raise 404 error for ZERO primary key too, instead of creating and returning a new item object
     $start_microtime = microtime(true);
     $item = $model->getItem(null, $check_view_access = 2, $no_cache = $version || $preview, $force_version = $version || $preview ? $version : 0);
     // ZERO means unversioned data
     $_run_time = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
     // Get item parameters as VIEW's parameters (item parameters are merged parameters in order: component/category/layout/type/item/menu/access)
     $params =& $item->parameters;
     // Get item 's layout as this may have been altered
     $ilayout = $params->get('ilayout');
     $print_logging_info = $params->get('print_logging_info');
     if ($print_logging_info) {
         global $fc_run_times;
     }
     if ($print_logging_info) {
         $fc_run_times['get_item_data'] = $_run_time;
     }
     // ********************************
     // Load needed JS libs & CSS styles
     // ********************************
     //add css file
     if (!$params->get('disablecss', '')) {
         $document->addStyleSheet($this->baseurl . '/components/com_flexicontent/assets/css/flexicontent.css');
         $document->addCustomTag('<!--[if IE]><style type="text/css">.floattext {zoom:1;}</style><![endif]-->');
     }
     //allow css override
     if (file_exists(JPATH_SITE . DS . 'templates' . DS . $app->getTemplate() . DS . 'css' . DS . 'flexicontent.css')) {
         $document->addStyleSheet($this->baseurl . '/templates/' . $app->getTemplate() . '/css/flexicontent.css');
     }
     //special to hide the joomfish language selector on item views
     if ($params->get('disable_lang_select', 0)) {
         $css = '#jflanguageselection { visibility:hidden; }';
         $document->addStyleDeclaration($css);
     }
     // *************************************************************
     // Get cached template data, loading any template language files
     // *************************************************************
     $themes = flexicontent_tmpl::getTemplates($lang_files = array($ilayout));
     // *****************
     // Get Item's Fields
     // *****************
     $_items = array(&$item);
     FlexicontentFields::getFields($_items, FLEXI_ITEMVIEW, $params, $aid);
     $fields = $item->fields;
     // ****************************************
     // Get category titles needed by pathway,
     // this will allow Falang to translate them
     // ****************************************
     $catshelper = new flexicontent_cats($cid);
     $parents = $catshelper->getParentlist($all_cols = false);
     //echo "<pre>".print_r($parents,true)."</pre>";
     /*$parents = array();
     		if ( $cid && isset($globalcats[$cid]->ancestorsarray) ) {
     			$parent_ids = $globalcats[$cid]->ancestorsarray;
     			foreach ($parent_ids as $parent_id) $parents[] = $globalcats[$parent_id];
     		}*/
     // **********************************************************
     // Calculate a (browser window) page title and a page heading
     // **********************************************************
     // Verify menu item points to current FLEXIcontent object
     if ($menu) {
         $view_ok = FLEXI_ITEMVIEW == @$menu->query['view'] || 'article' == @$menu->query['view'];
         $cid_ok = JRequest::getInt('cid') == (int) @$menu->query['cid'];
         $id_ok = JRequest::getInt('id') == (int) @$menu->query['id'];
         $menu_matches = $view_ok && $id_ok;
         //$menu_params = $menu->params;  // Get active menu item parameters
     } else {
         $menu_matches = false;
     }
     // MENU ITEM matched, use its page heading (but use menu title if the former is not set)
     if ($menu_matches) {
         $default_heading = FLEXI_J16GE ? $menu->title : $menu->name;
         // Cross set (show_) page_heading / page_title for compatibility of J2.5+ with J1.5 template (and for J1.5 with J2.5 template)
         $params->def('page_heading', $params->get('page_title', $default_heading));
         $params->def('page_title', $params->get('page_heading', $default_heading));
         $params->def('show_page_heading', $params->get('show_page_title', 0));
         $params->def('show_page_title', $params->get('show_page_heading', 0));
     } else {
         // Clear some menu parameters
         //$params->set('pageclass_sfx',	'');  // CSS class SUFFIX is behavior, so do not clear it ?
         // Calculate default page heading (=called page title in J1.5), which in turn will be document title below !! ...
         $default_heading = $item->title;
         // Decide to show page heading (=J1.5 page title), there is no need for this in item view
         $show_default_heading = 0;
         // Set both (show_) page_heading / page_title for compatibility of J2.5+ with J1.5 template (and for J1.5 with J2.5 template)
         $params->set('page_title', $default_heading);
         $params->set('page_heading', $default_heading);
         $params->set('show_page_heading', $show_default_heading);
         $params->set('show_page_title', $show_default_heading);
     }
     // Prevent showing the page heading if (a) IT IS same as item title and (b) item title is already configured to be shown
     if ($params->get('show_title', 1)) {
         if ($params->get('page_heading') == $item->title) {
             $params->set('show_page_heading', 0);
         }
         if ($params->get('page_title') == $item->title) {
             $params->set('show_page_title', 0);
         }
     }
     // ************************************************************
     // Create the document title, by from page title and other data
     // ************************************************************
     // Use the page heading as document title, (already calculated above via 'appropriate' logic ...)
     // or the overriden custom <title> ... set via parameter
     $doc_title = !$params->get('override_title', 0) ? $params->get('page_title') : $params->get('custom_ititle', $item->title);
     // Check and prepend category title
     if ($params->get('addcat_title', 1) && count($parents)) {
         $parentcat = end($parents);
         if (isset($item->category_title)) {
             if ($params->get('addcat_title', 1) == 1) {
                 // On Left
                 $doc_title = JText::sprintf('FLEXI_PAGETITLE_SEPARATOR', $item->category_title, $doc_title);
             } else {
                 // On Right
                 $doc_title = JText::sprintf('FLEXI_PAGETITLE_SEPARATOR', $doc_title, $item->category_title);
             }
         }
     }
     // Check and prepend or append site name to page title
     if ($doc_title != $app->getCfg('sitename')) {
         if ($app->getCfg('sitename_pagetitles', 0) == 1) {
             $doc_title = JText::sprintf('JPAGETITLE', $app->getCfg('sitename'), $doc_title);
         } elseif ($app->getCfg('sitename_pagetitles', 0) == 2) {
             $doc_title = JText::sprintf('JPAGETITLE', $doc_title, $app->getCfg('sitename'));
         }
     }
     // Finally, set document title
     $document->setTitle($doc_title);
     // ************************
     // Set document's META tags
     // ************************
     // Workaround for Joomla not setting the default value for 'robots', so component must do it
     $app_params = $app->getParams();
     if ($_mp = $app_params->get('robots')) {
         $document->setMetadata('robots', $_mp);
     }
     // Set item's META data: desc, keyword, title, author
     if ($item->metadesc) {
         $document->setDescription($item->metadesc);
     }
     if ($item->metakey) {
         $document->setMetadata('keywords', $item->metakey);
     }
     // ?? Deprecated <title> tag is used instead by search engines
     if ($app->getCfg('MetaTitle') == '1') {
         $document->setMetaData('title', $item->title);
     }
     if ($app->getCfg('MetaAuthor') == '1') {
         $document->setMetaData('author', $item->author);
     }
     // Set remaining META keys
     $mdata = $item->metadata->toArray();
     foreach ($mdata as $k => $v) {
         if ($v) {
             $document->setMetadata($k, $v);
         }
     }
     // Overwrite with menu META data if menu matched
     if ($menu_matches) {
         if ($_mp = $menu->params->get('menu-meta_description')) {
             $document->setDescription($_mp);
         }
         if ($_mp = $menu->params->get('menu-meta_keywords')) {
             $document->setMetadata('keywords', $_mp);
         }
         if ($_mp = $menu->params->get('robots')) {
             $document->setMetadata('robots', $_mp);
         }
         if ($_mp = $menu->params->get('secure')) {
             $document->setMetadata('secure', $_mp);
         }
     }
     // ****************************************************************
     // Make sure Joomla SEF plugin has inserted a correct REL canonical
     // or that it has not insert any REL if current URL is sufficient
     // ****************************************************************
     if ($params->get('add_canonical')) {
         // Get canonical URL that SEF plugin adds, also $domain passed by reference, to get the domain configured in SEF plugin (multi-domain website)
         $domain = null;
         $defaultCanonical = flexicontent_html::getDefaultCanonical($domain);
         $domain = $domain ? $domain : $uri->toString(array('scheme', 'host', 'port'));
         // Create desired REL canonical URL
         $ucanonical = $domain . JRoute::_(FlexicontentHelperRoute::getItemRoute($item->slug, $globalcats[$item->maincatid]->slug, 0, $item));
         // $item->categoryslug
         // Check if SEF plugin inserted a different REL canonical
         if ($defaultCanonical != $ucanonical) {
             // Add REL canonical only if different than current URL
             $head_obj = $document->addHeadLink(htmlspecialchars($ucanonical), 'canonical', 'rel', '');
             if ($uri->toString() == $ucanonical) {
                 unset($head_obj->_links[htmlspecialchars($ucanonical)]);
             }
             // Remove canonical inserted by SEF plugin
             unset($head_obj->_links[htmlspecialchars($defaultCanonical)]);
         }
     }
     // *************************
     // increment the hit counter
     // *************************
     // MOVED to flexisystem plugin due to ...
     /*if (FLEXIUtilities::count_new_hit($item->id) ) {
     			$model->hit();
     		}*/
     // Load template css/js and set template data variable
     $tmplvar = $themes->items->{$ilayout}->tmplvar;
     if ($ilayout) {
         // Add the templates css files if availables
         if (isset($themes->items->{$ilayout}->css)) {
             foreach ($themes->items->{$ilayout}->css as $css) {
                 $document->addStyleSheet($this->baseurl . '/' . $css);
             }
         }
         // Add the templates js files if availables
         if (isset($themes->items->{$ilayout}->js)) {
             foreach ($themes->items->{$ilayout}->js as $js) {
                 $document->addScript($this->baseurl . '/' . $js);
             }
         }
         // Set the template var
         $tmpl = $themes->items->{$ilayout}->tmplvar;
     } else {
         $tmpl = '.items.default';
     }
     // Just put item's text (description field) inside property 'text' in case the events modify the given text,
     $item->text = isset($item->fields['text']->display) ? $item->fields['text']->display : '';
     // Maybe here not to import all plugins but just those for description field ???
     // Anyway these events are usually not very time consuming, so lets trigger all of them ???
     JPluginHelper::importPlugin('content');
     // Suppress some plugins from triggering for compatibility reasons, e.g.
     // (a) jcomments, jom_comment_bot plugins, because we will get comments HTML manually inside the template files
     $suppress_arr = array('jcomments', 'jom_comment_bot');
     FLEXIUtilities::suppressPlugins($suppress_arr, 'suppress');
     // Do some compatibility steps, Set the view and option to 'article' and 'com_content'
     JRequest::setVar('view', 'article');
     JRequest::setVar('option', 'com_content');
     JRequest::setVar("isflexicontent", "yes");
     $limitstart = JRequest::getVar('limitstart', 0, '', 'int');
     // These events return text that could be displayed at appropriate positions by our templates
     $item->event = new stdClass();
     $results = $dispatcher->trigger('onContentAfterTitle', array('com_content.article', &$item, &$params, $limitstart));
     $item->event->afterDisplayTitle = trim(implode("\n", $results));
     $results = $dispatcher->trigger('onContentBeforeDisplay', array('com_content.article', &$item, &$params, $limitstart));
     $item->event->beforeDisplayContent = trim(implode("\n", $results));
     $results = $dispatcher->trigger('onContentAfterDisplay', array('com_content.article', &$item, &$params, $limitstart));
     $item->event->afterDisplayContent = trim(implode("\n", $results));
     // Reverse the compatibility steps, set the view and option back to 'items' and 'com_flexicontent'
     JRequest::setVar('view', FLEXI_ITEMVIEW);
     JRequest::setVar('option', 'com_flexicontent');
     // Restore suppressed plugins
     FLEXIUtilities::suppressPlugins($suppress_arr, 'restore');
     // Put text back into the description field, THESE events SHOULD NOT modify the item text, but some plugins may do it anyway... , so we assign text back for compatibility
     if (!empty($item->positions)) {
         foreach ($item->positions as $pos_fields) {
             foreach ($pos_fields as $pos_field) {
                 if ($pos_field->name !== 'text') {
                     continue;
                 }
                 $pos_field->display =& $item->text;
             }
         }
     }
     $item->fields['text']->display =& $item->text;
     // (TOC) TABLE OF Contents has been created inside description field (named 'text') by
     // the pagination plugin, this should be assigned to item as a property with same name
     if (isset($item->fields['text']->toc)) {
         $item->toc =& $item->fields['text']->toc;
     }
     // ********************************************************************************************
     // Create pathway, if automatic pathways is enabled, then path will be cleared before populated
     // ********************************************************************************************
     $pathway = $app->getPathWay();
     // Clear pathway, if automatic pathways are enabled
     if ($params->get('automatic_pathways', 0)) {
         $pathway_arr = $pathway->getPathway();
         $pathway->setPathway(array());
         //$pathway->set('_count', 0);  // not needed ??
         $item_depth = 0;
         // menu item depth is now irrelevant ???, ignore it
     } else {
         $item_depth = $params->get('item_depth', 0);
     }
     // Respect menu item depth, defined in menu item
     $p = $item_depth;
     while ($p < count($parents)) {
         // For some Content Types the pathway should not be populated with category links
         if (in_array($item->type_id, $globalnopath)) {
             break;
         }
         // Do not add to pathway unroutable categories
         if (in_array($parents[$p]->id, $globalnoroute)) {
             $p++;
             continue;
         }
         // Add current parent category
         $pathway->addItem($this->escape($parents[$p]->title), JRoute::_(FlexicontentHelperRoute::getCategoryRoute($parents[$p]->slug)));
         $p++;
     }
     if ($params->get('add_item_pathway', 1)) {
         $pathway->addItem($this->escape($item->title), JRoute::_(FlexicontentHelperRoute::getItemRoute($item->slug, $item->categoryslug, 0, $item)));
     }
     // **********************************************************************
     // Print link ... must include layout and current filtering url vars, etc
     // **********************************************************************
     $curr_url = $_SERVER['REQUEST_URI'];
     $print_link = $curr_url . (strstr($curr_url, '?') ? '&amp;' : '?') . 'pop=1&amp;tmpl=component&amp;print=1';
     //$print_link = JRoute::_('index.php?view='.FLEXI_ITEMVIEW.'&cid='.$item->categoryslug.'&id='.$item->slug.'&pop=1&tmpl=component&print=1');
     $pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx'));
     $this->assignRef('item', $item);
     $this->assignRef('user', $user);
     $this->assignRef('params', $params);
     $this->assignRef('print_link', $print_link);
     $this->assignRef('pageclass_sfx', $pageclass_sfx);
     $this->assignRef('parentcat', $parentcat);
     $this->assignRef('fields', $item->fields);
     $this->assignRef('tmpl', $tmpl);
     /*
      * Set template paths : this procedure is issued from K2 component
      *
      * "K2" Component by JoomlaWorks for Joomla! 1.5.x - Version 2.1
      * Copyright (c) 2006 - 2009 JoomlaWorks Ltd. All rights reserved.
      * Released under the GNU/GPL license: http://www.gnu.org/copyleft/gpl.html
      * More info at http://www.joomlaworks.gr and http://k2.joomlaworks.gr
      * Designed and developed by the JoomlaWorks team
      */
     $this->addTemplatePath(JPATH_COMPONENT . DS . 'templates');
     $this->addTemplatePath(JPATH_SITE . DS . 'templates' . DS . $app->getTemplate() . DS . 'html' . DS . 'com_flexicontent' . DS . 'templates');
     $this->addTemplatePath(JPATH_COMPONENT . DS . 'templates' . DS . 'default');
     $this->addTemplatePath(JPATH_SITE . DS . 'templates' . DS . $app->getTemplate() . DS . 'html' . DS . 'com_flexicontent' . DS . 'templates' . DS . 'default');
     if ($ilayout) {
         $this->addTemplatePath(JPATH_COMPONENT . DS . 'templates' . DS . $ilayout);
         $this->addTemplatePath(JPATH_SITE . DS . 'templates' . DS . $app->getTemplate() . DS . 'html' . DS . 'com_flexicontent' . DS . 'templates' . DS . $ilayout);
     }
     if ($print_logging_info) {
         $start_microtime = microtime(true);
     }
     parent::display($tpl);
     if ($print_logging_info) {
         $fc_run_times['template_render'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
     }
 }
 private function _replaceContent(&$tag)
 {
     $oldFormat = empty($tag->format);
     if (!ACYMAILING_J16) {
         $query = 'SELECT a.*,b.name as authorname, c.alias as catalias, c.title as cattitle, c.image AS catpict, s.alias as secalias, s.title as sectitle FROM ' . acymailing_table('content', false) . ' as a ';
         $query .= 'LEFT JOIN ' . acymailing_table('users', false) . ' as b ON a.created_by = b.id ';
         $query .= ' LEFT JOIN ' . acymailing_table('categories', false) . ' AS c ON c.id = a.catid ';
         $query .= ' LEFT JOIN ' . acymailing_table('sections', false) . ' AS s ON s.id = a.sectionid ';
         $query .= 'WHERE a.id = ' . $tag->id . ' LIMIT 1';
     } else {
         $query = 'SELECT a.*,b.name as authorname, c.alias as catalias, c.title as cattitle, c.params AS catparams FROM ' . acymailing_table('content', false) . ' as a ';
         $query .= 'LEFT JOIN ' . acymailing_table('users', false) . ' as b ON a.created_by = b.id ';
         $query .= ' LEFT JOIN ' . acymailing_table('categories', false) . ' AS c ON c.id = a.catid ';
         $query .= 'WHERE a.id = ' . $tag->id . ' LIMIT 1';
     }
     $this->db->setQuery($query);
     $article = $this->db->loadObject();
     if (empty($article)) {
         $app = JFactory::getApplication();
         if ($app->isAdmin()) {
             $app->enqueueMessage('The article "' . $tag->id . '" could not be loaded', 'notice');
         }
         return '';
     }
     if (empty($tag->lang) && !empty($this->newslanguage) && !empty($this->newslanguage->lang_code)) {
         $tag->lang = $this->newslanguage->lang_code . ',' . $this->newslanguage->lang_id;
     }
     $this->acypluginsHelper->translateItem($article, $tag, 'content');
     $varFields = array();
     foreach ($article as $fieldName => $oneField) {
         $varFields['{' . $fieldName . '}'] = $oneField;
     }
     $this->acypluginsHelper->cleanHtml($article->introtext);
     $this->acypluginsHelper->cleanHtml($article->fulltext);
     if ($this->params->get('integration') == 'jreviews' && !empty($article->images)) {
         $firstpict = explode('|', trim(reset(explode("\n", $article->images))) . '|||||||');
         if (!empty($firstpict[0])) {
             $picturePath = file_exists(ACYMAILING_ROOT . 'images' . DS . 'stories' . DS . str_replace('/', DS, $firstpict[0])) ? ACYMAILING_LIVE . 'images/stories/' . $firstpict[0] : ACYMAILING_LIVE . 'images/' . $firstpict[0];
             $myPict = '<img src="' . $picturePath . '" alt="" hspace="5" style="margin:5px" align="left" border="' . intval($firstpict[5]) . '" />';
             $article->introtext = $myPict . $article->introtext;
         }
     }
     $completeId = $article->id;
     $completeCat = $article->catid;
     if (!empty($article->alias)) {
         $completeId .= ':' . $article->alias;
     }
     if (!empty($article->catalias)) {
         $completeCat .= ':' . $article->catalias;
     }
     if (empty($tag->itemid)) {
         if (!ACYMAILING_J16) {
             $completeSec = $article->sectionid;
             if (!empty($article->secalias)) {
                 $completeSec .= ':' . $article->secalias;
             }
             if ($this->params->get('integration') == 'flexicontent' && class_exists('FlexicontentHelperRoute')) {
                 $link = FlexicontentHelperRoute::getItemRoute($completeId, $completeCat, $completeSec);
             } else {
                 $link = ContentHelperRoute::getArticleRoute($completeId, $completeCat, $completeSec);
             }
         } else {
             if ($this->params->get('integration') == 'flexicontent' && class_exists('FlexicontentHelperRoute')) {
                 $link = FlexicontentHelperRoute::getItemRoute($completeId, $completeCat);
             } else {
                 $link = ContentHelperRoute::getArticleRoute($completeId, $completeCat);
             }
         }
     } else {
         $link = 'index.php?option=com_content&view=article&id=' . $completeId . '&catid=' . $completeCat;
     }
     if ($this->params->get('integration') == 'flexicontent' && !class_exists('FlexicontentHelperRoute')) {
         $link = 'index.php?option=com_flexicontent&view=items&id=' . $completeId;
     } elseif ($this->params->get('integration') == 'jaggyblog') {
         $link = 'index.php?option=com_jaggyblog&task=viewpost&id=' . $completeId;
     }
     if (!empty($tag->itemid)) {
         $link .= '&Itemid=' . $tag->itemid;
     }
     if (!empty($tag->lang)) {
         $link .= (strpos($link, '?') ? '&' : '?') . 'lang=' . substr($tag->lang, 0, strpos($tag->lang, ','));
     }
     if (!empty($tag->autologin)) {
         $link .= (strpos($link, '?') ? '&' : '?') . 'user={usertag:username|urlencode}&passw={usertag:password|urlencode}';
     }
     if (empty($tag->lang) && !empty($article->language) && $article->language != '*') {
         if (!isset($this->langcodes[$article->language])) {
             $this->db->setQuery('SELECT sef FROM #__languages WHERE lang_code = ' . $this->db->Quote($article->language) . ' ORDER BY `published` DESC LIMIT 1');
             $this->langcodes[$article->language] = $this->db->loadResult();
             if (empty($this->langcodes[$article->language])) {
                 $this->langcodes[$article->language] = $article->language;
             }
         }
         $link .= (strpos($link, '?') ? '&' : '?') . 'lang=' . $this->langcodes[$article->language];
     }
     $link = acymailing_frontendLink($link);
     $varFields['{link}'] = $link;
     $afterTitle = '';
     $afterArticle = '';
     $contentText = '';
     $pictPath = '';
     if (!empty($tag->author)) {
         $authorName = empty($article->created_by_alias) ? $article->authorname : $article->created_by_alias;
         if ($tag->type == 'title') {
             $afterTitle .= '<br />';
         }
         $afterTitle .= '<span class="authorname">' . $authorName . '</span><br />';
     }
     $dateFormat = empty($tag->dateformat) ? JText::_('DATE_FORMAT_LC2') : $tag->dateformat;
     if (!empty($tag->created)) {
         if ($tag->type == 'title') {
             $afterTitle .= '<br />';
         }
         $varFields['{createddate}'] = JHTML::_('date', $article->created, $dateFormat);
         $afterTitle .= '<span class="createddate">' . $varFields['{createddate}'] . '</span><br />';
     }
     if (!empty($tag->modified)) {
         if ($tag->type == 'title') {
             $afterTitle .= '<br />';
         }
         $varFields['{modifieddate}'] = JHTML::_('date', $article->modified, $dateFormat);
         $afterTitle .= '<span class="modifieddate">' . $varFields['{modifieddate}'] . '</span><br />';
     }
     if (!isset($tag->pict) && $tag->type != 'title') {
         if ($this->params->get('removepictures', 'never') == 'always' || $this->params->get('removepictures', 'never') == 'intro' && $tag->type == "intro") {
             $tag->pict = 0;
         } else {
             $tag->pict = 1;
         }
     }
     if (strpos($article->introtext, 'jseblod') !== false && file_exists(ACYMAILING_ROOT . 'plugins' . DS . 'content' . DS . 'cckjseblod.php')) {
         global $mainframe;
         include_once ACYMAILING_ROOT . 'plugins' . DS . 'content' . DS . 'cckjseblod.php';
         if (function_exists('plgContentCCKjSeblod')) {
             $paramsContent = JComponentHelper::getParams('com_content');
             $article->text = $article->introtext . $article->fulltext;
             plgContentCCKjSeblod($article, $paramsContent);
             $article->introtext = $article->text;
             $article->fulltext = '';
         }
     }
     if ($tag->type != "title") {
         if ($tag->type == "intro") {
             $forceReadMore = false;
             $mytag = new stdClass();
             $mytag->wrap = $this->params->get('wordwrap', 0);
             if (empty($article->fulltext)) {
                 $article->introtext = $this->acypluginsHelper->wrapText($article->introtext, $mytag);
                 if (!empty($this->acypluginsHelper->wraped)) {
                     $forceReadMore = true;
                 }
             }
         }
         if (empty($article->fulltext) || $tag->type != "text") {
             $contentText .= $article->introtext;
         }
         if ($tag->type != "intro" && !empty($article->fulltext)) {
             if ($tag->type != "text" && !empty($article->introtext) && !preg_match('#^<[div|p]#i', trim($article->fulltext))) {
                 $contentText .= '<br />';
             }
             $contentText .= $article->fulltext;
         }
         $contentText = $this->acypluginsHelper->wrapText($contentText, $tag);
         if (!empty($this->acypluginsHelper->wraped)) {
             $forceReadMore = true;
         }
         if (!empty($tag->clean)) {
             $contentText = strip_tags($contentText, '<p><br><span><ul><li><h1><h2><h3><h4><a>');
         }
         if (ACYMAILING_J16 && !empty($article->images) && !empty($tag->pict)) {
             $picthtml = '';
             $images = json_decode($article->images);
             $pictVar = $tag->type == 'intro' ? 'image_intro' : 'image_fulltext';
             $floatVar = $tag->type == 'intro' ? 'float_intro' : 'float_fulltext';
             if (!empty($images->{$pictVar})) {
                 if ($images->{$floatVar} != 'right') {
                     if (empty($tag->format)) {
                         $tag->format = 'TOP_LEFT';
                     }
                     $images->{$floatVar} = 'left';
                 } elseif (empty($tag->format)) {
                     $tag->format = 'TOP_RIGHT';
                 }
                 $style = 'float:' . $images->{$floatVar} . ';padding-' . ($images->{$floatVar} == 'right' ? 'left' : 'right') . ':10px;padding-bottom:10px;';
                 if (!empty($tag->link) && empty($tag->nopictlink)) {
                     $picthtml .= '<a href="' . $link . '" style="text-decoration:none" >';
                 }
                 $alt = '';
                 $altVar = $pictVar . '_alt';
                 if (!empty($images->{$altVar})) {
                     $alt = $images->{$altVar};
                 }
                 $picthtml .= '<img' . (empty($tag->nopictstyle) ? ' style="' . $style . '"' : '') . ' alt="' . $alt . '" border="0" src="' . JURI::root() . $images->{$pictVar} . '" />';
                 $pictPath = JURI::root() . $images->{$pictVar};
                 if (!empty($tag->link) && empty($tag->nopictlink)) {
                     $picthtml .= '</a>';
                 }
                 $varFields['{picthtml}'] = $picthtml;
             }
         }
         $contentText = preg_replace('/^\\s*(<img[^>]*>)\\s*(?:<br[^>]*>\\s*)*/i', '$1', $contentText);
         if (file_exists(JPATH_SITE . DS . 'plugins' . DS . 'attachments') && empty($tag->noattach)) {
             try {
                 $query = 'SELECT display_name, url, filename ' . 'FROM #__attachments ' . 'WHERE (parent_entity = "article" ' . 'AND parent_id = ' . intval($tag->id) . ')';
                 if (ACYMAILING_J16) {
                     $query .= ' OR (parent_entity = "category" ' . 'AND parent_id = ' . intval($article->catid) . ')';
                 }
                 $this->db->setQuery($query);
                 $attachments = $this->db->loadObjectList();
             } catch (Exception $e) {
                 $attachments = array();
             }
             if (!empty($attachments)) {
                 $afterArticle .= '<br />' . JText::_('ATTACHED_FILES') . ' :';
                 foreach ($attachments as $oneAttachment) {
                     $afterArticle .= '<br /><a href="' . $oneAttachment->url . '">' . (empty($oneAttachment->display_name) ? $oneAttachment->filename : $oneAttachment->display_name) . '</a>';
                 }
             }
         }
         $readMoreText = empty($tag->readmore) ? $this->readmore : $tag->readmore;
         $varFields['{readmore}'] = '<a style="text-decoration:none;" target="_blank" href="' . $link . '"><span class="acymailing_readmore">' . $readMoreText . '</span></a>';
         if ($tag->type == "intro" && empty($tag->noreadmore) && (!empty($article->fulltext) || $forceReadMore)) {
             $contentText .= ' ' . $varFields['{readmore}'];
         }
         if (!empty($tag->share)) {
             $links = array();
             $shareOpt = explode(',', $tag->share);
             foreach ($shareOpt as $socialNetwork) {
                 $knownNetwork = true;
                 $socialNetwork = strtolower(trim($socialNetwork));
                 if ($socialNetwork == 'facebook') {
                     $linkShare = 'http://www.facebook.com/sharer.php?u=' . urlencode($link) . '&t=' . urlencode($article->title);
                     $picSrc = file_exists(ACYMAILING_MEDIA . 'plugins' . DS . 'facebook.png') ? 'media/com_acymailing/plugins/facebook.png' : 'media/com_acymailing/images/facebookshare.png';
                     $altText = 'Facebook';
                 } elseif ($socialNetwork == 'twitter') {
                     $text = JText::sprintf('SHARE_TEXT', $link);
                     $linkShare = 'http://twitter.com/home?status=' . urlencode($text);
                     $picSrc = file_exists(ACYMAILING_MEDIA . 'plugins' . DS . 'twitter.png') ? 'media/com_acymailing/plugins/twitter.png' : 'media/com_acymailing/images/twittershare.png';
                     $altText = 'Twitter';
                 } elseif ($socialNetwork == 'linkedin') {
                     $linkShare = 'http://www.linkedin.com/shareArticle?mini=true&url=' . urlencode($link) . '&title=' . urlencode($article->title);
                     $picSrc = file_exists(ACYMAILING_MEDIA . 'plugins' . DS . 'linkedin.png') ? 'media/com_acymailing/plugins/linkedin.png' : 'media/com_acymailing/images/linkedin.png';
                     $altText = 'LinkedIn';
                 } elseif ($socialNetwork == 'hyves') {
                     $linkShare = 'http://www.hyves-share.nl/button/respect/?hc_hint=1&url=' . urlencode($link) . '&title=' . urlencode($article->title);
                     $picSrc = file_exists(ACYMAILING_MEDIA . 'plugins' . DS . 'hyves.png') ? 'media/com_acymailing/plugins/hyves.png' : 'media/com_acymailing/images/hyvesshare.png';
                     $altText = 'Hyves';
                 } elseif ($socialNetwork == 'google') {
                     $linkShare = 'https://plus.google.com/share?url=' . urlencode($link);
                     $picSrc = file_exists(ACYMAILING_MEDIA . 'plugins' . DS . 'google.png') ? 'media/com_acymailing/plugins/google.png' : 'media/com_acymailing/images/google_plusshare.png';
                     $altText = 'Google+';
                 } elseif ($socialNetwork == 'mailto') {
                     $linkShare = 'mailto:?subject=' . urlencode($article->title) . '&body=' . urlencode($article->title . ' (' . $link . ')');
                     $picSrc = file_exists(ACYMAILING_MEDIA . 'plugins' . DS . 'mailto.png') ? 'media/com_acymailing/plugins/mailto.png' : 'media/com_acymailing/images/mailto.png';
                     $altText = 'MailTo';
                 } else {
                     $knownNetwork = false;
                     acymailing_display('Network not found: ' . $socialNetwork . '. Availables networks are facebook, twitter, linkedin, hyves, google and mailto.', 'warning');
                 }
                 if ($knownNetwork) {
                     array_push($links, '<a target="_blank" href="' . $linkShare . '" title="' . JText::sprintf('SOCIAL_SHARE', $altText) . '"><img alt="' . $altText . '" src="' . $picSrc . '" /></a>');
                 }
             }
             $afterArticle .= '<br />' . (!empty($tag->sharetxt) ? $tag->sharetxt . ' ' : '') . implode(' ', $links);
         }
     }
     if (!empty($tag->jtags) && version_compare(JVERSION, '3.1.0', '>=')) {
         $this->db->setQuery('SELECT t.id, t.alias, t.title FROM #__tags AS t JOIN #__contentitem_tag_map AS m ON t.id = m.tag_id WHERE t.published = 1 AND m.type_alias = "com_content.article" AND m.content_item_id = ' . intval($tag->id));
         $tags = $this->db->loadObjectList();
         if (!empty($tags)) {
             $afterArticle .= '<br />';
             foreach ($tags as $oneTag) {
                 $afterArticle .= ' <a href="index.php?option=com_tags&view=tag&id=' . $oneTag->id . '-' . $oneTag->alias . '">' . $oneTag->title . '</a> ';
             }
         }
     }
     $format = new stdClass();
     $format->tag = $tag;
     $format->title = empty($tag->notitle) ? $article->title : '';
     $format->afterTitle = $afterTitle;
     $format->afterArticle = $afterArticle;
     $format->imagePath = $pictPath;
     $format->description = $contentText;
     $format->link = empty($tag->link) ? '' : $link;
     $format->cols = 2;
     $result = $this->acypluginsHelper->getStandardDisplay($format);
     if (!empty($tag->theme)) {
         if (preg_match('#<img[^>]*>#Uis', $article->introtext . $article->fulltext, $pregresult)) {
             $cleanContent = strip_tags($result, '<p><br><span><ul><li><h1><h2><h3><h4><a>');
             $tdwidth = (empty($tag->maxwidth) ? $this->params->get('maxwidth', 150) : $tag->maxwidth) + 20;
             $result = '<table cellspacing="0" width="500" cellpadding="0" border="0" ><tr><td class="contentpicture" width="' . $tdwidth . '" valign="top" align="center"><a href="' . $link . '" target="_blank" style="border:0px;text-decoration:none">' . $pregresult[0] . '</a></td><td class="contenttext">' . $cleanContent . '</td></tr></table>';
         }
     }
     if ($tag->type != 'title') {
         $result = '<div class="acymailing_content">' . $result . '</div>';
     }
     if (!(empty($tag->cattitle) && empty($tag->catpict)) && (!strpos($article->catid, ',') && $this->currentcatid != $article->catid || strpos($article->catid, ',') && !in_array($this->currentcatid, explode(',', $article->catid)))) {
         if (strpos($article->catid, ',')) {
             $catids = explode(',', $article->catid);
             $this->currentcatid = $catids[0];
         } else {
             $this->currentcatid = $article->catid;
         }
         if (ACYMAILING_J16) {
             $params = json_decode($article->catparams);
             $article->catpict = $params->image;
         }
         $resultTitle = $article->cattitle;
         if (!empty($tag->catpict) && !empty($article->catpict)) {
             $style = '';
             if (!empty($tag->catmaxwidth)) {
                 $style .= 'max-width:' . intval($tag->catmaxwidth) . 'px;';
             }
             if (!empty($tag->catmaxheight)) {
                 $style .= 'max-height:' . intval($tag->catmaxheight) . 'px;';
             }
             $resultTitle = '<img' . (empty($style) ? '' : ' style="' . $style . '"') . ' alt="" src="' . $article->catpict . '" />';
             if (!empty($tag->cattitlelink)) {
                 $resultTitle = '<a href="index.php?option=com_content&view=category&id=' . $this->currentcatid . '">' . $resultTitle . '</a>';
             }
         } else {
             if (!empty($tag->cattitlelink)) {
                 $resultTitle = '<a href="index.php?option=com_content&view=category&id=' . $this->currentcatid . '">' . $resultTitle . '</a>';
             }
             $resultTitle = '<h3 class="cattitle">' . $resultTitle . '</h3>';
         }
         $result = $resultTitle . $result;
     }
     if ($oldFormat) {
         if (file_exists(ACYMAILING_MEDIA . 'plugins' . DS . 'tagcontent_html.php')) {
             ob_start();
             require ACYMAILING_MEDIA . 'plugins' . DS . 'tagcontent_html.php';
             $result = ob_get_clean();
         } elseif (file_exists(ACYMAILING_MEDIA . 'plugins' . DS . 'tagcontent.php')) {
             ob_start();
             require ACYMAILING_MEDIA . 'plugins' . DS . 'tagcontent.php';
             $result = ob_get_clean();
         }
     } elseif (!empty($tag->template) && file_exists(ACYMAILING_MEDIA . 'plugins' . DS . $tag->template)) {
         ob_start();
         require ACYMAILING_MEDIA . 'plugins' . DS . $tag->template;
         $result = ob_get_clean();
     }
     $result = str_replace(array_keys($varFields), $varFields, $result);
     $result = $this->acypluginsHelper->removeJS($result);
     $result = $this->acypluginsHelper->replaceVideos($result);
     $tag->maxheight = empty($tag->maxheight) ? $this->params->get('maxheight', 150) : $tag->maxheight;
     $tag->maxwidth = empty($tag->maxwidth) ? $this->params->get('maxwidth', 150) : $tag->maxwidth;
     $result = $this->acypluginsHelper->managePicts($tag, $result);
     if (!empty($tag->maxchar) && strlen(strip_tags($result)) > $tag->maxchar) {
         $result = strip_tags($result);
         for ($i = $tag->maxchar; $i > 0; $i--) {
             if ($result[$i] == ' ') {
                 break;
             }
         }
         if (!empty($i)) {
             $result = substr($result, 0, $i) . @$tag->textafter;
         }
     }
     return $result;
 }
                $w = '&amp;w=' . $this->params->get('intro_width', 200);
                $h = '&amp;h=' . $this->params->get('intro_height', 200);
                $aoe = '&amp;aoe=1';
                $q = '&amp;q=95';
                $zc = $this->params->get('intro_method') ? '&amp;zc=' . $this->params->get('intro_method') : '';
                $ext = pathinfo($src, PATHINFO_EXTENSION);
                $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
                $conf = $w . $h . $aoe . $q . $zc . $f;
                $base_url = !preg_match("#^http|^https|^ftp|^/#i", $src) ? JURI::base(true) . '/' : '';
                $thumb = JURI::base(true) . '/components/com_flexicontent/librairies/phpthumb/phpThumb.php?src=' . $base_url . $src . $conf;
            } else {
                // Do not resize image when (a) image src path not set or (b) using image field's already created thumbnails
                $thumb = $src;
            }
        }
        $link_url = $custom_link ? $custom_link : JRoute::_(FlexicontentHelperRoute::getItemRoute($item->slug, $item->categoryslug, 0, $item));
        // MICRODATA document type (itemtype) for each item
        // -- NOTE: category's microdata itemtype will override the microdata itemtype of the CONTENT TYPE
        $microdata_itemtype = $microdata_itemtype_cat ? $microdata_itemtype_cat : $item->params->get('microdata_itemtype');
        $microdata_itemtype_props = $microdata_itemtype ? 'itemscope itemtype="http://schema.org/' . $microdata_itemtype . '"' : '';
        ?>
		
		<?php 
        echo $intro_catblock ? '<li class="intro_catblock">' . ($intro_catblock_title && @$globalcats[$item->rel_catid] ? $globalcats[$item->rel_catid]->title : '') . '</li>' : '';
        ?>
		
		<li id="fc_bloglist_item_<?php 
        echo $i;
        ?>
" class="<?php 
        echo $fc_item_classes;
    /**
     * Creates the item page
     *
     * @since 1.0
     */
    function display($tpl = null)
    {
        // ********************************
        // Initialize variables, flags, etc
        // ********************************
        global $globalcats;
        $categories = $globalcats;
        $app = JFactory::getApplication();
        $dispatcher = JDispatcher::getInstance();
        $document = JFactory::getDocument();
        $config = JFactory::getConfig();
        $session = JFactory::getSession();
        $user = JFactory::getUser();
        $db = JFactory::getDBO();
        $option = JRequest::getVar('option');
        $nullDate = $db->getNullDate();
        // Get the COMPONENT only parameters
        // Get component parameters
        $params = new JRegistry();
        $cparams = JComponentHelper::getParams('com_flexicontent');
        $params->merge($cparams);
        $params = clone JComponentHelper::getParams('com_flexicontent');
        // Some flags
        $enable_translation_groups = flexicontent_db::useAssociations();
        //$params->get("enable_translation_groups");
        $print_logging_info = $params->get('print_logging_info');
        if ($print_logging_info) {
            global $fc_run_times;
        }
        // *****************
        // Load JS/CSS files
        // *****************
        // Add css to document
        $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontentbackend.css', FLEXI_VERSION);
        $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/j3x.css', FLEXI_VERSION);
        // Fields common CSS
        $document->addStyleSheetVersion(JURI::root(true) . '/components/com_flexicontent/assets/css/flexi_form_fields.css', FLEXI_VERSION);
        // Add JS frameworks
        flexicontent_html::loadFramework('select2');
        $prettycheckable_added = flexicontent_html::loadFramework('prettyCheckable');
        flexicontent_html::loadFramework('flexi-lib');
        // Add js function to overload the joomla submitform validation
        JHTML::_('behavior.formvalidation');
        // load default validation JS to make sure it is overriden
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/admin.js', FLEXI_VERSION);
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/validate.js', FLEXI_VERSION);
        // Add js function for custom code used by FLEXIcontent item form
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/itemscreen.js', FLEXI_VERSION);
        // ***********************
        // Get data from the model
        // ***********************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $model = $this->getModel();
        $item = $model->getItem();
        $form = $this->get('Form');
        if ($print_logging_info) {
            $fc_run_times['get_item_data'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // ***************************
        // Get Associated Translations
        // ***************************
        if ($enable_translation_groups) {
            $langAssocs = $this->get('LangAssocs');
        }
        $langs = FLEXIUtilities::getLanguages('code');
        // Get item id and new flag
        $cid = $model->getId();
        $isnew = !$cid;
        // Create and set a unique item id for plugins that needed it
        if ($cid) {
            $unique_tmp_itemid = $cid;
        } else {
            $unique_tmp_itemid = $app->getUserState('com_flexicontent.edit.item.unique_tmp_itemid');
            $unique_tmp_itemid = $unique_tmp_itemid ? $unique_tmp_itemid : date('_Y_m_d_h_i_s_', time()) . uniqid(true);
        }
        //print_r($unique_tmp_itemid);
        JRequest::setVar('unique_tmp_itemid', $unique_tmp_itemid);
        // Get number of subscribers
        $subscribers = $model->getSubscribersCount();
        // ******************
        // Version Panel data
        // ******************
        // Get / calculate some version related variables
        $versioncount = $model->getVersionCount();
        $versionsperpage = $params->get('versionsperpage', 10);
        $pagecount = (int) ceil($versioncount / $versionsperpage);
        // Data need by version panel: (a) current version page, (b) currently active version
        $current_page = 1;
        $k = 1;
        $allversions = $model->getVersionList();
        foreach ($allversions as $v) {
            if ($k > 1 && ($k - 1) % $versionsperpage == 0) {
                $current_page++;
            }
            if ($v->nr == $item->version) {
                break;
            }
            $k++;
        }
        // Finally fetch the version data for versions in current page
        $versions = $model->getVersionList(($current_page - 1) * $versionsperpage, $versionsperpage);
        // Create display of average rating
        $ratings = $model->getRatingDisplay();
        // *****************
        // Type related data
        // *****************
        // Get available types and the currently selected/requested type
        $types = $model->getTypeslist();
        $typesselected = $model->getTypesselected();
        // Get and merge type parameters
        $tparams = $this->get('Typeparams');
        $tparams = new JRegistry($tparams);
        $params->merge($tparams);
        // Apply type configuration if it type is set
        // Get user allowed permissions on the item ... to be used by the form rendering
        // Also hide parameters panel if user can not edit parameters
        $perms = $this->_getItemPerms($item);
        if (!$perms['canparams']) {
            $document->addStyleDeclaration('#details-options {display:none;}');
        }
        // ******************
        // Create the toolbar
        // ******************
        $toolbar = JToolBar::getInstance('toolbar');
        $tip_class = FLEXI_J30GE ? ' hasTooltip' : ' hasTip';
        // SET toolbar title
        if ($cid) {
            JToolBarHelper::title(JText::_('FLEXI_EDIT_ITEM'), 'itemedit');
            // Editing existing item
        } else {
            JToolBarHelper::title(JText::_('FLEXI_NEW_ITEM'), 'itemadd');
            // Creating new item
        }
        // **************
        // Common Buttons
        // **************
        // Applying new item type is a special case that has not loaded custom fieds yet
        JToolBarHelper::apply($item->type_id ? 'items.apply' : 'items.apply_type', !$isnew ? 'FLEXI_APPLY' : ($typesselected->id ? 'FLEXI_ADD' : 'FLEXI_APPLY_TYPE'), false);
        /*if (!$isnew || $item->version) flexicontent_html::addToolBarButton(
        		'FLEXI_FAST_APPLY', $btn_name='apply_ajax', $full_js="Joomla.submitbutton('items.apply_ajax')", $msg_alert='', $msg_confirm='',
        		$btn_task='items.apply_ajax', $extra_js='', $btn_list=false, $btn_menu=true, $btn_confirm=false, $btn_class="".$tip_class, $btn_icon="icon-loop",
        		'data-placement="bottom" title="Fast saving, without reloading the form. <br/><br/>Note: new files will not be uploaded, <br/>- in such a case please use \'Apply\'"');*/
        if (!$isnew || $item->version) {
            JToolBarHelper::save('items.save');
        }
        if (!$isnew || $item->version) {
            JToolBarHelper::custom('items.saveandnew', 'savenew.png', 'savenew.png', 'FLEXI_SAVE_AND_NEW', false);
        }
        JToolBarHelper::cancel('items.cancel');
        // ***********************
        // Add a preview button(s)
        // ***********************
        //$_sh404sef = JPluginHelper::isEnabled('system', 'sh404sef') && $config->get('sef');
        $_sh404sef = defined('SH404SEF_IS_RUNNING') && $config->get('sef');
        if ($cid) {
            // Domain URL and autologin vars
            $server = JURI::getInstance()->toString(array('scheme', 'host', 'port'));
            $autologin = '';
            //$params->get('autoflogin', 1) ? '&fcu='.$user->username . '&fcp='.$user->password : '';
            // Check if we are in the backend, in the back end we need to set the application to the site app instead
            // we do not remove 'isAdmin' check so that we can copy later without change, e.g. to a plugin
            $isAdmin = JFactory::getApplication()->isAdmin();
            if ($isAdmin && !$_sh404sef) {
                JFactory::$application = JApplication::getInstance('site');
            }
            // Create the URL
            $item_url = FlexicontentHelperRoute::getItemRoute($item->id . ':' . $item->alias, $categories[$item->catid]->slug) . ($item->language != '*' ? '&lang=' . substr($item->language, 0, 2) : '');
            $item_url = $_sh404sef ? Sh404sefHelperGeneral::getSefFromNonSef($item_url, $fullyQualified = true, $xhtml = false, $ssl = null) : JRoute::_($item_url);
            // Check if we are in the backend again
            // In backend we need to remove administrator from URL as it is added even though we've set the application to the site app
            if ($isAdmin && !$_sh404sef) {
                $admin_folder = str_replace(JURI::root(true), '', JURI::base(true));
                $item_url = str_replace($admin_folder . '/', '/', $item_url);
                // Restore application
                JFactory::$application = JApplication::getInstance('administrator');
            }
            $previewlink = $item_url . (strstr($item_url, '?') ? '&amp;' : '?') . 'preview=1' . $autologin;
            //$previewlink     = str_replace('&amp;', '&', $previewlink);
            //$previewlink = JRoute::_(JURI::root() . FlexicontentHelperRoute::getItemRoute($item->id.':'.$item->alias, $categories[$item->catid]->slug)) .$autologin;
            // PREVIEW for latest version
            if (!$params->get('use_versioning', 1) || $item->version == $item->current_version && $item->version == $item->last_version) {
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small btn-info spaced-btn" onClick="window.open(\'' . $previewlink . '\');"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('Preview') . '</button>', 'preview');
            } else {
                // Add a preview button for (currently) LOADED version of the item
                $previewlink_loaded_ver = $previewlink . '&version=' . $item->version;
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small" onClick="window.open(\'' . $previewlink_loaded_ver . '\');" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('FLEXI_PREVIEW_FORM_LOADED_VERSION') . ' [' . $item->version . ']</button>', 'preview');
                // Add a preview button for currently ACTIVE version of the item
                $previewlink_active_ver = $previewlink . '&version=' . $item->current_version;
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small" onClick="window.open(\'' . $previewlink_active_ver . '\');" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('FLEXI_PREVIEW_FRONTEND_ACTIVE_VERSION') . ' [' . $item->current_version . ']</button>', 'preview');
                // Add a preview button for currently LATEST version of the item
                $previewlink_last_ver = $previewlink;
                //'&version='.$item->last_version;
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small" onClick="window.open(\'' . $previewlink_last_ver . '\');" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('FLEXI_PREVIEW_LATEST_SAVED_VERSION') . ' [' . $item->last_version . ']</button>', 'preview');
            }
            JToolBarHelper::spacer();
            JToolBarHelper::divider();
            JToolBarHelper::spacer();
        }
        // ************************
        // Add modal layout editing
        // ************************
        if ($perms['cantemplates']) {
            JToolBarHelper::divider();
            if (!$isnew || $item->version) {
                flexicontent_html::addToolBarButton('FLEXI_EDIT_LAYOUT', $btn_name = 'apply_ajax', $full_js = "var url = jQuery(this).attr('data-href'); fc_showDialog(url, 'fc_modal_popup_container'); return false;", $msg_alert = '', $msg_confirm = '', $btn_task = 'items.apply_ajax', $extra_js = '', $btn_list = false, $btn_menu = true, $btn_confirm = false, $btn_class = "btn-info" . $tip_class, $btn_icon = "icon-pencil", 'data-placement="bottom" data-href="index.php?option=com_flexicontent&amp;view=template&amp;type=items&amp;tmpl=component&amp;ismodal=1&amp;folder=' . $item->itemparams->get('ilayout', $tparams->get('ilayout', 'default')) . '" title="Edit the display layout of this item. <br/><br/>Note: this layout maybe assigned to content types or other items, thus changing it will effect them too"');
            }
        }
        // Check if saving an item that translates an original content in site's default language
        $site_default = substr(flexicontent_html::getSiteDefaultLang(), 0, 2);
        $is_content_default_lang = $site_default == substr($item->language, 0, 2);
        // *****************************************************************************
        // Get (CORE & CUSTOM) fields and their VERSIONED values and then
        // (a) Apply Content Type Customization to CORE fields (label, description, etc)
        // (b) Create the edit html of the CUSTOM fields by triggering 'onDisplayField'
        // *****************************************************************************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $fields = $this->get('Extrafields');
        $item->fields =& $fields;
        if ($print_logging_info) {
            $fc_run_times['get_field_vals'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $jcustom = $app->getUserState('com_flexicontent.edit.item.custom');
        //print_r($jcustom);
        foreach ($fields as $field) {
            // a. Apply CONTENT TYPE customizations to CORE FIELDS, e.g a type specific label & description
            // NOTE: the field parameters are already created so there is not need to call this for CUSTOM fields, which do not have CONTENT TYPE customizations
            if ($field->iscore) {
                FlexicontentFields::loadFieldConfig($field, $item);
            }
            // b. Create field 's editing HTML (the form field)
            // NOTE: this is DONE only for CUSTOM fields, since form field html is created by the form for all CORE fields, EXCEPTION is the 'text' field (see bellow)
            if (!$field->iscore) {
                if (isset($jcustom[$field->name])) {
                    $field->value = array();
                    foreach ($jcustom[$field->name] as $i => $_val) {
                        $field->value[$i] = $_val;
                    }
                }
                $is_editable = !$field->valueseditable || $user->authorise('flexicontent.editfieldvalues', 'com_flexicontent.field.' . $field->id);
                if ($is_editable) {
                    FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayField', array(&$field, &$item));
                    if ($field->untranslatable) {
                        $field->html = (!isset($field->html) ? '<div class="fc-mssg-inline fc-warning" style="margin:0 4px 6px 4px; max-width: unset;">' . JText::_('FLEXI_PLEASE_PUBLISH_THIS_PLUGIN') . '</div><div class="clear"></div>' : '') . '<div class="alert alert-info fc-small fc-iblock" style="margin:0 4px 6px 4px; max-width: unset;">' . JText::_('FLEXI_FIELD_VALUE_IS_NON_TRANSLATABLE') . '</div>' . "\n" . (isset($field->html) ? '<div class="clear"></div>' . $field->html : '');
                    }
                } else {
                    if ($field->valueseditable == 1) {
                        $field->html = '<div class="fc-mssg fc-note">' . JText::_($field->parameters->get('no_acc_msg_form') ? $field->parameters->get('no_acc_msg_form') : 'FLEXI_NO_ACCESS_LEVEL_TO_EDIT_FIELD') . '</div>';
                    } else {
                        if ($field->valueseditable == 2) {
                            FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayFieldValue', array(&$field, $item));
                            $field->html = '<div class="fc-mssg fc-note">' . JText::_($field->parameters->get('no_acc_msg_form') ? $field->parameters->get('no_acc_msg_form') : 'FLEXI_NO_ACCESS_LEVEL_TO_EDIT_FIELD') . '</div>' . "\n" . $field->display;
                        } else {
                            if ($field->valueseditable == 3) {
                                FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayFieldValue', array(&$field, $item));
                                $field->html = $field->display;
                            } else {
                                if ($field->valueseditable == 4) {
                                    $field->html = '';
                                    $field->formhidden = 4;
                                }
                            }
                        }
                    }
                }
            }
            // c. Create main text field, via calling the display function of the textarea field (will also check for tabs)
            if ($field->field_type == 'maintext') {
                if (isset($item->item_translations)) {
                    $shortcode = substr($item->language, 0, 2);
                    foreach ($item->item_translations as $lang_id => $t) {
                        if ($shortcode == $t->shortcode) {
                            continue;
                        }
                        $field->name = array('jfdata', $t->shortcode, 'text');
                        $field->value[0] = html_entity_decode($t->fields->text->value, ENT_QUOTES, 'UTF-8');
                        FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
                        $t->fields->text->tab_labels = $field->tab_labels;
                        $t->fields->text->html = $field->html;
                        unset($field->tab_labels);
                        unset($field->html);
                    }
                }
                $field->name = 'text';
                // NOTE: We use the text created by the model and not the text retrieved by the CORE plugin code, which maybe overwritten with JoomFish/Falang data
                $field->value[0] = $item->text;
                // do not decode special characters this was handled during saving !
                // Render the field's (form) HTML
                FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
            }
        }
        if ($print_logging_info) {
            $fc_run_times['render_field_html'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // *************************
        // Get tags used by the item
        // *************************
        $usedtagsIds = $this->get('UsedtagsIds');
        // NOTE: This will normally return the already set versioned value of tags ($item->tags)
        $usedtags = $model->getUsedtagsData($usedtagsIds);
        // *******************************
        // Get categories used by the item
        // *******************************
        if ($isnew) {
            // Case for preselected main category for new items
            $maincat = $item->catid ? $item->catid : JRequest::getInt('maincat', 0);
            if (!$maincat) {
                $maincat = $app->getUserStateFromRequest($option . '.items.filter_cats', 'filter_cats', '', 'int');
            }
            if ($maincat) {
                $selectedcats = array($maincat);
                $item->catid = $maincat;
            } else {
                $selectedcats = array();
            }
            if ($tparams->get('cid_default')) {
                $selectedcats = $tparams->get('cid_default');
            }
            if ($tparams->get('catid_default')) {
                $item->catid = $tparams->get('catid_default');
            }
        } else {
            // NOTE: This will normally return the already set versioned value of categories ($item->categories)
            $selectedcats = $this->get('Catsselected');
        }
        //$selectedcats 	= $isnew ? array() : $fields['categories']->value;
        //echo "<br/>row->tags: "; print_r($item->tags);
        //echo "<br/>usedtagsIds: "; print_r($usedtagsIds);
        //echo "<br/>usedtags (data): "; print_r($usedtags);
        //echo "<br/>row->categories: "; print_r($item->categories);
        //echo "<br/>selectedcats: "; print_r($selectedcats);
        // *********************************************************************************************
        // Build select lists for the form field. Only few of them are used in J1.6+, since we will use:
        // (a) form XML file to declare them and then (b) getInput() method form field to create them
        // *********************************************************************************************
        // First clean form data, we do this after creating the description field which may contain HTML
        JFilterOutput::objectHTMLSafe($item, ENT_QUOTES);
        $lists = array();
        // build state list
        $non_publishers_stategrp = $perms['isSuperAdmin'] || $item->state == -3 || $item->state == -4;
        $special_privelege_stategrp = $item->state == 2 || $perms['canarchive'] || ($item->state == -2 || $perms['candelete']);
        $state = array();
        // Using <select> groups
        if ($non_publishers_stategrp || $special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_PUBLISHERS_WORKFLOW_STATES'));
        }
        $state[] = JHTML::_('select.option', 1, JText::_('FLEXI_PUBLISHED'));
        $state[] = JHTML::_('select.option', 0, JText::_('FLEXI_UNPUBLISHED'));
        $state[] = JHTML::_('select.option', -5, JText::_('FLEXI_IN_PROGRESS'));
        // States reserved for workflow
        if ($non_publishers_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_NON_PUBLISHERS_WORKFLOW_STATES'));
        }
        if ($item->state == -3 || $perms['isSuperAdmin']) {
            $state[] = JHTML::_('select.option', -3, JText::_('FLEXI_PENDING'));
        }
        if ($item->state == -4 || $perms['isSuperAdmin']) {
            $state[] = JHTML::_('select.option', -4, JText::_('FLEXI_TO_WRITE'));
        }
        // Special access states
        if ($special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_SPECIAL_ACTION_STATES'));
        }
        if ($item->state == 2 || $perms['canarchive']) {
            $state[] = JHTML::_('select.option', 2, JText::_('FLEXI_ARCHIVED'));
        }
        if ($item->state == -2 || $perms['candelete']) {
            $state[] = JHTML::_('select.option', -2, JText::_('FLEXI_TRASHED'));
        }
        // Close last <select> group
        if ($non_publishers_stategrp || $special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
        }
        $fieldname = 'jform[state]';
        $elementid = 'jform_state';
        $class = 'use_select2_lib';
        $attribs = 'class="' . $class . '"';
        $lists['state'] = JHTML::_('select.genericlist', $state, $fieldname, $attribs, 'value', 'text', $item->state, $elementid);
        if (!FLEXI_J16GE) {
            $lists['state'] = str_replace('<optgroup label="">', '</optgroup>', $lists['state']);
        }
        // *** BOF: J2.5 SPECIFIC SELECT LISTS
        if (FLEXI_J16GE) {
            // build featured flag
            $fieldname = 'jform[featured]';
            $elementid = 'jform_featured';
            /*
            $options = array();
            $options[] = JHTML::_('select.option',  0, JText::_( 'FLEXI_NO' ) );
            $options[] = JHTML::_('select.option',  1, JText::_( 'FLEXI_YES' ) );
            $attribs = FLEXI_J16GE ? ' style ="float:none!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
            $lists['featured'] = JHTML::_('select.radiolist', $options, $fieldname, $attribs, 'value', 'text', $item->featured, $elementid);
            */
            $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
            $attribs = ' class="' . $classes . '" ';
            $i = 1;
            $options = array(0 => JText::_('FLEXI_NO'), 1 => JText::_('FLEXI_YES'));
            $lists['featured'] = '';
            foreach ($options as $option_id => $option_label) {
                $checked = $option_id == $item->featured ? ' checked="checked"' : '';
                $elementid_no = $elementid . '_' . $i;
                if (!$prettycheckable_added) {
                    $lists['featured'] .= '<label class="fccheckradio_lbl" for="' . $elementid_no . '">';
                }
                $extra_params = !$prettycheckable_added ? '' : ' data-labeltext="' . JText::_($option_label) . '" data-labelPosition="right" data-customClass="fcradiocheck"';
                $lists['featured'] .= ' <input type="radio" id="' . $elementid_no . '" data-element-grpid="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="' . $option_id . '" ' . $checked . $extra_params . ' />';
                if (!$prettycheckable_added) {
                    $lists['featured'] .= '&nbsp;' . JText::_($option_label) . '</label>';
                }
                $i++;
            }
        }
        // *** EOF: J1.5 SPECIFIC SELECT LISTS
        // build version approval list
        $fieldname = 'jform[vstate]';
        $elementid = 'jform_vstate';
        /*
        $options = array();
        $options[] = JHTML::_('select.option',  1, JText::_( 'FLEXI_NO' ) );
        $options[] = JHTML::_('select.option',  2, JText::_( 'FLEXI_YES' ) );
        $attribs = FLEXI_J16GE ? ' style ="float:left!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
        $lists['vstate'] = JHTML::_('select.radiolist', $options, $fieldname, $attribs, 'value', 'text', 2, $elementid);
        */
        $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
        $attribs = ' class="' . $classes . '" ';
        $i = 1;
        $options = array(1 => JText::_('FLEXI_NO'), 2 => JText::_('FLEXI_YES'));
        $lists['vstate'] = '';
        foreach ($options as $option_id => $option_label) {
            $checked = $option_id == 2 ? ' checked="checked"' : '';
            $elementid_no = $elementid . '_' . $i;
            if (!$prettycheckable_added) {
                $lists['vstate'] .= '<label class="fccheckradio_lbl" for="' . $elementid_no . '">';
            }
            $extra_params = !$prettycheckable_added ? '' : ' data-labeltext="' . JText::_($option_label) . '" data-labelPosition="right" data-customClass="fcradiocheck"';
            $lists['vstate'] .= ' <input type="radio" id="' . $elementid_no . '" data-element-grpid="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="' . $option_id . '" ' . $checked . $extra_params . ' />';
            if (!$prettycheckable_added) {
                $lists['vstate'] .= '&nbsp;' . JText::_($option_label) . '</label>';
            }
            $i++;
        }
        // build field for notifying subscribers
        if (!$subscribers) {
            $lists['notify'] = !$isnew ? JText::_('FLEXI_NO_SUBSCRIBERS_EXIST') : '';
        } else {
            // b. Check if notification emails to subscribers , were already sent during current session
            $subscribers_notified = $session->get('subscribers_notified', array(), 'flexicontent');
            if (!empty($subscribers_notified[$item->id])) {
                $lists['notify'] = JText::_('FLEXI_SUBSCRIBERS_ALREADY_NOTIFIED');
            } else {
                // build favs notify field
                $fieldname = 'jform[notify]';
                $elementid = 'jform_notify';
                /*
                $attribs = FLEXI_J16GE ? ' style ="float:none!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
                $lists['notify'] = '<input type="checkbox" name="jform[notify]" id="jform_notify" '.$attribs.' /> '. $lbltxt;
                */
                $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
                $attribs = ' class="' . $classes . '" ';
                $lbltxt = $subscribers . ' ' . JText::_($subscribers > 1 ? 'FLEXI_SUBSCRIBERS' : 'FLEXI_SUBSCRIBER');
                if (!$prettycheckable_added) {
                    $lists['notify'] .= '<label class="fccheckradio_lbl" for="' . $elementid . '">';
                }
                $extra_params = !$prettycheckable_added ? '' : ' data-labeltext="' . $lbltxt . '" data-labelPosition="right" data-customClass="fcradiocheck"';
                $lists['notify'] = ' <input type="checkbox" id="' . $elementid . '" data-element-grpid="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="1" ' . $extra_params . ' checked="checked" />';
                if (!$prettycheckable_added) {
                    $lists['notify'] .= '&nbsp;' . $lbltxt . '</label>';
                }
            }
        }
        // Retrieve author configuration
        $authorparams = flexicontent_db::getUserConfig($user->id);
        // Get author's maximum allowed categories per item and set js limitation
        $max_cat_assign = intval($authorparams->get('max_cat_assign', 0));
        $document->addScriptDeclaration('
			max_cat_assign_fc = ' . $max_cat_assign . ';
			existing_cats_fc  = ["' . implode('","', $selectedcats) . '"];
		');
        JText::script('FLEXI_TOO_MANY_ITEM_CATEGORIES', true);
        // Creating categorories tree for item assignment, we use the 'create' privelege
        $actions_allowed = array('core.create');
        // Featured categories form field
        $featured_cats_parent = $params->get('featured_cats_parent', 0);
        $featured_cats = array();
        $enable_featured_cid_selector = $perms['multicat'] && $perms['canchange_featcat'];
        if ($featured_cats_parent) {
            $featured_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $featured_cats_parent, $depth_limit = 0);
            $disabled_cats = $params->get('featured_cats_parent_disable', 1) ? array($featured_cats_parent) : array();
            $featured_sel = array();
            foreach ($selectedcats as $item_cat) {
                if (isset($featured_tree[$item_cat])) {
                    $featured_sel[] = $item_cat;
                }
            }
            $class = "use_select2_lib select2_list_selected";
            $attribs = 'class="' . $class . '" multiple="multiple" size="8"';
            $attribs .= $enable_featured_cid_selector ? '' : ' disabled="disabled"';
            $fieldname = 'jform[featured_cid][]';
            $lists['featured_cid'] = ($enable_featured_cid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($featured_tree, $fieldname, $featured_sel, 3, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees = array(), $disable_subtrees = array(), $custom_options = array(), $disabled_cats);
        } else {
            // Do not display, if not configured or not allowed to the user
            $lists['featured_cid'] = false;
        }
        // Multi-category form field, for user allowed to use multiple categories
        $lists['cid'] = '';
        $enable_cid_selector = $perms['multicat'] && $perms['canchange_seccat'];
        if (1) {
            if ($tparams->get('cid_allowed_parent')) {
                $cid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $tparams->get('cid_allowed_parent'), $depth_limit = 0);
                $disabled_cats = $tparams->get('cid_allowed_parent_disable', 1) ? array($tparams->get('cid_allowed_parent')) : array();
            } else {
                $cid_tree =& $categories;
                $disabled_cats = array();
            }
            // Get author's maximum allowed categories per item and set js limitation
            $max_cat_assign = !$authorparams ? 0 : intval($authorparams->get('max_cat_assign', 0));
            $document->addScriptDeclaration('
				max_cat_assign_fc = ' . $max_cat_assign . ';
				existing_cats_fc  = ["' . implode('","', $selectedcats) . '"];
			');
            $class = "mcat use_select2_lib select2_list_selected";
            $class .= $max_cat_assign ? " validate-fccats" : " validate";
            $attribs = 'class="' . $class . '" multiple="multiple" size="20"';
            $attribs .= $enable_cid_selector ? '' : ' disabled="disabled"';
            $fieldname = 'jform[cid][]';
            $skip_subtrees = $featured_cats_parent ? array($featured_cats_parent) : array();
            $lists['cid'] = ($enable_cid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($cid_tree, $fieldname, $selectedcats, false, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees, $disable_subtrees = array(), $custom_options = array(), $disabled_cats);
        } else {
            if (count($selectedcats) > 1) {
                foreach ($selectedcats as $catid) {
                    $cat_titles[$catid] = $globalcats[$catid]->title;
                }
                $lists['cid'] .= implode(', ', $cat_titles);
            } else {
                $lists['cid'] = false;
            }
        }
        // Main category form field
        $class = 'scat use_select2_lib';
        if ($perms['multicat']) {
            $class .= ' validate-catid';
        } else {
            $class .= ' required';
        }
        $attribs = 'class="' . $class . '"';
        $fieldname = 'jform[catid]';
        $enable_catid_selector = $isnew && !$tparams->get('catid_default') || !$isnew && empty($item->catid) || $perms['canchange_cat'];
        if ($tparams->get('catid_allowed_parent')) {
            $catid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $tparams->get('catid_allowed_parent'), $depth_limit = 0);
            $disabled_cats = $tparams->get('catid_allowed_parent_disable', 1) ? array($tparams->get('catid_allowed_parent')) : array();
        } else {
            $catid_tree =& $categories;
            $disabled_cats = array();
        }
        $lists['catid'] = false;
        if (!empty($catid_tree)) {
            $disabled = $enable_catid_selector ? '' : ' disabled="disabled"';
            $attribs .= $disabled;
            $lists['catid'] = ($enable_catid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($catid_tree, $fieldname, $item->catid, 2, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees = array(), $disable_subtrees = array(), $custom_options = array(), $disabled_cats);
        } else {
            if (!$isnew && $item->catid) {
                $lists['catid'] = $globalcats[$item->catid]->title;
            }
        }
        //buid types selectlist
        $class = 'required use_select2_lib';
        $attribs = 'class="' . $class . '"';
        $fieldname = 'jform[type_id]';
        $elementid = 'jform_type_id';
        $lists['type'] = flexicontent_html::buildtypesselect($types, $fieldname, $typesselected->id, 1, $attribs, $elementid, $check_perms = true);
        //build languages list
        $allowed_langs = !$authorparams ? null : $authorparams->get('langs_allowed', null);
        $allowed_langs = !$allowed_langs ? null : FLEXIUtilities::paramToArray($allowed_langs);
        if (!$isnew && $allowed_langs) {
            $allowed_langs[] = $item->language;
        }
        // We will not use the default getInput() function of J1.6+ since we want to create a radio selection field with flags
        // we could also create a new class and override getInput() method but maybe this is an overkill, we may do it in the future
        $lists['languages'] = flexicontent_html::buildlanguageslist('jform[language]', 'class="use_select2_lib"', $item->language, 2, $allowed_langs);
        // Label for current item state: published, unpublished, archived etc
        switch ($item->state) {
            case 0:
                $published = JText::_('FLEXI_UNPUBLISHED');
                break;
            case 1:
                $published = JText::_('FLEXI_PUBLISHED');
                break;
            case -1:
                $published = JText::_('FLEXI_ARCHIVED');
                break;
            case -3:
                $published = JText::_('FLEXI_PENDING');
                break;
            case -5:
                $published = JText::_('FLEXI_IN_PROGRESS');
                break;
            case -4:
            default:
                $published = JText::_('FLEXI_TO_WRITE');
                break;
        }
        // **************************************************************
        // Handle Item Parameters Creation and Load their values for J1.5
        // In J1.6+ we declare them in the item form XML file
        // **************************************************************
        if (JHTML::_('date', $item->publish_down, 'Y') <= 1969 || $item->publish_down == $db->getNullDate() || empty($item->publish_down)) {
            $form->setValue('publish_down', null, '');
            // Setting to text will break form date element
        }
        // ****************************
        // Handle Template related work
        // ****************************
        // (a) Get the templates structures used to create form fields for template parameters
        $themes = flexicontent_tmpl::getTemplates();
        $tmpls_all = $themes->items;
        // (b) Get Content Type allowed templates
        $allowed_tmpls = $tparams->get('allowed_ilayouts');
        $type_default_layout = $tparams->get('ilayout', 'default');
        if (empty($allowed_tmpls)) {
            $allowed_tmpls = array();
        } else {
            if (!is_array($allowed_tmpls)) {
                $allowed_tmpls = explode("|", $allowed_tmpls);
            }
        }
        // (c) Add default layout, unless all templates allowed (=array is empty)
        if (count($allowed_tmpls) && !in_array($type_default_layout, $allowed_tmpls)) {
            $allowed_tmpls[] = $type_default_layout;
        }
        // (d) Create array of template data according to the allowed templates for current content type
        if (count($allowed_tmpls)) {
            foreach ($tmpls_all as $tmpl) {
                if (in_array($tmpl->name, $allowed_tmpls)) {
                    $tmpls[] = $tmpl;
                }
            }
        } else {
            $tmpls = $tmpls_all;
        }
        // (e) Apply Template Parameters values into the form fields structures
        foreach ($tmpls as $tmpl) {
            $jform = new JForm('com_flexicontent.template.item', array('control' => 'jform', 'load_data' => true));
            $jform->load($tmpl->params);
            $tmpl->params = $jform;
            foreach ($tmpl->params->getGroup('attribs') as $field) {
                $fieldname = $field->__get('fieldname');
                $value = $item->itemparams->get($fieldname);
                if (strlen($value)) {
                    $tmpl->params->setValue($fieldname, 'attribs', $value);
                }
            }
        }
        // ******************************
        // Assign data to VIEW's template
        // ******************************
        $this->assignRef('document', $document);
        $this->assignRef('lists', $lists);
        $this->assignRef('row', $item);
        if (FLEXI_J16GE) {
            $this->assignRef('form', $form);
        } else {
            $this->assignRef('editor', $editor);
            $this->assignRef('pane', $pane);
            $this->assignRef('formparams', $formparams);
        }
        if ($enable_translation_groups) {
            $this->assignRef('lang_assocs', $langAssocs);
        }
        if (FLEXI_FISH || FLEXI_J16GE) {
            $this->assignRef('langs', $langs);
        }
        $this->assignRef('typesselected', $typesselected);
        $this->assignRef('published', $published);
        $this->assignRef('nullDate', $nullDate);
        $this->assignRef('subscribers', $subscribers);
        $this->assignRef('fields', $fields);
        $this->assignRef('versions', $versions);
        $this->assignRef('ratings', $ratings);
        $this->assignRef('pagecount', $pagecount);
        $this->assignRef('params', $params);
        $this->assignRef('tparams', $tparams);
        $this->assignRef('tmpls', $tmpls);
        $this->assignRef('usedtags', $usedtags);
        $this->assignRef('perms', $perms);
        $this->assignRef('current_page', $current_page);
        // Clear custom form data from session
        $app->setUserState($form->option . '.edit.' . $form->context . '.custom', false);
        $app->setUserState($form->option . '.edit.' . $form->context . '.jfdata', false);
        $app->setUserState($form->option . '.edit.' . $form->context . '.unique_tmp_itemid', false);
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        parent::display($tpl);
        if ($print_logging_info) {
            $fc_run_times['form_rendering'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
    }
					<button class="<?php 
        echo $btn_class;
        ?>
  btn-success" type="button" onclick="return flexi_submit('save_a_preview', 'flexi_form_submit_btns', 'flexi_form_submit_msg');">
						<span class="fcbutton_preview_save"><?php 
        echo JText::_(!$isnew ? 'FLEXI_SAVE_A_PREVIEW' : 'FLEXI_ADD_A_PREVIEW');
        ?>
</span>
					</button>
				<?php 
    }
    ?>

				<?php 
    $params = 'status=no,toolbar=no,scrollbars=yes,titlebar=no,menubar=no,resizable=yes,left=50,width=\'+((screen.width-100) > 1360 ? 1360 : (screen.width-100))+\',top=20,height=\'+((screen.width-160) > 100 ? 1000 : (screen.width-160))+\',directories=no,location=no';
    $link = JRoute::_(FlexicontentHelperRoute::getItemRoute($this->item->id . ':' . $this->item->alias, $this->item->catid, 0, $this->item) . '&preview=1');
    ?>
			
				<?php 
    if (in_array('preview_latest', $allowbuttons_fe) && !$isredirected_after_submit && !$isnew) {
        ?>
					<button class="<?php 
        echo $btn_class;
        ?>
  btn-default" type="button" onclick="window.open('<?php 
        echo $link;
        ?>
','preview2','<?php 
        echo $params;
        ?>
'); return false;">
 /**
  * Creates the edit button
  *
  * @param int $id
  * @param array $params
  * @since 1.0
  */
 static function editbutton($item, &$params)
 {
     if (!$params->get('show_editbutton', 1) || JRequest::getCmd('print')) {
         return;
     }
     $user = JFactory::getUser();
     // Determine if current user can edit the given item
     $has_edit_state = false;
     $asset = 'com_content.article.' . $item->id;
     $has_edit_state = $user->authorise('core.edit', $asset) || $user->authorise('core.edit.own', $asset) && $item->created_by == $user->get('id');
     // ALTERNATIVE 1
     //$rights = FlexicontentHelperPerm::checkAllItemAccess($user->get('id'), 'item', $item->id);
     //$has_edit_state = in_array('edit', $rights) || (in_array('edit.own', $rights) && $item->created_by == $user->get('id')) ;
     // Create the edit button only if user can edit the give item
     if (!$has_edit_state) {
         return;
     }
     $show_icons = $params->get('show_icons');
     if ($show_icons) {
         $attribs = '';
         $image = JHTML::image(FLEXI_ICONPATH . 'edit.png', JText::_('FLEXI_EDIT'), $attribs);
     } else {
         $image = '';
     }
     $overlib = JText::_('FLEXI_EDIT_TIP');
     $text = JText::_('FLEXI_EDIT');
     $button_classes = 'fc_editbutton';
     if ($show_icons == 1) {
         $caption = '';
         $button_classes .= '';
     } else {
         $caption = $text;
         $button_classes .= FLEXI_J30GE ? ' btn btn-small' : ' fc_button fcsimple fcsmall';
     }
     $button_classes .= FLEXI_J30GE ? ' hasTooltip' : ' hasTip';
     $tooltip_title = flexicontent_html::getToolTip($text, $overlib, 0);
     if ($params->get('show_editbutton', 1) == '1') {
         // Maintain menu item ? e.g. current category view,
         $Itemid = JRequest::getInt('Itemid', 0);
         //$Itemid = 0;
         $item_url = JRoute::_(FlexicontentHelperRoute::getItemRoute($item->slug, $item->categoryslug, $Itemid, $item));
         $link = $item_url . (strstr($item_url, '?') ? '&' : '?') . 'task=edit';
         $targetLink = "_self";
     } else {
         if ($params->get('show_editbutton', 1) == '2') {
             //$link = JURI::base(true).'/administrator/index.php?option=com_flexicontent&view=items&filter_id='.$item->id;
             $link = JURI::base(true) . '/administrator/index.php?option=com_flexicontent&task=items.edit&cid[]=' . $item->id;
             $targetLink = "_blank";
         }
     }
     $output = '<a href="' . $link . '" class="' . $button_classes . '" target="' . $targetLink . '" title="' . $tooltip_title . '">' . $image . $caption . '</a>';
     $output = JText::_('FLEXI_ICON_SEP') . $output . JText::_('FLEXI_ICON_SEP');
     return $output;
 }
 function onDisplayFieldValue(&$field, $item, $values = null, $prop = 'display')
 {
     if (!in_array($field->field_type, self::$field_types)) {
         return;
     }
     $field->{$prop} = '';
     global $globalcats;
     $app = JFactory::getApplication();
     $db = JFactory::getDBO();
     $user = JFactory::getUser();
     $option = JRequest::getCmd('option');
     $view = JRequest::getString('view', FLEXI_ITEMVIEW);
     $print = JRequest::getCMD('print');
     // No output if it is not FLEXIcontent item view or view is "print"
     if ($view != FLEXI_ITEMVIEW || $option != 'com_flexicontent' || $print) {
         return;
     }
     // parameters shortcuts
     $load_css = $field->parameters->get('load_css', 1);
     $use_tooltip = $field->parameters->get('use_tooltip', 1);
     $use_title = $field->parameters->get('use_title', 0);
     $use_category_link = $field->parameters->get('use_category_link', 0);
     $show_prevnext_count = $field->parameters->get('show_prevnext_count', 1);
     $tooltip_title_next = JText::_($field->parameters->get('tooltip_title_next', 'FLEXI_FIELDS_PAGENAV_GOTONEXT'));
     $tooltip_title_prev = JText::_($field->parameters->get('tooltip_title_prev', 'FLEXI_FIELDS_PAGENAV_GOTOPREV'));
     $prev_label = JText::_($field->parameters->get('prev_label', 'FLEXI_FIELDS_PAGENAV_GOTOPREV'));
     $next_label = JText::_($field->parameters->get('next_label', 'FLEXI_FIELDS_PAGENAV_GOTONEXT'));
     $category_label = JText::_($field->parameters->get('category_label', 'FLEXI_FIELDS_PAGENAV_CATEGORY'));
     $field->{$prop} = null;
     $use_model_state = true;
     if ($use_model_state) {
         $cid = (int) $app->getUserState($option . '.nav_catid', 0);
     }
     $cid = !$cid || !isset($globalcats[$cid]) ? JRequest::getInt('cid') : $cid;
     $cid = !$cid || !isset($globalcats[$cid]) ? (int) $item->catid : $cid;
     $item_count = $app->getUserState($option . '.' . $cid . 'nav_item_count', 0);
     $loc_to_ids = $app->getUserState($option . '.' . $cid . 'nav_loc_to_ids', array());
     $ids_to_loc = array_flip($loc_to_ids);
     // Get category parameters
     $query = 'SELECT * FROM #__categories WHERE id = ' . $cid;
     $db->setQuery($query);
     $category = $db->loadObject();
     $category->parameters = new JRegistry($category->params);
     if (isset($ids_to_loc[$item->id])) {
         $location = $ids_to_loc[$item->id];
     } else {
         // Get list of ids of selected, null indicates to return item ids array. TODO retrieve item ids from view:
         // This will allow special navigating layouts "mcats,author,myitems,tags,favs" and also utilize current filtering
         $ids = null;
         $loc_to_ids = $this->getItemList($ids, $cid, $user->id);
         $ids_to_loc = array_flip($loc_to_ids);
         // Item ID to location MAP
         $item_count = count($loc_to_ids);
         // Total items in category
         $location = isset($ids_to_loc[$item->id]) ? $ids_to_loc[$item->id] : false;
         // Location of current content item in array list
         if ($location !== false) {
             $offset = $location - 50 > 0 ? $location - 50 : 0;
             $length = $offset + 100 < $item_count ? 100 : $item_count - $offset;
             $nav_loc_to_ids = array_slice($loc_to_ids, $offset, $length, true);
             $app->setUserState($option . '.' . $cid . 'nav_item_count', $item_count);
             $app->setUserState($option . '.' . $cid . 'nav_loc_to_ids', $nav_loc_to_ids);
         } else {
             $app->setUserState($option . '.' . $cid . 'nav_item_count', null);
             $app->setUserState($option . '.' . $cid . 'nav_loc_to_ids', null);
         }
     }
     // Get previous and next item data
     $field->prev = null;
     $field->prevtitle = null;
     $field->prevurl = null;
     $field->next = null;
     $field->nexttitle = null;
     $field->nexturl = null;
     $field->category = null;
     $field->categorytitle = null;
     $field->categoryurl = null;
     // Get item data
     $rows = false;
     $prev_id = null;
     $next_id = null;
     if ($location !== false) {
         $prev_id = $location - 1 >= 0 ? $loc_to_ids[$location - 1] : null;
         $next_id = $location + 1 < $item_count ? $loc_to_ids[$location + 1] : null;
         $ids = array();
         // Previous item if it exists
         if ($prev_id) {
             $ids[] = $prev_id;
         }
         // Current item may belong may not be list in main category so retrieve it to get a proper categoryslug
         $ids[] = $item->id;
         // Next item if it exists
         if ($next_id) {
             $ids[] = $next_id;
         }
         // Query specific ids
         $rows = $this->getItemList($ids, $cid, $user->id);
         // previous content item
         if ($prev_id) {
             $field->prev = $rows[$prev_id];
             $field->prevtitle = $field->prev->title;
             $field->prevurl = JRoute::_(FlexicontentHelperRoute::getItemRoute($field->prev->slug, $field->prev->categoryslug, 0, $field->prev));
         }
         // next content item
         if ($next_id) {
             $field->next = $rows[$next_id];
             $field->nexttitle = $field->next->title;
             $field->nexturl = JRoute::_(FlexicontentHelperRoute::getItemRoute($field->next->slug, $field->next->categoryslug, 0, $field->next));
         }
     }
     // Check if displaying nothing and stop
     if (!$field->prev && !$field->next && !$use_category_link) {
         return;
     }
     // Get images
     $items_arr = array();
     if ($field->prev) {
         $items_arr[$field->prev->id] = $field->prev;
     }
     if ($field->next) {
         $items_arr[$field->next->id] = $field->next;
     }
     $thumbs = $this->getItemThumbs($field->parameters, $items_arr);
     $field->prevThumb = $field->prev && isset($thumbs[$field->prev->id]) ? $thumbs[$field->prev->id] : '';
     $field->nextThumb = $field->next && isset($thumbs[$field->next->id]) ? $thumbs[$field->next->id] : '';
     // Get layout name
     $viewlayout = $field->parameters->get('viewlayout', '');
     $viewlayout = $viewlayout ? 'value_' . $viewlayout : 'value_default';
     //$this->values = $values;
     //$this->displayFieldValue( $prop, $viewlayout );
     include self::getFormPath($this->fieldtypes[0], $viewlayout);
     // Load needed JS/CSS
     if ($use_tooltip) {
         JHtml::_('bootstrap.tooltip');
     }
     if ($load_css) {
         JFactory::getDocument()->addStyleSheet(JURI::root(true) . '/plugins/flexicontent_fields/fcpagenav/' . (FLEXI_J16GE ? 'fcpagenav/' : '') . 'fcpagenav.css');
     }
     $field->{$prop} = $html;
 }
Exemple #16
0
 //var_dump ($fc_list_items[2]->fieldvalues[$fieldaddressid][0]);
 foreach ($fc_list_items as $adress) {
     //var_dump ($adress->fieldvalues);
     if (!isset($adress->fieldvalues[$fieldaddressid][0])) {
         $adress->fieldvalues[$fieldaddressid][0] = '';
     }
     $coord = $adress->fieldvalues[$fieldaddressid][0];
     $coord = unserialize($coord);
     $lat = $coord['lat'];
     $lon = $coord['lon'];
     if (!empty($lat) || !empty($lon)) {
         $coordo = $lat . "," . $lon;
         // }
         $title = addslashes($adress->title);
         if ($uselink) {
             $link = JRoute::_(FlexicontentHelperRoute::getItemRoute($adress->id, $adress->catid, $forced_itemid, $adress));
             $link = '<p class="link"><a href="' . $link . '" target="' . $linkmode . '">' . JText::_($readmore) . '</a></p>';
             $link = addslashes($link);
         } else {
             $link = '';
         }
         if ($useadress) {
             if (!isset($coord['addr_display'])) {
                 $coord['addr_display'] = '';
             }
             $addre = '<p>' . $coord['addr_display'] . '</p>';
             $addre = addslashes($addre);
             $addre = preg_replace("/(\r\n|\n|\r)/", " ", $addre);
         } else {
             $addre = '';
         }
 /**
  * Content Search method
  * The sql must return the following fields that are used in a common display
  * routine: href, title, section, created, text, browsernav
  * @param string Target search string
  * @param string mathcing option, exact|any|all
  * @param string ordering option, newest|oldest|popular|alpha|category
  * @param mixed An array if restricted to areas, null if search all
  */
 function onContentSearch($text, $phrase = '', $ordering = '', $areas = null)
 {
     $db = JFactory::getDbo();
     $app = JFactory::getApplication();
     $user = JFactory::getUser();
     // Get language
     $cntLang = substr(JFactory::getLanguage()->getTag(), 0, 2);
     // Current Content language (Can be natively switched in J2.5)
     $urlLang = JRequest::getWord('lang', '');
     // Language from URL (Can be switched via Joomfish in J1.5)
     $lang = FLEXI_J16GE || empty($urlLang) ? $cntLang : $urlLang;
     // COMPONENT PARAMETERS
     $cparams = $app->isSite() ? $app->getParams('com_flexicontent') : JComponentHelper::getParams('com_flexicontent');
     if (!defined('FLEXI_SECTION')) {
         define('FLEXI_SECTION', $cparams->get('flexi_section'));
     }
     // define section
     $show_noauth = $cparams->get('show_noauth', 0);
     // items the user cannot see ...
     $searchText = $text;
     $AllAreas = array_keys($this->_getAreas());
     $AllTypes = array_keys($this->_getContentTypes());
     if (is_array($areas)) {
         // search in selected areas
         $searchAreas = array_intersect($areas, $AllAreas);
         $searchTypes = array_intersect($areas, $AllTypes);
         if (!$searchAreas && !$searchTypes) {
             return array();
         }
         if (!$searchAreas) {
             $searchAreas = $AllAreas;
         }
         if (!$searchTypes) {
             $searchTypes = $AllTypes;
         }
     } else {
         // search in all avaliable areas if no selected ones
         $searchAreas = $AllAreas;
         $searchTypes = $AllTypes;
     }
     foreach ($searchTypes as $id => $tipe) {
         $searchTypes[$id] = preg_replace('/\\D/', '', $tipe);
     }
     $types = implode(', ', $searchTypes);
     $filter_lang = $this->params->def('filter_lang', 1);
     $limit = $this->params->def('search_limit', 50);
     // Dates for publish up & down items
     $date = JFactory::getDate();
     $nowDate = FLEXI_J16GE ? $date->toSql() : $date->toMySQL();
     $nullDate = $db->getNullDate();
     $text = trim($text);
     if ($text == '') {
         return array();
     }
     $wheres = array();
     switch ($phrase) {
         case 'exact':
             $text = FLEXI_J16GE ? $db->escape($text, true) : $db->getEscaped($text, true);
             $text = $db->Quote('%' . $text . '%', false);
             $wheres2 = array();
             if (in_array('FlexisearchTitle', $searchAreas)) {
                 $wheres2[] = 'i.title LIKE ' . $text;
             }
             if (in_array('FlexisearchDesc', $searchAreas)) {
                 $wheres2[] = 'i.introtext LIKE ' . $text;
                 $wheres2[] = 'i.fulltext LIKE ' . $text;
             }
             if (in_array('FlexisearchMeta', $searchAreas)) {
                 $wheres2[] = 'i.metakey LIKE ' . $text;
                 $wheres2[] = 'i.metadesc LIKE ' . $text;
             }
             if (in_array('FlexisearchFields', $searchAreas)) {
                 $wheres2[] = "f.field_type IN ('text','textselect') AND f.issearch=1 AND fir.value LIKE " . $text;
             }
             if (in_array('FlexisearchTags', $searchAreas)) {
                 $wheres2[] = 't.name LIKE ' . $text;
             }
             if (count($wheres2)) {
                 $where = '(' . implode(') OR (', $wheres2) . ')';
             }
             break;
         case 'all':
         case 'any':
         default:
             $words = explode(' ', $text);
             $wheres = array();
             foreach ($words as $word) {
                 $word = FLEXI_J16GE ? $db->escape($word, true) : $db->getEscaped($word, true);
                 $word = $db->Quote('%' . $word . '%', false);
                 $wheres2 = array();
                 if (in_array('FlexisearchTitle', $searchAreas)) {
                     $wheres2[] = 'i.title LIKE ' . $word;
                 }
                 if (in_array('FlexisearchDesc', $searchAreas)) {
                     $wheres2[] = 'i.introtext LIKE ' . $word;
                     $wheres2[] = 'i.fulltext LIKE ' . $word;
                 }
                 if (in_array('FlexisearchMeta', $searchAreas)) {
                     $wheres2[] = 'i.metakey LIKE ' . $word;
                     $wheres2[] = 'i.metadesc LIKE ' . $word;
                 }
                 if (in_array('FlexisearchFields', $searchAreas)) {
                     $wheres2[] = "f.field_type IN ('text','textselect') AND f.issearch=1 AND fir.value LIKE " . $word;
                 }
                 if (in_array('FlexisearchTags', $searchAreas)) {
                     $wheres2[] = 't.name LIKE ' . $word;
                 }
                 if (count($wheres2)) {
                     $wheres[] = '(' . implode(') OR (', $wheres2) . ')';
                 }
             }
             if (count($wheres)) {
                 $where = '(' . implode($phrase == 'all' ? ') AND (' : ') OR (', $wheres) . ')';
             }
             break;
     }
     if (!@$where) {
         return array();
     }
     //if ( empty($where) ) $where = '1';
     switch ($ordering) {
         //case 'relevance': $order = ' ORDER BY score DESC, i.title ASC'; break;
         case 'oldest':
             $order = 'i.created ASC';
             break;
         case 'popular':
             $order = 'i.hits DESC';
             break;
         case 'alpha':
             $order = 'i.title ASC';
             break;
         case 'category':
             $order = 'c.title ASC, i.title ASC';
             break;
         case 'newest':
             $order = 'i.created DESC';
             break;
         default:
             $order = 'i.created DESC';
             break;
     }
     // ****************************************************************************************
     // Create JOIN clause and WHERE clause part for filtering by current (viewing) access level
     // ****************************************************************************************
     $joinaccess = '';
     $andaccess = '';
     $select_access = '';
     // Extra access columns for main category and content type (item access will be added as 'access')
     $select_access .= ',  c.access as category_access, ty.access as type_access';
     if (!$show_noauth) {
         // User not allowed to LIST unauthorized items
         if (FLEXI_J16GE) {
             $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
             $aid_list = implode(",", $aid_arr);
             $andaccess .= ' AND ty.access IN (0,' . $aid_list . ')';
             $andaccess .= ' AND  c.access IN (0,' . $aid_list . ')';
             $andaccess .= ' AND  i.access IN (0,' . $aid_list . ')';
         } else {
             $aid = (int) $user->get('aid');
             if (FLEXI_ACCESS) {
                 $joinaccess .= ' LEFT JOIN #__flexiaccess_acl AS gt ON ty.id = gt.axo AND gt.aco = "read" AND gt.axosection = "type"';
                 $joinaccess .= ' LEFT JOIN #__flexiaccess_acl AS gc ON  c.id = gc.axo AND gc.aco = "read" AND gc.axosection = "category"';
                 $joinaccess .= ' LEFT JOIN #__flexiaccess_acl AS gi ON  i.id = gi.axo AND gi.aco = "read" AND gi.axosection = "item"';
                 $andaccess .= ' AND (gt.aro IN ( ' . $user->gmid . ' ) OR ty.access <= ' . $aid . ')';
                 $andaccess .= ' AND (gc.aro IN ( ' . $user->gmid . ' ) OR  c.access <= ' . $aid . ')';
                 $andaccess .= ' AND (gi.aro IN ( ' . $user->gmid . ' ) OR  i.access <= ' . $aid . ')';
             } else {
                 $andaccess .= ' AND ty.access <= ' . $aid;
                 $andaccess .= ' AND  c.access <= ' . $aid;
                 $andaccess .= ' AND  i.access <= ' . $aid;
             }
         }
         $select_access .= ', 1 AS has_access';
     } else {
         // Access Flags for: content type, main category, item
         if (FLEXI_J16GE) {
             $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
             $aid_list = implode(",", $aid_arr);
             $select_access .= ', ' . ' CASE WHEN ' . '  ty.access IN (' . $aid_list . ') AND ' . '   c.access IN (' . $aid_list . ') AND ' . '   i.access IN (' . $aid_list . ') ' . ' THEN 1 ELSE 0 END AS has_access';
         } else {
             $aid = (int) $user->get('aid');
             if (FLEXI_ACCESS) {
                 $joinaccess .= ' LEFT JOIN #__flexiaccess_acl AS gt ON ty.id = gt.axo AND gt.aco = "read" AND gt.axosection = "type"';
                 $joinaccess .= ' LEFT JOIN #__flexiaccess_acl AS gc ON  c.id = gc.axo AND gc.aco = "read" AND gc.axosection = "category"';
                 $joinaccess .= ' LEFT JOIN #__flexiaccess_acl AS gi ON  i.id = gi.axo AND gi.aco = "read" AND gi.axosection = "item"';
                 $select_access .= ', ' . ' CASE WHEN ' . '  (gt.aro IN ( ' . $user->gmid . ' ) OR ty.access <= ' . (int) $aid . ') AND ' . '  (gc.aro IN ( ' . $user->gmid . ' ) OR  c.access <= ' . (int) $aid . ') AND ' . '  (gi.aro IN ( ' . $user->gmid . ' ) OR  i.access <= ' . (int) $aid . ') ' . ' THEN 1 ELSE 0 END AS has_access';
             } else {
                 $select_access .= ', ' . ' CASE WHEN ' . '  (ty.access <= ' . (int) $aid . ') AND ' . '  ( c.access <= ' . (int) $aid . ') AND ' . '  ( i.access <= ' . (int) $aid . ') ' . ' THEN 1 ELSE 0 END AS has_access';
             }
         }
     }
     // **********************************************************************************************************************************************************
     // Create WHERE clause part for filtering by current active language, and current selected contend types ( !! although this is possible via a filter too ...)
     // **********************************************************************************************************************************************************
     $andlang = '';
     if ($app->isSite() && (FLEXI_FISH || FLEXI_J16GE && $app->getLanguageFilter()) && $filter_lang) {
         $andlang .= ' AND ( i.language LIKE ' . $db->Quote($lang . '%') . ' OR i.language="*" ) ';
         $andlang .= ' AND ( c.language LIKE ' . $db->Quote($lang . '%') . ' OR c.language="*" ) ';
     }
     // search articles
     $results = array();
     if ($limit > 0) {
         $query = $db->getQuery(true);
         $query->clear();
         $query->select('' . ' i.id as id,' . ' i.title AS title,' . ' i.language AS language,' . ' i.metakey AS metakey,' . ' i.metadesc AS metadesc,' . ' i.modified AS created,' . ' t.name AS tagname,' . ' fir.value as field,' . ' i.access, ie.type_id,' . ' CONCAT(i.introtext, i.fulltext) AS text,' . ' CONCAT_WS( " / ", ' . $db->Quote(JText::_('FLEXICONTENT')) . ', c.title, i.title ) AS section,' . ' CASE WHEN CHAR_LENGTH(i.alias) THEN CONCAT_WS(\':\', i.id, i.alias) ELSE i.id END AS slug,' . ' CASE WHEN CHAR_LENGTH(c.alias) THEN CONCAT_WS(\':\', c.id, c.alias) ELSE c.id END AS catslug,' . ' "2" AS browsernav' . $select_access);
         $query->from('#__content AS i ' . ' JOIN #__categories AS c ON i.catid = c.id' . ' JOIN #__flexicontent_items_ext AS ie ON i.id = ie.item_id' . ' JOIN #__flexicontent_types AS ty ON ie.type_id = ty.id' . ' LEFT JOIN #__flexicontent_fields_item_relations AS fir ON i.id = fir.item_id' . ' LEFT JOIN #__flexicontent_fields AS f ON fir.field_id = f.id' . ' LEFT JOIN #__flexicontent_tags_item_relations AS tir ON i.id = tir.itemid' . ' LEFT JOIN #__flexicontent_tags AS t ON tir.tid = t.id	' . $joinaccess);
         $query->where(' (' . $where . ') ' . ' AND ie.type_id IN(' . $types . ') ' . ' AND i.state IN (1, -5) AND c.published = 1 ' . ' AND (i.publish_up = ' . $db->Quote($nullDate) . ' OR i.publish_up <= ' . $db->Quote($nowDate) . ') ' . ' AND (i.publish_down = ' . $db->Quote($nullDate) . ' OR i.publish_down >= ' . $db->Quote($nowDate) . ') ' . $andaccess . $andlang);
         $query->group('i.id');
         $query->order($order);
         //echo "<pre style='white-space:normal!important;'>".$query."</pre>";
         $db->setQuery($query, 0, $limit);
         $list = $db->loadObjectList();
         if ($db->getErrorNum()) {
             echo $db->getErrorMsg();
         }
         if ($list) {
             $item_cats = FlexicontentFields::_getCategories($list);
             foreach ($list as $key => $item) {
                 // echo $item->title." ".$item->tagname."<br/>"; // Before checking for noHTML
                 if (FLEXI_J16GE || $item->sectionid == FLEXI_SECTION) {
                     $item->categories = isset($item_cats[$item->id]) ? $item_cats[$item->id] : array();
                     // in case of item categories missing
                     $item->href = JRoute::_(FlexicontentHelperRoute::getItemRoute($item->slug, $item->catslug, 0, $item));
                 } else {
                     $item->href = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug, $item->sectionid));
                 }
                 if (searchHelper::checkNoHTML($item, $searchText, array('title', 'metadesc', 'metakey', 'tagname', 'field', 'text'))) {
                     $results[$item->id] = $item;
                 }
             }
         }
     }
     return $results;
 }
 public static function getList(&$params)
 {
     global $modfc_jprof, $mod_fc_run_times;
     $forced_itemid = $params->get('forced_itemid');
     $db = JFactory::getDBO();
     $user = JFactory::getUser();
     // Get IDs of user's access view levels
     if (!FLEXI_J16GE) {
         $aid = (int) $user->get('aid');
     } else {
         $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
     }
     // get the component parameters
     $flexiparams = JComponentHelper::getParams('com_flexicontent');
     // get module ordering parameters
     $ordering = $params->get('ordering', array());
     $count = (int) $params->get('count', 5);
     $featured = (int) $params->get('count_feat', 1);
     // Default ordering is 'added' if none ordering is set. Also make sure $ordering is an array (of ordering groups)
     if (empty($ordering)) {
         $ordering = array('added');
     }
     if (!is_array($ordering)) {
         $ordering = explode(',', $ordering);
     }
     // get other module parameters
     $method_curlang = (int) $params->get('method_curlang', 0);
     // standard
     $display_title = $params->get('display_title');
     $link_title = $params->get('link_title');
     $cuttitle = $params->get('cuttitle');
     $display_date = $params->get('display_date');
     $display_text = $params->get('display_text');
     $display_hits = $params->get('display_hits');
     $display_voting = $params->get('display_voting');
     $display_comments = $params->get('display_comments');
     $mod_readmore = $params->get('mod_readmore');
     $mod_cut_text = $params->get('mod_cut_text');
     $mod_do_stripcat = $params->get('mod_do_stripcat', 1);
     $mod_use_image = $params->get('mod_use_image');
     $mod_image = $params->get('mod_image');
     $mod_link_image = $params->get('mod_link_image');
     $mod_default_img_show = $params->get('mod_default_img_show', 1);
     $mod_default_img_path = $params->get('mod_default_img_path', 'components/com_flexicontent/assets/images/image.png');
     $mod_width = (int) $params->get('mod_width', 80);
     $mod_height = (int) $params->get('mod_height', 80);
     $mod_method = (int) $params->get('mod_method', 1);
     // featured
     $display_title_feat = $params->get('display_title_feat');
     $link_title_feat = $params->get('link_title_feat');
     $cuttitle_feat = $params->get('cuttitle_feat');
     $display_date_feat = $params->get('display_date_feat');
     $display_text_feat = $params->get('display_text');
     $display_hits_feat = $params->get('display_hits_feat');
     $display_voting_feat = $params->get('display_voting_feat');
     $display_comments_feat = $params->get('display_comments_feat');
     $mod_readmore_feat = $params->get('mod_readmore_feat');
     $mod_cut_text_feat = $params->get('mod_cut_text_feat');
     $mod_do_stripcat_feat = $params->get('mod_do_stripcat_feat', 1);
     $mod_use_image_feat = $params->get('mod_use_image_feat');
     $mod_link_image_feat = $params->get('mod_link_image_feat');
     $mod_width_feat = (int) $params->get('mod_width_feat', 140);
     $mod_height_feat = (int) $params->get('mod_height_feat', 140);
     $mod_method_feat = (int) $params->get('mod_method_feat', 1);
     // Common for image of standard/feature image
     $mod_image_custom_display = $params->get('mod_image_custom_display');
     $mod_image_custom_url = $params->get('mod_image_custom_url');
     $mod_image_fallback_img = $params->get('mod_image_fallback_img');
     // Retrieve default image for the image field and also create field parameters so that they can be used
     if ($mod_image) {
         $query = 'SELECT attribs, name FROM #__flexicontent_fields WHERE id = ' . (int) $mod_image;
         $db->setQuery($query);
         $mod_image_dbdata = $db->loadObject();
         $mod_image_name = $mod_image_dbdata->name;
         //$img_fieldparams = new JRegistry($mod_image_dbdata->attribs);
     }
     if ($mod_default_img_show) {
         $src = $mod_default_img_path;
         // Default image featured
         $h = '&amp;h=' . $mod_height;
         $w = '&amp;w=' . $mod_width;
         $aoe = '&amp;aoe=1';
         $q = '&amp;q=95';
         $zc = $mod_method ? '&amp;zc=' . $mod_method : '';
         $ext = strtolower(pathinfo($src, PATHINFO_EXTENSION));
         $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
         $conf = $w . $h . $aoe . $q . $zc . $f;
         $base_url = !preg_match("#^http|^https|^ftp|^/#i", $src) ? JURI::base(true) . '/' : '';
         $thumb_default = JURI::base() . 'components/com_flexicontent/librairies/phpthumb/phpThumb.php?src=' . $base_url . $src . $conf;
         // Default image standard
         $h = '&amp;h=' . $mod_height_feat;
         $w = '&amp;w=' . $mod_width_feat;
         $aoe = '&amp;aoe=1';
         $q = '&amp;q=95';
         $zc = $mod_method_feat ? '&amp;zc=' . $mod_method_feat : '';
         $ext = strtolower(pathinfo($src, PATHINFO_EXTENSION));
         $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
         $conf = $w . $h . $aoe . $q . $zc . $f;
         $base_url = !preg_match("#^http|^https|^ftp|^/#i", $src) ? JURI::base(true) . '/' : '';
         $thumb_default_feat = JURI::base() . 'components/com_flexicontent/librairies/phpthumb/phpThumb.php?src=' . $base_url . $src . $conf;
     }
     // Retrieve custom displayed field data (including their parameters and access):  hits/voting/etc
     if ($display_hits || $display_hits_feat || $display_voting || $display_voting_feat) {
         $query = 'SELECT * FROM #__flexicontent_fields';
         $disp_field_where = array();
         if ($display_hits || $display_hits_feat) {
             $disp_field_where[] = 'field_type="hits"';
         }
         if ($display_voting || $display_voting_feat) {
             $disp_field_where[] = 'field_type="voting"';
         }
         $query .= ' WHERE ' . implode($disp_field_where, ' OR ');
         $db->setQuery($query);
         $disp_fields_data = $db->loadObjectList('field_type');
         if ($display_hits || $display_hits_feat) {
             $hitsfield = $disp_fields_data['hits'];
             $hitsfield->parameters = new JRegistry($hitsfield->attribs);
             $has_access_hits = in_array($hitsfield->access, $aid_arr);
         }
         if ($display_voting || $display_voting_feat) {
             $votingfield = $disp_fields_data['voting'];
             $votingfield->parameters = new JRegistry($votingfield->attribs);
             $has_access_voting = in_array($votingfield->access, $aid_arr);
         }
     }
     // get module fields parameters
     $use_fields = $params->get('use_fields', 1);
     $display_label = $params->get('display_label');
     $fields = array_map('trim', explode(',', $params->get('fields')));
     if ($fields[0] == '') {
         $fields = array();
     }
     // get fields that when empty cause an item to be skipped
     $skip_items = (int) $params->get('skip_items', 0);
     $skiponempty_fields = array_map('trim', explode(',', $params->get('skiponempty_fields')));
     if ($skiponempty_fields[0] == '') {
         $skiponempty_fields = array();
     }
     if ($params->get('maxskipcount', 50) > 100) {
         $params->set('maxskipcount', 100);
     }
     $striptags_onempty_fields = $params->get('striptags_onempty_fields');
     $onempty_fields_combination = $params->get('onempty_fields_combination');
     // featured
     $use_fields_feat = $params->get('use_fields_feat', 1);
     $display_label_feat = $params->get('display_label_feat');
     $fields_feat = array_map('trim', explode(',', $params->get('fields_feat')));
     if ($fields_feat[0] == '') {
         $fields_feat = array();
     }
     //$mod_fc_run_times['query_items']= $modfc_jprof->getmicrotime();
     $cat_items_arr = array();
     if (!is_array($ordering)) {
         $ordering = explode(',', $ordering);
     }
     foreach ($ordering as $ord) {
         $items_arr = modFlexicontentHelper::getItems($params, $ord);
         if (empty($items_arr)) {
             continue;
         }
         foreach ($items_arr as $catid => $items) {
             if (!isset($cat_items_arr[$catid])) {
                 $cat_items_arr[$catid] = array();
             }
             for ($i = 0; $i < count($items); $i++) {
                 $items[$i]->featured = $i < $featured ? 1 : 0;
                 $items[$i]->fetching = $ord;
                 $cat_items_arr[$catid][] = $items[$i];
             }
         }
     }
     //$mod_fc_run_times['query_items'] = $modfc_jprof->getmicrotime() - $mod_fc_run_times['query_items'];
     // Impementation of Empty Field Filter.
     // The cost of the following code is minimal.
     // The big time cost goes into rendering the fields ...
     // We need to create the display of the fields before examining if they are empty.
     // The hardcoded limit of max items skipped is 100.
     if ($skip_items && count($skiponempty_fields)) {
         $mod_fc_run_times['empty_fields_filter'] = $modfc_jprof->getmicrotime();
         // 0. Add ONLY skipfields to the list of fields to be rendered
         $fields_list = implode(',', $skiponempty_fields);
         //$skip_params = new JRegistry();
         //$skip_params->set('fields',$fields_list);
         foreach ($cat_items_arr as $catid => $cat_items) {
             // 1. The filtered rows
             $filtered_rows = array();
             $order_count = array();
             // 2. Get field values (we pass null parameters to only retrieve field values and not render (YET) the 'skip-onempty' fields
             FlexicontentFields::getFields($cat_items, 'module', $skip_params = null);
             // 3. Skip Items with empty fields (if this filter is enabled)
             foreach ($cat_items as $i => $item) {
                 //echo "$i . {$item->title}<br/>";
                 // Check to initialize counter for this ordering
                 if (!isset($order_count[$item->fetching])) {
                     $order_count[$item->fetching] = 0;
                 }
                 // Check if enough encountered for this ordering
                 if ($order_count[$item->fetching] >= $count) {
                     continue;
                 }
                 // Initialize skip property ZERO for 'any' and ONE for 'all'
                 $skip_curritem = $onempty_fields_combination == 'any' ? 0 : 1;
                 // Now check for empty field display or empty field values, if so item must be skipped
                 foreach ($skiponempty_fields as $skipfield_name) {
                     if ($skip_items == 2) {
                         // We will check field's display
                         FlexicontentFields::getFieldDisplay($item, $skipfield_name, null, 'display', 'module');
                         $skipfield_data = @$item->fields[$skipfield_name]->display;
                     } else {
                         // We will check field's value
                         $skipfield_iscore = $item->fields[$skipfield_name]->iscore;
                         $skipfield_id = $item->fields[$skipfield_name]->id;
                         $skipfield_data = $skipfield_iscore ? $item->{$skipfield_name} : @$item->fieldvalues[$skipfield_id];
                     }
                     // Strip HTML Tags
                     if ($striptags_onempty_fields) {
                         $skipfield_data = strip_tags($skipfield_data);
                     }
                     // Decide if field is empty
                     $skipfield_isempty = is_array($skipfield_data) ? !count($skipfield_data) : !strlen(trim($skipfield_data));
                     if ($skipfield_isempty) {
                         if ($onempty_fields_combination == 'any') {
                             $skip_curritem = 1;
                             break;
                         }
                     } else {
                         if ($onempty_fields_combination == 'all') {
                             $skip_curritem = 0;
                             break;
                         }
                     }
                 }
                 if ($skip_curritem) {
                     //echo "Skip: $i . {$item->title}<br/>";
                     if (!isset($order_skipcount[$item->fetching])) {
                         $order_skipcount[$item->fetching] = 0;
                     }
                     $order_skipcount[$item->fetching]++;
                     continue;
                 }
                 // 4. Increment counter for item's ordering and Add item to list of displayed items
                 $order_count[$item->fetching]++;
                 $filtered_rows[] = $item;
             }
             $filtered_rows_arr[$catid] = $filtered_rows;
         }
         $mod_fc_run_times['empty_fields_filter'] = $modfc_jprof->getmicrotime() - $mod_fc_run_times['empty_fields_filter'];
     } else {
         $filtered_rows_arr =& $cat_items_arr;
     }
     $mod_fc_run_times['item_list_creation'] = $modfc_jprof->getmicrotime();
     // *** OPTIMIZATION: we only render the fields after skipping unwanted items
     if ($use_fields && count($fields) || $use_fields_feat && count($fields_feat)) {
         $all_fields = array();
         if ($use_fields && count($fields)) {
             $all_fields = array_merge($all_fields, $fields);
         }
         if ($use_fields_feat && count($fields_feat)) {
             $all_fields = array_merge($all_fields, $fields_feat);
         }
         $all_fields = array_unique($all_fields);
         $fields_list = implode(',', $all_fields);
         $params->set('fields', $fields_list);
     }
     // *** OPTIMIZATION: we should create some variables outside the loop ... TODO MORE
     if (($display_hits_feat || $display_hits) && $has_access_hits) {
         $hits_icon = FLEXI_J16GE ? JHTML::image('components/com_flexicontent/assets/images/' . 'user.png', JText::_('FLEXI_HITS_L')) : JHTML::_('image.site', 'user.png', 'components/com_flexicontent/assets/images/', NULL, NULL, JText::_('FLEXI_HITS_L'));
     }
     if ($display_comments_feat || $display_comments) {
         $comments_icon = FLEXI_J16GE ? JHTML::image('components/com_flexicontent/assets/images/' . 'comments.png', JText::_('FLEXI_COMMENTS_L')) : JHTML::_('image.site', 'comments.png', 'components/com_flexicontent/assets/images/', NULL, NULL, JText::_('FLEXI_COMMENTS_L'));
     }
     $option = JRequest::getVar('option');
     $view = JRequest::getVar('view');
     $isflexi_itemview = $option == 'com_flexicontent' && $view == FLEXI_ITEMVIEW;
     $active_item_id = JRequest::getInt('id', 0);
     $lists_arr = array();
     foreach ($filtered_rows_arr as $catid => $filtered_rows) {
         if (empty($filtered_rows)) {
             $rows = array();
         } else {
             if ($use_fields && count($fields) || $use_fields_feat && count($fields_feat)) {
                 $rows = FlexicontentFields::getFields($filtered_rows, 'module', $params);
             } else {
                 $rows =& $filtered_rows;
             }
         }
         // For Debuging
         /*foreach ($order_skipcount as $skipordering => $skipcount) {
         		  echo "SKIPS $skipordering ==> $skipcount<br>\n";
         		}*/
         $lists = array();
         foreach ($ordering as $ord) {
             $lists[$ord] = array();
         }
         $ord = "__start__";
         foreach ($rows as $row) {
             if ($ord != $row->fetching) {
                 // Detect change of next ordering group
                 $ord = $row->fetching;
                 $i = 0;
             }
             if ($row->featured) {
                 // image processing
                 $thumb = '';
                 $thumb_rendered = '';
                 if ($mod_use_image_feat) {
                     if ($mod_image_custom_display) {
                         @(list($fieldname, $varname) = preg_split('/##/', $mod_image_custom_display));
                         $fieldname = trim($fieldname);
                         $varname = trim($varname);
                         $varname = $varname ? $varname : 'display';
                         $thumb_rendered = FlexicontentFields::getFieldDisplay($row, $fieldname, null, $varname, 'module');
                         $src = '';
                     } else {
                         if ($mod_image_custom_url) {
                             @(list($fieldname, $varname) = preg_split('/##/', $mod_image_custom_url));
                             $fieldname = trim($fieldname);
                             $varname = trim($varname);
                             $varname = $varname ? $varname : 'display';
                             $src = FlexicontentFields::getFieldDisplay($row, $fieldname, null, $varname, 'module');
                         } else {
                             if ($mod_image) {
                                 FlexicontentFields::getFieldDisplay($row, $mod_image_name, null, 'display_large_src', 'module');
                                 // just makes sure thumbs are created by requesting a '*_src' display
                                 $img_field =& $row->fields[$mod_image_name];
                                 if ($mod_use_image_feat == 1) {
                                     $src = str_replace(JURI::root(), '', @$img_field->thumbs_src['large'][0]);
                                 } else {
                                     $src = '';
                                     $thumb = @$img_field->thumbs_src[$mod_use_image_feat][0];
                                 }
                                 if (!$src && $mod_image_fallback_img == 1 || $src && $mod_image_fallback_img == 2 && $img_field->using_default_value) {
                                     $src = flexicontent_html::extractimagesrc($row);
                                 }
                             } else {
                                 $src = flexicontent_html::extractimagesrc($row);
                             }
                         }
                     }
                     if (!$thumb && !$src && $mod_default_img_show) {
                         $thumb = $thumb_default_feat;
                     }
                     if ($src) {
                         $h = '&amp;h=' . $mod_height_feat;
                         $w = '&amp;w=' . $mod_width_feat;
                         $aoe = '&amp;aoe=1';
                         $q = '&amp;q=95';
                         $zc = $mod_method_feat ? '&amp;zc=' . $mod_method_feat : '';
                         $ext = strtolower(pathinfo($src, PATHINFO_EXTENSION));
                         $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
                         $conf = $w . $h . $aoe . $q . $zc . $f;
                         $base_url = !preg_match("#^http|^https|^ftp|^/#i", $src) ? JURI::base(true) . '/' : '';
                         $thumb = JURI::base() . 'components/com_flexicontent/librairies/phpthumb/phpThumb.php?src=' . $base_url . $src . $conf;
                     }
                 }
                 $lists[$ord]['featured'][$i] = new stdClass();
                 $lists[$ord]['featured'][$i]->_row = $row;
                 $lists[$ord]['featured'][$i]->id = $row->id;
                 $lists[$ord]['featured'][$i]->is_active_item = $isflexi_itemview && $row->id == $active_item_id;
                 //date
                 if ($display_date_feat == 1) {
                     $dateformat = JText::_($params->get('date_format_feat', 'DATE_FORMAT_LC3'));
                     if ($dateformat == JText::_('custom')) {
                         $dateformat = $params->get('custom_date_format_feat', JText::_('DATE_FORMAT_LC3'));
                     }
                     $date_fields_feat = $params->get('date_fields_feat', array('created'));
                     $date_fields_feat = !is_array($date_fields_feat) ? array($date_fields_feat) : $date_fields_feat;
                     $lists[$ord]['featured'][$i]->date_created = "";
                     if (in_array('created', $date_fields_feat)) {
                         // Created
                         $lists[$ord]['featured'][$i]->date_created .= $params->get('date_label_feat', 1) ? '<span class="date_label_feat">' . JText::_('FLEXI_DATE_CREATED') . '</span> ' : '';
                         $lists[$ord]['featured'][$i]->date_created .= '<span class="date_value_feat">' . JHTML::_('date', $row->created, $dateformat) . '</span>';
                     }
                     $lists[$ord]['featured'][$i]->date_modified = "";
                     if (in_array('modified', $date_fields_feat)) {
                         // Modified
                         $lists[$ord]['featured'][$i]->date_modified .= $params->get('date_label_feat', 1) ? '<span class="date_label_feat">' . JText::_('FLEXI_DATE_MODIFIED') . '</span> ' : '';
                         $modified_date = $row->modified != $db->getNullDate() ? JHTML::_('date', $row->modified, $dateformat) : JText::_('FLEXI_DATE_NEVER');
                         $lists[$ord]['featured'][$i]->date_modified .= '<span class="date_value_feat">' . $modified_date . '</span>';
                     }
                 }
                 $lists[$ord]['featured'][$i]->image_rendered = $thumb_rendered;
                 $lists[$ord]['featured'][$i]->image = $thumb;
                 $lists[$ord]['featured'][$i]->hits = $row->hits;
                 $lists[$ord]['featured'][$i]->hits_rendered = '';
                 if ($display_hits_feat && $has_access_hits) {
                     FlexicontentFields::loadFieldConfig($hitsfield, $row);
                     $lists[$ord]['featured'][$i]->hits_rendered .= $params->get('hits_label_feat') ? '<span class="hits_label_feat">' . JText::_($hitsfield->label) . '</span> ' : '';
                     $lists[$ord]['featured'][$i]->hits_rendered .= $hits_icon;
                     $lists[$ord]['featured'][$i]->hits_rendered .= ' (' . $row->hits . (!$params->get('hits_label_feat') ? ' ' . JTEXT::_('FLEXI_HITS_L') : '') . ')';
                 }
                 $lists[$ord]['featured'][$i]->voting = '';
                 if ($display_voting_feat && $has_access_voting) {
                     FlexicontentFields::loadFieldConfig($votingfield, $row);
                     $lists[$ord]['featured'][$i]->voting .= $params->get('voting_label_feat') ? '<span class="voting_label_feat">' . JText::_($votingfield->label) . '</span> ' : '';
                     $lists[$ord]['featured'][$i]->voting .= '<div class="voting_value_feat">' . flexicontent_html::ItemVoteDisplay($votingfield, $row->id, $row->rating_sum, $row->rating_count, 'main', '', $params->get('vote_stars_feat', 1), $params->get('allow_vote_feat', 0), $params->get('vote_counter_feat', 1), !$params->get('voting_label_feat')) . '</div>';
                 }
                 if ($display_comments_feat) {
                     $lists[$ord]['featured'][$i]->comments = $row->comments_total;
                     $lists[$ord]['featured'][$i]->comments_rendered = $params->get('comments_label_feat') ? '<span class="comments_label_feat">' . JText::_('FLEXI_COMMENTS') . '</span> ' : '';
                     $lists[$ord]['featured'][$i]->comments_rendered .= $comments_icon;
                     $lists[$ord]['featured'][$i]->comments_rendered .= ' (' . $row->comments_total . (!$params->get('comments_label_feat') ? ' ' . JTEXT::_('FLEXI_COMMENTS_L') : '') . ')';
                 }
                 $lists[$ord]['featured'][$i]->catid = $row->catid;
                 $lists[$ord]['featured'][$i]->itemcats = explode(",", $row->itemcats);
                 $lists[$ord]['featured'][$i]->link = JRoute::_(FlexicontentHelperRoute::getItemRoute($row->slug, $row->categoryslug, $forced_itemid, $row) . ($method_curlang == 1 ? "&lang=" . substr($row->language, 0, 2) : ""));
                 $lists[$ord]['featured'][$i]->title = strlen($row->title) > $cuttitle_feat ? JString::substr($row->title, 0, $cuttitle_feat) . '...' : $row->title;
                 $lists[$ord]['featured'][$i]->alias = $row->alias;
                 $lists[$ord]['featured'][$i]->fulltitle = $row->title;
                 $lists[$ord]['featured'][$i]->text = $mod_do_stripcat_feat ? flexicontent_html::striptagsandcut($row->introtext, $mod_cut_text_feat) : $row->introtext;
                 $lists[$ord]['featured'][$i]->typename = $row->typename;
                 $lists[$ord]['featured'][$i]->access = $row->access;
                 $lists[$ord]['featured'][$i]->featured = 1;
                 if ($use_fields_feat && @$row->fields && $fields_feat) {
                     $lists[$ord]['featured'][$i]->fields = array();
                     foreach ($fields_feat as $field) {
                         if (!isset($row->fields[$field])) {
                             continue;
                         }
                         /*$lists[$ord]['featured'][$i]->fields[$field] = new stdClass();
                         		$lists[$ord]['featured'][$i]->fields[$field]->display 	= @$row->fields[$field]->display ? $row->fields[$field]->display : '';
                         		$lists[$ord]['featured'][$i]->fields[$field]->name = $row->fields[$field]->name;
                         		$lists[$ord]['featured'][$i]->fields[$field]->id   = $row->fields[$field]->id;*/
                         // Expose field to the module template  ... the template should NOT modify this ...
                         if (!isset($row->fields[$field]->display)) {
                             $row->fields[$field]->display = '';
                         }
                         $lists[$ord]['featured'][$i]->fields[$field] = $row->fields[$field];
                     }
                 }
                 $i++;
             } else {
                 // image processing
                 $thumb = '';
                 $thumb_rendered = '';
                 if ($mod_use_image) {
                     if ($mod_image_custom_display) {
                         @(list($fieldname, $varname) = preg_split('/##/', $mod_image_custom_display));
                         $fieldname = trim($fieldname);
                         $varname = trim($varname);
                         $varname = $varname ? $varname : 'display';
                         $thumb_rendered = FlexicontentFields::getFieldDisplay($row, $fieldname, null, $varname, 'module');
                         $src = '';
                         // Clear src no rendering needed
                     } else {
                         if ($mod_image_custom_url) {
                             @(list($fieldname, $varname) = preg_split('/##/', $mod_image_custom_url));
                             $fieldname = trim($fieldname);
                             $varname = trim($varname);
                             $varname = $varname ? $varname : 'display';
                             $src = FlexicontentFields::getFieldDisplay($row, $fieldname, null, $varname, 'module');
                         } else {
                             if ($mod_image) {
                                 FlexicontentFields::getFieldDisplay($row, $mod_image_name, null, 'display_large_src', 'module');
                                 // just makes sure thumbs are created by requesting a '*_src' display
                                 $img_field =& $row->fields[$mod_image_name];
                                 if ($mod_use_image == 1) {
                                     $src = str_replace(JURI::root(), '', @$img_field->thumbs_src['large'][0]);
                                 } else {
                                     $src = '';
                                     $thumb = @$img_field->thumbs_src[$mod_use_image][0];
                                 }
                                 if (!$src && $mod_image_fallback_img == 1 || $src && $mod_image_fallback_img == 2 && $img_field->using_default_value) {
                                     $src = flexicontent_html::extractimagesrc($row);
                                 }
                             } else {
                                 $src = flexicontent_html::extractimagesrc($row);
                             }
                         }
                     }
                     if (!$thumb && !$src && $mod_default_img_show) {
                         $thumb = $thumb_default;
                     }
                     if ($src) {
                         $h = '&amp;h=' . $mod_height;
                         $w = '&amp;w=' . $mod_width;
                         $aoe = '&amp;aoe=1';
                         $q = '&amp;q=95';
                         $zc = $mod_method ? '&amp;zc=' . $mod_method : '';
                         $ext = strtolower(pathinfo($src, PATHINFO_EXTENSION));
                         $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
                         $conf = $w . $h . $aoe . $q . $zc . $f;
                         $base_url = !preg_match("#^http|^https|^ftp|^/#i", $src) ? JURI::base(true) . '/' : '';
                         $thumb = JURI::base() . 'components/com_flexicontent/librairies/phpthumb/phpThumb.php?src=' . $base_url . $src . $conf;
                     }
                 }
                 // START population of item's custom properties
                 $lists[$ord]['standard'][$i] = new stdClass();
                 $lists[$ord]['standard'][$i]->_row = $row;
                 $lists[$ord]['standard'][$i]->id = $row->id;
                 $lists[$ord]['standard'][$i]->is_active_item = $isflexi_itemview && $row->id == $active_item_id;
                 //date
                 if ($display_date == 1) {
                     $dateformat = JText::_($params->get('date_format', 'DATE_FORMAT_LC3'));
                     if ($dateformat == JText::_('custom')) {
                         $dateformat = $params->get('custom_date_format', JText::_('DATE_FORMAT_LC3'));
                     }
                     $date_fields = $params->get('date_fields', array('created'));
                     $date_fields = !is_array($date_fields) ? array($date_fields) : $date_fields;
                     $lists[$ord]['standard'][$i]->date_created = "";
                     if (in_array('created', $date_fields)) {
                         // Created
                         $lists[$ord]['standard'][$i]->date_created .= $params->get('date_label', 1) ? '<span class="date_label">' . JText::_('FLEXI_DATE_CREATED') . '</span> ' : '';
                         $lists[$ord]['standard'][$i]->date_created .= '<span class="date_value">' . JHTML::_('date', $row->created, $dateformat) . '</span>';
                     }
                     $lists[$ord]['standard'][$i]->date_modified = "";
                     if (in_array('modified', $date_fields)) {
                         // Modified
                         $lists[$ord]['standard'][$i]->date_modified .= $params->get('date_label', 1) ? '<span class="date_label">' . JText::_('FLEXI_DATE_MODIFIED') . '</span> ' : '';
                         $modified_date = $row->modified != $db->getNullDate() ? JHTML::_('date', $row->modified, $dateformat) : JText::_('FLEXI_DATE_NEVER');
                         $lists[$ord]['standard'][$i]->date_modified .= '<span class="date_value_feat">' . $modified_date . '</span>';
                     }
                 }
                 $lists[$ord]['standard'][$i]->image_rendered = $thumb_rendered;
                 $lists[$ord]['standard'][$i]->image = $thumb;
                 $lists[$ord]['standard'][$i]->hits = $row->hits;
                 $lists[$ord]['standard'][$i]->hits_rendered = '';
                 if ($display_hits && $has_access_hits) {
                     FlexicontentFields::loadFieldConfig($hitsfield, $row);
                     $lists[$ord]['standard'][$i]->hits_rendered .= $params->get('hits_label') ? '<span class="hits_label">' . JText::_($hitsfield->label) . '</span> ' : '';
                     $lists[$ord]['standard'][$i]->hits_rendered .= $hits_icon;
                     $lists[$ord]['standard'][$i]->hits_rendered .= ' (' . $row->hits . (!$params->get('hits_label') ? ' ' . JTEXT::_('FLEXI_HITS_L') : '') . ')';
                 }
                 $lists[$ord]['standard'][$i]->voting = '';
                 if ($display_voting && $has_access_voting) {
                     FlexicontentFields::loadFieldConfig($votingfield, $row);
                     $lists[$ord]['standard'][$i]->voting .= $params->get('voting_label') ? '<span class="voting_label">' . JText::_($votingfield->label) . '</span> ' : '';
                     $lists[$ord]['standard'][$i]->voting .= '<div class="voting_value">' . flexicontent_html::ItemVoteDisplay($votingfield, $row->id, $row->rating_sum, $row->rating_count, 'main', '', $params->get('vote_stars', 1), $params->get('allow_vote', 0), $params->get('vote_counter', 1), !$params->get('voting_label')) . '</div>';
                 }
                 if ($display_comments) {
                     $lists[$ord]['standard'][$i]->comments = $row->comments_total;
                     $lists[$ord]['standard'][$i]->comments_rendered = $params->get('comments_label') ? '<span class="comments_label">' . JText::_('FLEXI_COMMENTS') . '</span> ' : '';
                     $lists[$ord]['standard'][$i]->comments_rendered .= $comments_icon;
                     $lists[$ord]['standard'][$i]->comments_rendered .= ' (' . $row->comments_total . (!$params->get('comments_label') ? ' ' . JTEXT::_('FLEXI_COMMENTS_L') : '') . ')';
                 }
                 $lists[$ord]['standard'][$i]->catid = $row->catid;
                 $lists[$ord]['standard'][$i]->itemcats = explode(",", $row->itemcats);
                 $lists[$ord]['standard'][$i]->link = JRoute::_(FlexicontentHelperRoute::getItemRoute($row->slug, $row->categoryslug, $forced_itemid, $row) . ($method_curlang == 1 ? "&lang=" . substr($row->language, 0, 2) : ""));
                 $lists[$ord]['standard'][$i]->title = strlen($row->title) > $cuttitle ? JString::substr($row->title, 0, $cuttitle) . '...' : $row->title;
                 $lists[$ord]['standard'][$i]->alias = $row->alias;
                 $lists[$ord]['standard'][$i]->fulltitle = $row->title;
                 $lists[$ord]['standard'][$i]->text = $mod_do_stripcat ? flexicontent_html::striptagsandcut($row->introtext, $mod_cut_text) : $row->introtext;
                 $lists[$ord]['standard'][$i]->typename = $row->typename;
                 $lists[$ord]['standard'][$i]->access = $row->access;
                 $lists[$ord]['standard'][$i]->featured = 0;
                 if ($use_fields && @$row->fields && $fields) {
                     $lists[$ord]['standard'][$i]->fields = array();
                     foreach ($fields as $field) {
                         if (!isset($row->fields[$field])) {
                             continue;
                         }
                         /*$lists[$ord]['standard'][$i]->fields[$field] = new stdClass();
                         		$lists[$ord]['standard'][$i]->fields[$field]->display 	= @$row->fields[$field]->display ? $row->fields[$field]->display : '';
                         		$lists[$ord]['standard'][$i]->fields[$field]->name = $row->fields[$field]->name;
                         		$lists[$ord]['standard'][$i]->fields[$field]->id   = $row->fields[$field]->id;*/
                         // Expose field to the module template  ... the template should NOT modify this ...
                         if (!isset($row->fields[$field]->display)) {
                             $row->fields[$field]->display = '';
                         }
                         $lists[$ord]['standard'][$i]->fields[$field] = $row->fields[$field];
                         // Expose field to the module template  ... but template may modify it ...
                     }
                 }
                 $i++;
             }
         }
         $lists_arr[$catid] = $lists;
     }
     $mod_fc_run_times['item_list_creation'] = $modfc_jprof->getmicrotime() - $mod_fc_run_times['item_list_creation'];
     return $lists_arr;
 }
Exemple #19
0
 /**
  * Creates the RSS for the View
  *
  * @since 1.0
  */
 function display($tpl = null)
 {
     $db = JFactory::getDBO();
     $doc = JFactory::getDocument();
     $app = JFactory::getApplication();
     $params = $this->get('Params');
     $doc->link = JRoute::_(FlexicontentHelperRoute::getCategoryRoute(JRequest::getVar('cid', null, '', 'int')));
     $category = $this->get('Category');
     // Prepare query to match feed data
     JRequest::setVar('limit', $params->get('feed_limit'));
     // Force a specific limit, this will be moved to the model
     $params->set('orderby', $params->get('feed_orderby', 'rdate'));
     $params->set('orderbycustomfield', $params->get('feed_orderbycustomfield', 1));
     $params->set('orderbycustomfieldid', $params->get('feed_orderbycustomfieldid', 0));
     $params->set('orderbycustomfielddir', $params->get('feed_orderbycustomfielddir', 'ASC'));
     $params->set('orderbycustomfieldint', $params->get('feed_orderbycustomfieldint', 0));
     $params->set('orderby_2nd', $params->get('feed_orderby', 'alpha'));
     $params->set('orderbycustomfield_2nd', $params->get('feed_orderbycustomfield_2nd', 1));
     $params->set('orderbycustomfieldid_2nd', $params->get('feed_orderbycustomfieldid_2nd', 0));
     $params->set('orderbycustomfielddir_2nd', $params->get('feed_orderbycustomfielddir_2nd', 'ASC'));
     $params->set('orderbycustomfieldint_2nd', $params->get('feed_orderbycustomfieldint_2nd', 0));
     $model = $this->getModel();
     $model->setState('limit', $params->get('feed_limit', $model->getState('limit')));
     $rows = $this->get('Data');
     $feed_summary = $params->get('feed_summary', 0);
     $feed_summary_cut = $params->get('feed_summary_cut', 200);
     $feed_use_image = $params->get('feed_use_image', 1);
     $feed_link_image = $params->get('feed_link_image', 1);
     $feed_image_source = $params->get('feed_image_source', '');
     $feed_image_size = $params->get('feed_image_size', '');
     $feed_image_method = $params->get('feed_image_method', 1);
     $feed_image_width = $params->get('feed_image_width', 100);
     $feed_image_height = $params->get('feed_image_height', 80);
     // Retrieve default image for the image field
     if ($feed_use_image && $feed_image_source) {
         $query = 'SELECT attribs, name FROM #__flexicontent_fields WHERE id = ' . (int) $feed_image_source;
         $db->setQuery($query);
         $image_dbdata = $db->loadObject();
         //$image_dbdata->params = FLEXI_J16GE ? new JRegistry($image_dbdata->params) : new JParameter($image_dbdata->params);
         $img_size_map = array('l' => 'large', 'm' => 'medium', 's' => 'small', '' => '');
         $img_field_size = $img_size_map[$feed_image_size];
         $img_field_name = $image_dbdata->name;
     }
     // TODO render and add extra fields here ... maybe via special display function for feeds view
     $extra_fields = $params->get('feed_extra_fields', '');
     $extra_fields = array_unique(preg_split("/\\s*,\\s*/u", $extra_fields));
     if ($extra_fields) {
         foreach ($extra_fields as $fieldname) {
             // Render given field for ALL ITEMS
             FlexicontentFields::getFieldDisplay($rows, $fieldname, $values = null, $method = 'display');
         }
     }
     foreach ($rows as $row) {
         // strip html from feed item title
         $title = $this->escape($row->title);
         $title = html_entity_decode($title);
         // url link to article
         // & used instead of &amp; as this is converted by feed creator
         $link = JRoute::_(FlexicontentHelperRoute::getItemRoute($row->slug, $category->slug, 0, $row));
         // strip html from feed item description text
         $description = $feed_summary ? $row->introtext . $row->fulltext : $row->introtext;
         $description = flexicontent_html::striptagsandcut($description, $feed_summary_cut);
         if ($feed_use_image) {
             // feed image is enabled
             $src = '';
             $thumb = '';
             if ($feed_image_source) {
                 // case 1 use an image field
                 FlexicontentFields::getFieldDisplay($row, $img_field_name, null, 'display', 'module');
                 $img_field = $row->fields[$img_field_name];
                 if (!$img_field_size) {
                     $src = str_replace(JURI::root(), '', $img_field->thumbs_src['large'][0]);
                 } else {
                     $src = '';
                     $thumb = $img_field->thumbs_src[$img_field_size][0];
                 }
             } else {
                 // case 2 extract from item
                 $src = flexicontent_html::extractimagesrc($row);
             }
             $RESIZE_FLAG = !$feed_image_source || !$img_field_size;
             if ($src && $RESIZE_FLAG) {
                 // Resize image when src path is set and RESIZE_FLAG: (a) using image extracted from item main text OR (b) not using image field's already created thumbnails
                 $h = '&amp;h=' . $feed_image_height;
                 $w = '&amp;w=' . $feed_image_width;
                 $aoe = '&amp;aoe=1';
                 $q = '&amp;q=95';
                 $zc = $feed_image_method ? '&amp;zc=' . $feed_image_method : '';
                 $ext = pathinfo($src, PATHINFO_EXTENSION);
                 $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
                 $conf = $w . $h . $aoe . $q . $zc . $f;
                 $base_url = !preg_match("#^http|^https|^ftp|^/#i", $src) ? JURI::base(true) . '/' : '';
                 $thumb = JURI::base(true) . '/components/com_flexicontent/librairies/phpthumb/phpThumb.php?src=' . $base_url . $src . $conf;
             } else {
                 // Do not resize image when (a) image src path not set or (b) using image field's already created thumbnails
             }
             if ($thumb) {
                 $description = "\n\t  \t\t\t<div class='feed-description'>\n\t\t  \t\t\t<a class='feed-readmore' target='_blank' href='" . $link . "'>\n\t\t  \t\t\t\t<img src='" . $thumb . "' alt='" . $title . "' title='" . $title . "' align='left'/>\n\t\t  \t\t\t</a>\n\t\t  \t\t\t<p>" . $description . "</p>\n\t\t  \t\t</div>";
             }
         }
         if ($extra_fields) {
             foreach ($extra_fields as $fieldname) {
                 if ($row->fields[$fieldname]->display) {
                     $description .= '<br/><b>' . $row->fields[$fieldname]->label . ":</b> " . $row->fields[$fieldname]->display;
                 }
             }
         }
         //$author = $row->created_by_alias ? $row->created_by_alias : $row->author;
         @($date = $row->created ? date('r', strtotime($row->created)) : '');
         // load individual item creator class
         $item = new JFeedItem();
         $item->title = $title;
         $item->link = $link;
         $item->description = $description;
         $item->date = $date;
         //$item->author    = $author;
         $item->category = $this->escape($category->title);
         // loads item info into rss array
         $doc->addItem($item);
     }
 }
 /**
  * Utility Function:
  * Force frontend specific redirestions most notably redirecting the joomla ARTICLE VIEW to the FLEXIcontent ITEM VIEW
  * Some special cases are handled e.g. redirecting the joomla article form to FLEXIcontent item form
  *
  * @access public
  * @return void
  */
 function redirectSiteComContent()
 {
     $app = JFactory::getApplication();
     $option = JRequest::getCMD('option');
     $view = JRequest::getCMD('view');
     $db = JFactory::getDBO();
     // Let's Redirect/Reroute Joomla's article view & form to FLEXIcontent item view & form respectively !!
     // NOTE: we do not redirect/reroute Joomla's category views (blog,list,featured for J2.5 etc),
     //       thus site administrator can still utilize them
     if ($option == 'com_content' && ($view == 'article' || $view == FLEXI_ITEMVIEW || $view == 'form')) {
         // In J2.5, in case of form we need to use a_id instead of id, this will also be set in HTTP Request too and JRouter too
         $id = JRequest::getInt('id');
         $id = $view == 'form' ? JRequest::getInt('a_id') : $id;
         // Get article category id, if it is not already in url
         $catid = JRequest::getInt('catid');
         if (!$catid) {
             $db->setQuery('SELECT catid FROM #__content WHERE id = ' . $id);
             $catid = $db->loadResult();
         }
         $in_limits = $catid >= FLEXI_LFT_CATEGORY && $catid <= FLEXI_RGT_CATEGORY;
         // Allow Joomla article view for non-bound items or for specific content types
         if ($in_limits && $view == 'article') {
             $db->setQuery('SELECT	attribs' . ' FROM #__flexicontent_types AS ty ' . ' JOIN #__flexicontent_items_ext AS ie ON ie.type_id = ty.id ' . ' WHERE ie.item_id = ' . $id);
             $type_params = $db->loadResult();
             if (!$type_params) {
                 $in_limits = false;
             } else {
                 $type_params = new JRegistry($type_params);
                 $in_limits = $type_params->get('allow_jview') == 0;
                 // Allow viewing by article view, if so configured
             }
         }
         if (empty($in_limits)) {
             return;
         }
         if ($this->params->get('redirect_method_fe', 1) == 1) {
             // Set new request variables:
             // NOTE: we only need to set REQUEST variable that must be changed,
             //       but setting any other variables to same value will not hurt
             if ($view == 'article' || $view == FLEXI_ITEMVIEW) {
                 $newRequest = array('option' => $this->extension, 'view' => FLEXI_ITEMVIEW, 'Itemid' => JRequest::getInt('Itemid'), 'lang' => JRequest::getCmd('lang'));
             } else {
                 if ($view == 'form') {
                     $newRequest = array('option' => $this->extension, 'view' => FLEXI_ITEMVIEW, 'task' => 'edit', 'layout' => 'form', 'id' => $id, 'Itemid' => JRequest::getInt('Itemid'), 'lang' => JRequest::getCmd('lang'));
                 } else {
                     // Unknown CASE ?? unreachable ?
                     return;
                 }
             }
             JRequest::set($newRequest, 'get');
             // Set variable also in the router, for best compatibility
             $router = $app->getRouter();
             $router->setVars($newRequest, false);
             //$app->enqueueMessage( "Set com_flexicontent item view instead of com_content article view", 'message');
         } else {
             if ($view == 'form') {
                 $urlItem = 'index.php?option=' . $this->extension . '&view=' . FLEXI_ITEMVIEW . '&id=' . $id . '&task=edit&layout=form';
             } else {
                 // Include the route helper files
                 require_once JPATH_SITE . DS . 'components' . DS . 'com_content' . DS . 'helpers' . DS . 'route.php';
                 require_once JPATH_SITE . DS . 'components' . DS . 'com_flexicontent' . DS . 'helpers' . DS . 'route.php';
                 $itemslug = JRequest::getVar('id');
                 $catslug = JRequest::getVar('catid');
                 // Warning current menu item id must not be passed to the routing functions since it points to com_content, and thus it will break FC SEF URLs
                 $urlItem = $catslug ? FlexicontentHelperRoute::getItemRoute($itemslug, $catslug) : FlexicontentHelperRoute::getItemRoute($itemslug);
                 $urlItem = JRoute::_($urlItem);
             }
             //$app->enqueueMessage( "Redirected to com_flexicontent item view instead of com_content article view", 'message');
             $app->redirect($urlItem);
         }
     }
 }
Exemple #21
0
 /**
  * Method to CHECK item's -VIEWING- ACCESS, this could be moved to the controller,
  * if we do this, then we must check the view variable, because DISPLAY() CONTROLLER TASK
  * is shared among all views ... or create a separate FRONTEND controller for the ITEM VIEW
  *
  * @access	private
  * @return	array
  * @since	1.5
  */
 function _check_viewing_access($version = false)
 {
     global $globalcats;
     $app = JFactory::getApplication();
     $user = JFactory::getUser();
     $session = JFactory::getSession();
     $aid = (int) $user->get('aid');
     $gid = (int) $user->get('gid');
     $cid = $this->_cid;
     $params = $this->_item->parameters;
     $cparams = $this->_cparams;
     $fcreturn = serialize(array('id' => @$this->_item->id, 'cid' => $cid));
     // a special url parameter, used by some SEF code
     $referer = @$_SERVER['HTTP_REFERER'];
     // the previously viewed page (refer)
     // a basic item title string
     $title_str = "<br />" . JText::_('FLEXI_TITLE') . ": " . $this->_item->title . '[id: ' . $this->_item->id . ']';
     // Since we will check access for VIEW (=read) only, we skip checks if TASK Variable is set,
     // the edit() or add() or other controller task, will be responsible for checking permissions.
     if (@$this->_item->id && !JRequest::getVar('task', false) && JRequest::getVar('view') == FLEXI_ITEMVIEW) {
         //*************************************************************
         // STEP A: Calculate ownership, edit permission and read access
         // (a) isOwner, (b) canedititem, (c) canviewitem
         //*************************************************************
         // (a) Calculate if owned by current user
         $isOwner = $this->_item->created_by == $user->get('id');
         // (b) Calculate edit access ...
         // NOTE: we will allow view access if current user can edit the item (but set a warning message about it, see bellow)
         $canedititem = $params->get('access-edit');
         $caneditstate = $params->get('access-edit-state');
         if (!$caneditstate) {
             // Item not editable, check if item is editable till logoff
             if ($session->has('rendered_uneditable', 'flexicontent')) {
                 $rendered_uneditable = $session->get('rendered_uneditable', array(), 'flexicontent');
                 $canedititem = isset($rendered_uneditable[$this->_item->id]);
             }
         }
         // (c) Calculate read access ...
         $canviewitem = $params->get('access-view');
         // *********************************************************************************
         // STEP B: Calculate SOME ITEM PUBLICATION STATE FLAGS, used to decide if current item is active
         // FLAGS: item_is_published, item_is_scheduled, item_is_expired, cats_are_published
         // *********************************************************************************
         $item_is_published = $this->_item->state == 1 || $this->_item->state == -5 || $this->_item->state == (FLEXI_J16GE ? 2 : -1);
         $item_is_scheduled = $this->_item->publication_scheduled;
         $item_is_expired = $this->_item->publication_expired;
         if ($cid) {
             // cid is set, check state of current item category only
             // NOTE:  J1.6+ all ancestor categories from current one to the root, for J1.5 only the current one ($cid)
             if (!isset($this->_item->ancestor_cats_published)) {
                 $ancestor_cats_published = true;
                 foreach ($globalcats[$cid]->ancestorsarray as $pcid) {
                     $ancestor_cats_published = $ancestor_cats_published && $globalcats[$pcid]->published == 1;
                 }
                 $this->_item->ancestor_cats_published = $ancestor_cats_published;
             }
             $cats_are_published = $this->_item->ancestor_cats_published;
             //$this->_item->catpublished;
             $cats_np_err_mssg = JText::sprintf('FLEXI_CONTENT_UNAVAILABLE_ITEM_CURRCAT_UNPUBLISHED', $cid);
         } else {
             // cid is not set, we have no current category, the item is visible if it belongs to at one published category
             $itemcats = $this->_item->categories;
             $cats_are_published = true;
             foreach ($itemcats as $catid) {
                 if (!isset($globalcats[$catid])) {
                     continue;
                 }
                 $cats_are_published |= $globalcats[$catid]->published;
                 // For J1.6+ check all ancestor categories from current one to the root
                 foreach ($globalcats[$catid]->ancestorsarray as $pcid) {
                     $cats_are_published = $cats_are_published && $globalcats[$pcid]->published == 1;
                 }
             }
             $cats_np_err_mssg = JText::_('FLEXI_CONTENT_UNAVAILABLE_ITEM_ALLCATS_UNPUBLISHED');
         }
         // Calculate if item is active ... and viewable is also it's (current or All) categories are published
         $item_active = $item_is_published && !$item_is_scheduled && !$item_is_expired;
         $item_n_cat_active = $item_active && $cats_are_published;
         $previewing_and_unlogged = $version && $user->guest;
         // this is a flag indicates to redirect to login instead of 404 error
         $ignore_publication = $canedititem || $caneditstate || $isOwner || $previewing_and_unlogged;
         $inactive_notice_set = false;
         $item_state_pending = $this->_item->state == -3;
         $item_state_draft = $this->_item->state == -4;
         //***********************************************************************************************************************
         // STEP C: CHECK item state, if publication state is not ignored terminate with 404 NOT found, otherwise add a notice
         // NOTE: Asking all users to login when item is not active maybe wrong approach, so instead we raise 404 error, but we
         // will ask them to login only if previewing a latest or specific version (so ignore publication FLAG includes this case)
         // (a) Check that item is PUBLISHED (1,-5) or ARCHIVED (-1)
         // (b) Check that item has expired publication date
         // (c) Check that item has scheduled publication date
         // (d) Check that current item category or all items categories are published
         //***********************************************************************************************************************
         // (a) Check that item is PUBLISHED (1,-5) or ARCHIVED (-1)
         if (!$caneditstate && ($item_state_pending || $item_state_draft) && $isOwner) {
             // SPECIAL workflow case, regardless of (view/edit privilege), allow users to view unpublished owned content, (a) if waiting for approval, or (b) if can request approval
             $inactive_notice_set = true;
         } else {
             if (!$item_is_published && !$ignore_publication) {
                 // Raise error that the item is unpublished
                 $msg = JText::_('FLEXI_CONTENT_UNAVAILABLE_ITEM_UNPUBLISHED') . $title_str;
                 if (FLEXI_J16GE) {
                     throw new Exception($msg, 404);
                 } else {
                     JError::raiseError(404, $msg);
                 }
             } else {
                 if (!$item_is_published && !$inactive_notice_set) {
                     // Item edittable, set warning that ...
                     JError::raiseNotice(404, JText::_('FLEXI_CONTENT_UNAVAILABLE_ITEM_UNPUBLISHED'));
                     $inactive_notice_set = true;
                 }
             }
         }
         // NOTE: First, we check for expired publication, since if item expired, scheduled publication is meaningless
         // (b) Check that item has expired publication date
         if ($item_is_expired && !$ignore_publication) {
             // Raise error that the item is scheduled for publication
             $msg = JText::_('FLEXI_CONTENT_UNAVAILABLE_ITEM_EXPIRED') . $title_str;
             if (FLEXI_J16GE) {
                 throw new Exception($msg, 404);
             } else {
                 JError::raiseError(404, $msg);
             }
         } else {
             if ($item_is_expired && !$inactive_notice_set) {
                 // Item edittable, set warning that ...
                 JError::raiseNotice(404, JText::_('FLEXI_CONTENT_UNAVAILABLE_ITEM_EXPIRED'));
                 $inactive_notice_set = true;
             }
         }
         // (c) Check that item has scheduled publication date
         if ($item_is_scheduled && !$ignore_publication) {
             // Raise error that the item is scheduled for publication
             $msg = JText::_('FLEXI_CONTENT_UNAVAILABLE_ITEM_SCHEDULED') . $title_str;
             if (FLEXI_J16GE) {
                 throw new Exception($msg, 404);
             } else {
                 JError::raiseError(404, $msg);
             }
         } else {
             if ($item_is_scheduled && !$inactive_notice_set) {
                 // Item edittable, set warning that ...
                 JError::raiseNotice(404, JText::_('FLEXI_CONTENT_UNAVAILABLE_ITEM_SCHEDULED'));
                 $inactive_notice_set = true;
             }
         }
         // (d) Check that current item category or all items categories are published
         if (!$cats_are_published && !$ignore_publication) {
             // Terminate execution with a HTTP not-found Server Error
             $msg = $cats_np_err_mssg . $title_str;
             if (FLEXI_J16GE) {
                 throw new Exception($msg, 404);
             } else {
                 JError::raiseError(404, $msg);
             }
         } else {
             if (!$cats_are_published && !$inactive_notice_set) {
                 // Item edittable, set warning that item's (ancestor) category is unpublished
                 JError::raiseNotice(404, $cats_np_err_mssg);
                 $inactive_notice_set = true;
             }
         }
         //*******************************************************************************************
         // STEP D: CHECK viewing access in relation to if user being logged and being owner / editor
         // (a) redirect user previewing a non-current item version, to either current item version or to refer if has no edit permission
         // (b) redirect item owner to previous page if user has no access (read/edit) to the item
         // (c) redirect unlogged user to login, so that user can possible login to privileged account
         // (d) redirect unauthorized logged user to the unauthorized page (if this is set)
         // (e) finally raise a 403 forbidden Server Error if user is unauthorized to access item
         //*******************************************************************************************
         // SPECIAL case when previewing an non-current version of an item, this is allowed only if user can edit the item
         $current_version = FLEXIUtilities::getCurrentVersions($this->_id, true);
         // Get current item version
         if ($version && $version != $current_version && !$canedititem && !$previewing_and_unlogged) {
             // (a) redirect user previewing a non-current item version, to either current item version or to refer if has no edit permission
             JError::raiseNotice(403, JText::_('FLEXI_ALERTNOTAUTH_PREVIEW_UNEDITABLE') . "<br />" . JText::_('FLEXI_ALERTNOTAUTH_TASK'));
             if ($item_n_cat_active && $canviewitem) {
                 $app->redirect(JRoute::_(FlexicontentHelperRoute::getItemRoute($this->_item->slug, $this->_item->categoryslug, 0, $this->_item)));
             } else {
                 $app->redirect($referer);
                 // Item not viewable OR no view access, redirect to refer page
             }
         } else {
             if (!$item_n_cat_active && !$previewing_and_unlogged) {
                 if (!$caneditstate && ($item_state_pending || $item_state_draft) && $isOwner) {
                     // no redirect, SET message to owners, to wait for approval or to request approval of their content
                     $app->enqueueMessage(JText::_($item_state_pending ? 'FLEXI_ALERT_VIEW_OWN_PENDING_STATE' : 'FLEXI_ALERT_VIEW_OWN_DRAFT_STATE'), 'notice');
                 } else {
                     if (!$canedititem && !$caneditstate && $isOwner) {
                         // (b) redirect item owner to previous page if user cannot access (read/edit) the item
                         JError::raiseNotice(403, JText::_($item_state_pending ? 'FLEXI_ALERTNOTAUTH_VIEW_OWN_PENDING' : 'FLEXI_ALERTNOTAUTH_VIEW_OWN_UNPUBLISHED'));
                         $app->redirect($referer);
                     } else {
                         if ($canedititem || $caneditstate) {
                             // no redirect, SET notice to the editors, that they are viewing unreadable content because they can edit the item
                             $app->enqueueMessage(JText::_('FLEXI_CONTENT_ACCESS_ALLOWED_BECAUSE_EDITABLE_PUBLISHABLE'), 'notice');
                         } else {
                             $app->enqueueMessage('INTERNAL ERROR: item inactive but checks were ignored despite current user not begin item owner or item assigned editor', 'notice');
                             $app->redirect($referer);
                         }
                     }
                 }
             } else {
                 if (!$canviewitem && !$canedititem || !$item_n_cat_active) {
                     if ($user->guest) {
                         // (c) redirect unlogged user to login, so that user can possible login to privileged account
                         $uri = JFactory::getURI();
                         $return = $uri->toString();
                         $com_users = FLEXI_J16GE ? 'com_users' : 'com_user';
                         $url = $cparams->get('login_page', 'index.php?option=' . $com_users . '&view=login');
                         $return = strtr(base64_encode($return), '+/=', '-_,');
                         $url .= '&return=' . $return;
                         //$url .= '&return='.base64_encode($return);
                         $url .= '&fcreturn=' . base64_encode($fcreturn);
                         JError::raiseWarning(403, JText::sprintf("FLEXI_LOGIN_TO_ACCESS", $url));
                         $app->redirect($url);
                     } else {
                         $msg = JText::_('FLEXI_ALERTNOTAUTH_VIEW');
                         $msg .= $item->type_id && !$item->has_type_access ? "<br/>" . JText::_("FLEXI_ALERTNOTAUTH_VIEW_TYPE") : '';
                         $msg .= $item->catid && !$item->has_mcat_access ? "<br/>" . JText::_("FLEXI_ALERTNOTAUTH_VIEW_MCAT") : '';
                         if ($cparams->get('unauthorized_page', '')) {
                             // (d) redirect unauthorized logged user to the unauthorized page (if this is set)
                             JError::raiseNotice(403, $msg);
                             $app->redirect($cparams->get('unauthorized_page'));
                         } else {
                             // (e) finally raise a 403 forbidden Server Error if user is unauthorized to access item
                             if (FLEXI_J16GE) {
                                 throw new Exception($msg, 403);
                             } else {
                                 JError::raiseError(403, $msg);
                             }
                         }
                     }
                 } else {
                 }
             }
         }
     }
     // End of Existing item (not new)
 }
				$footer_shown = $readmore_shown || $item->event->afterDisplayContent;
			?>

			<?php if ( $footer_shown ) : ?>
			<footer class="group">
			<?php endif; ?>

			<?php if ( $readmore_shown ) : ?>
			<span class="readmore">
				<?php
				/*$uniqueid = "read_more_fc_item_".$item->id;
				$itemlnk = JRoute::_(FlexicontentHelperRoute::getItemRoute($item->slug, $item->categoryslug, 0, $item).'&tmpl=component');
				echo '<script>document.write(\'<a href="'.$itemlnk.'" id="mb'.$uniqueid.'" class="mb" rel="width:\'+((MooTools.version>='1.2.4' ? window.getSize().x : window.getSize().size.x)-150)+\',height:\'+((MooTools.version>='1.2.4' ? window.getSize().y : window.getSize().size.y)-150)+\'">\')</script>';
				*/
				?>
				<a href="<?php echo JRoute::_(FlexicontentHelperRoute::getItemRoute($item->slug, $item->categoryslug, 0, $item)); ?>" class="readon">
				<?php
				if ($item->params->get('readmore')) :
					echo ' ' . $item->params->get('readmore');
				else :
					echo ' ' . JText::sprintf('FLEXI_READ_MORE', $item->title);
				endif;
				?>
				</a>
				<?php //echo '<script>document.write(\'</a> <div class="multiBoxDesc mbox_img_url mb'.$uniqueid.'">'.$item->title.'</div>\')</script>'; ?>
			</span>
			<?php endif; ?>
				
			<!-- BOF afterDisplayContent -->
			<?php if ($item->event->afterDisplayContent) : ?>
				<div class="fc_afterDisplayContent group">
    ?>
		<tr class="<?php 
    echo "row{$k}";
    ?>
">
			<td class="sort_handle"><?php 
    echo $this->pagination->getRowOffset($i);
    ?>
</td>
			<td><?php 
    echo $cid_checkbox;
    ?>
</td>
			<td>
				<?php 
    $item_url = str_replace('&', '&amp;', FlexicontentHelperRoute::getItemRoute($row->id . ':' . $row->alias, $row->categoryslug, 0, $row) . ($row->language != '*' ? '&lang=' . substr($row->language, 0, 2) : ''));
    $item_url = JRoute::_(JURI::root() . $item_url, $xhtml = false);
    // xhtml to false we do it manually above (at least the ampersand) also it has no effect because we prepended the root URL ?
    $previewlink = $item_url . '&amp;preview=1' . $autologin;
    echo '<a class="preview" href="' . $previewlink . '" target="_blank">' . $image_preview . '</a>';
    ?>
			</td>
			<td class="col_title">
				<?php 
    // Display an icon with checkin link, if current user has checked out current item
    if ($row->checked_out) {
        // Record check-in is allowed if either (a) current user has Global Checkin privilege OR (b) record checked out by current user
        $canCheckin = $canCheckinRecords || $row->checked_out == $user->id;
        if ($canCheckin) {
            //if (FLEXI_J16GE && $row->checked_out == $user->id) echo JHtml::_('jgrid.checkedout', $i, $row->editor, $row->checked_out_time, 'items.', $canCheckin);
            $task_str = 'items.checkin';
    function onDisplayFieldValue(&$field, $item, $values = null, $prop = 'display')
    {
        if (!in_array($field->field_type, self::$field_types)) {
            return;
        }
        $view = JRequest::getString('view', FLEXI_ITEMVIEW);
        //if ($view != FLEXI_ITEMVIEW) return;
        if (JRequest::getCmd('print')) {
            return;
        }
        global $mainframe, $addthis;
        //$scheme = JURI::getInstance()->getScheme();  // we replaced http(s):// with //
        $document = JFactory::getDocument();
        $lang = $document->getLanguage();
        $lang = $item->params->get('language', $lang);
        $lang = $lang ? $lang : 'en-GB';
        $lang = substr($lang, 0, 2);
        $lang = in_array($lang, array('en', 'es', 'it', 'th')) ? $lang : 'en';
        // parameters shortcuts
        $display_comments = $field->parameters->get('display_comments', 1) && $item->parameters->get('comments', 0);
        $display_resizer = $field->parameters->get('display_resizer', 1);
        $display_print = $field->parameters->get('display_print', 1);
        $display_email = $field->parameters->get('display_email', 1);
        $display_voice = $field->parameters->get('display_voice', 1);
        $display_pdf = 0;
        //$field->parameters->get('display_pdf', 1);
        $load_css = $field->parameters->get('load_css', 1);
        $display_social = $field->parameters->get('display_social', 1);
        $addthis_user = $field->parameters->get('addthis_user', '');
        $addthis_pubid = $field->parameters->get('addthis_pubid', $addthis_user);
        $spacer_size = $field->parameters->get('spacer_size', 21);
        $module_position = $field->parameters->get('module_position', '');
        $default_size = $field->parameters->get('default_size', 12);
        $default_line = $field->parameters->get('default_line', 16);
        $target = $field->parameters->get('target', 'flexicontent');
        $voicetarget = $field->parameters->get('voicetarget', 'flexicontent');
        $spacer = ' style="width:' . $spacer_size . 'px;"';
        // define a global variable to be sure the script is loaded only once
        $addthis = isset($addthis) ? $addthis : 0;
        if ($load_css) {
            $document->addStyleSheet(JURI::root(true) . '/plugins/flexicontent_fields/toolbar/toolbar/toolbar.css');
        }
        if ($display_social || $display_comments || $display_email || $display_print) {
            $item_url = FlexicontentHelperRoute::getItemRoute($item->slug, $item->categoryslug);
            $server = JURI::getInstance()->toString(array('scheme', 'host', 'port'));
            $item_link = $server . JRoute::_($item_url);
            // NOTE: this uses current SSL setting (e.g menu item), and not URL scheme: http/https
            //$item_link = JRoute::_($item_url, true, -1);
        }
        $display = '<div class="flexitoolbar">';
        // begin of the toolbar container
        // comments button
        if ($display_comments) {
            $comment_link = $item_link . '#addcomments';
            $display .= '
			<div class="flexi-react toolbar-element">
				<span class="comments-bubble">' . ($module_position ? '<!-- jot ' . $module_position . ' s -->' : '') . $this->_getCommentsCount($item->id) . ($module_position ? '<!-- jot ' . $module_position . ' e -->' : '') . '</span>
				<span class="comments-legend flexi-legend"><a href="' . $comment_link . '" title="' . JText::_('FLEXI_FIELD_TOOLBAR_COMMENT') . '">' . JText::_('FLEXI_FIELD_TOOLBAR_COMMENT') . '</a></span>
			</div>
			<div class="toolbar-spacer"' . $spacer . '></div>
			';
        }
        // text resizer
        if ($display_resizer) {
            $document->addScriptDeclaration('var textsize = ' . $default_size . ';
			var lineheight = ' . $default_line . ';
			function fsize(size,line,unit,id){
				var vfontsize = document.getElementById(id);
				if(vfontsize){
					vfontsize.style.fontSize = size + unit;
					vfontsize.style.lineHeight = line + unit;
				}
			}
			function changetextsize(up){
				if(up){
					textsize 	= parseFloat(textsize)+2;
					lineheight 	= parseFloat(lineheight)+2;
				}else{
					textsize 	= parseFloat(textsize)-2;
					lineheight 	= parseFloat(lineheight)-2;
				}
			}');
            $display .= '
			<div class="flexi-resizer toolbar-element">
				<a class="decrease" href="javascript:fsize(textsize,lineheight,\'px\',\'' . $target . '\');" onclick="changetextsize(0);">' . JText::_("FLEXI_FIELD_TOOLBAR_DECREASE") . '</a>
				<a class="increase" href="javascript:fsize(textsize,lineheight,\'px\',\'' . $target . '\');" onclick="changetextsize(1);">' . JText::_("FLEXI_FIELD_TOOLBAR_INCREASE") . '</a>
				<span class="flexi-legend">' . JText::_("FLEXI_FIELD_TOOLBAR_SIZE") . '</span>
			</div>
			<div class="toolbar-spacer"' . $spacer . '></div>
			';
        }
        // email button
        if ($display_email) {
            require_once JPATH_SITE . DS . 'components' . DS . 'com_mailto' . DS . 'helpers' . DS . 'mailto.php';
            $url = 'index.php?option=com_mailto&tmpl=component&link=' . MailToHelper::addLink($item_link);
            $estatus = 'width=400,height=400,menubar=yes,resizable=yes';
            $display .= '
			<div class="flexi-email toolbar-element">
				<span class="email-legend flexi-legend"><a rel="nofollow" href="' . JRoute::_($url) . '" onclick="window.open(this.href,\'win2\',\'' . $estatus . '\'); return false;" title="' . JText::_('FLEXI_FIELD_TOOLBAR_SEND') . '">' . JText::_('FLEXI_FIELD_TOOLBAR_SEND') . '</a></span>
			</div>
			<div class="toolbar-spacer"' . $spacer . '></div>
			';
        }
        // print button
        if ($display_print) {
            $pop = JRequest::getInt('pop');
            $pstatus = 'status=no,toolbar=no,scrollbars=yes,titlebar=no,menubar=no,resizable=yes,width=640,height=480,directories=no,location=no';
            $print_link = $pop ? '#' : $item_link . (strstr($item_link, '?') ? '&amp;' : '?') . 'pop=1&amp;print=1&amp;tmpl=component';
            $js_link = $pop ? 'onclick="window.print();return false;"' : 'onclick="window.open(this.href,\'win2\',\'' . $pstatus . '\'); return false;"';
            $display .= '
			<div class="flexi-print toolbar-element">
				<span class="print-legend flexi-legend"><a rel="nofollow" href="' . $print_link . '" ' . $js_link . ' title="' . JText::_('FLEXI_FIELD_TOOLBAR_PRINT') . '">' . JText::_('FLEXI_FIELD_TOOLBAR_PRINT') . '</a></span>
			</div>
			<div class="toolbar-spacer"' . $spacer . '></div>
			';
        }
        // pdf button
        if ($display_voice) {
            $display .= "\n\t\t\t<div class=\"flexi-voice toolbar-element\">";
            if ($lang == 'th') {
                // Special case language case, maybe la=laos, and Bhutan languages in the future (NECTEC support these languages)
                $document->addScript(JURI::root(true) . '/plugins/flexicontent_fields/toolbar/toolbar/th.js');
                $display .= "\n\t\t\t\t\t<span class=\"voice-legend flexi-legend\"><a href=\"javascript:void(0);\" onclick=\"openwindow('" . $voicetarget . "','" . $lang . "');\" class=\"mainlevel-toolbar-article-horizontal\" rel=\"nofollow\">" . JTEXT::_('FLEXI_FIELD_TOOLBAR_VOICE') . "</a></span>\n\t\t\t\t\t";
            } else {
                $document->addScript('//vozme.com/get_text.js');
                $display .= "\n\t\t\t\t\t<span class=\"voice-legend flexi-legend\"><a href=\"javascript:void(0);\" onclick=\"get_id('" . $voicetarget . "','" . $lang . "','fm');\" class=\"mainlevel-toolbar-article-horizontal\" rel=\"nofollow\">" . JTEXT::_('FLEXI_FIELD_TOOLBAR_VOICE') . "</a></span>\n\t\t\t\t\t";
            }
            $display .= "\n\t\t\t</div>\n\t\t\t<div class=\"toolbar-spacer\"" . $spacer . "></div>\n\t\t\t\t";
        }
        // pdf button
        if ($display_pdf) {
            $pdflink = 'index.php?view=items&cid=' . $item->categoryslug . '&id=' . $item->slug . '&format=pdf';
            $display .= '
			<div class="flexi-pdf toolbar-element">
				<span class="pdf-legend flexi-legend"><a href="' . JRoute::_($pdflink) . '" title="' . JText::_('FLEXI_FIELD_TOOLBAR_PDF') . '">' . JText::_('FLEXI_FIELD_TOOLBAR_PDF') . '</a></span>
			</div>
			<div class="toolbar-spacer"' . $spacer . '></div>
			';
        }
        // AddThis social SHARE buttons, also optionally add OPEN GRAPH TAGs
        if ($display_social) {
            // ***************
            // OPEN GRAPH TAGs
            // ***************
            // OPEN GRAPH: site name
            if ($field->parameters->get('add_og_site_name')) {
                $document->addCustomTag("<meta property=\"og:site_name\" content=\"" . JFactory::getApplication()->getCfg('sitename') . "\" />");
            }
            // OPEN GRAPH: title
            if ($field->parameters->get('add_og_title')) {
                $title = flexicontent_html::striptagsandcut($item->title);
                $document->addCustomTag("<meta property=\"og:title\" content=\"{$title}\" />");
            }
            // OPEN GRAPH: description
            if ($field->parameters->get('add_og_descr')) {
                if ($item->metadesc) {
                    $document->addCustomTag('<meta property="og:description" content="' . $item->metadesc . '" />');
                } else {
                    $text = flexicontent_html::striptagsandcut($item->text);
                    $document->addCustomTag("<meta property=\"og:description\" content=\"{$text}\" />");
                }
            }
            // OPEN GRAPH: type
            $og_type = (int) $field->parameters->get('add_og_type');
            if ($og_type) {
                if ($og_type > 2) {
                    $og_type = 1;
                }
                $og_type_names = array(1 => 'article', 2 => 'website');
                $document->addCustomTag("<meta property=\"og:type\" content=\"" . $og_type_names[$og_type] . "\">");
            }
            // OPEN GRAPH: image (extracted from item's description text)
            if ($field->parameters->get('add_og_image')) {
                $og_image_field = $field->parameters->get('og_image_field');
                $og_image_fallback = $field->parameters->get('og_image_fallback');
                $og_image_thumbsize = $field->parameters->get('og_image_thumbsize');
                if ($og_image_field) {
                    $imageurl = FlexicontentFields::getFieldDisplay($item, $og_image_field, null, 'display_' . $og_image_thumbsize . '_src', 'module');
                    if ($imageurl) {
                        $img_field = $item->fields[$og_image_field];
                        if (!$imageurl && $og_image_fallback == 1 || $imageurl && $og_image_fallback == 2 && $img_field->using_default_value) {
                            $imageurl = $this->_extractimageurl($item);
                        }
                    }
                } else {
                    $imageurl = $this->_extractimageurl($item);
                }
                // Add image if fould, making sure it is converted to ABSOLUTE URL
                if ($imageurl) {
                    $is_absolute = (bool) parse_url($imageurl, PHP_URL_SCHEME);
                    // preg_match("#^http|^https|^ftp#i", $imageurl);
                    $imageurl = $is_absolute ? $imageurl : JURI::root() . $imageurl;
                    $document->addCustomTag("<meta property=\"og:image\" content=\"{$imageurl}\" />");
                }
            }
            // Add og-URL explicitely as this is required by facebook ?
            if ($item_link) {
                $document->addCustomTag("<meta property=\"og:url\" content=\"" . $item_link . "\" />");
            }
            // ****************************
            // AddThis social SHARE buttons
            // ****************************
            $addthis_outside_toolbar = $field->parameters->get('addthis_outside_toolbar', 0);
            $addthis_custom_code = $field->parameters->get('addthis_custom_code', false);
            $addthis_custom_predefined = $field->parameters->get('addthis_custom_predefined', false);
            $addthis_code = '';
            if ($addthis_custom_code) {
                $addthis_code = str_replace('_item_url_', $item_link, $addthis_custom_code);
                $addthis_code = str_replace('_item_title_', htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8'), $addthis_code);
            } else {
                switch ($addthis_custom_predefined) {
                    case 1:
                        $addthis_code .= '
						<!-- AddThis Button BEGIN -->
						<div class="addthis_toolbox addthis_default_style addthis_counter_style" addthis:url="' . $item_link . '" addthis:title="' . htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8') . '">
						<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
						<a class="addthis_button_tweet"></a>
						<a class="addthis_button_pinterest_pinit"></a>
						<a class="addthis_counter addthis_pill_style"></a>
						</div>
						<!-- AddThis Button END -->
						';
                        break;
                    case 2:
                        $addthis_code .= '
						<!-- AddThis Button BEGIN -->
						<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url="' . $item_link . '" addthis:title="' . htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8') . '">
						<a class="addthis_button_preferred_1"></a>
						<a class="addthis_button_preferred_2"></a>
						<a class="addthis_button_preferred_3"></a>
						<a class="addthis_button_preferred_4"></a>
						<a class="addthis_button_compact"></a>
						<a class="addthis_counter addthis_bubble_style"></a>
						</div>
						<!-- AddThis Button END -->
						';
                        break;
                    default:
                    case 3:
                        $addthis_code .= '
						<!-- AddThis Button BEGIN -->
						<div class="addthis_toolbox addthis_default_style addthis_16x16_style" addthis:url="' . $item_link . '" addthis:title="' . htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8') . '">
						<a class="addthis_button_preferred_1"></a>
						<a class="addthis_button_preferred_2"></a>
						<a class="addthis_button_preferred_3"></a>
						<a class="addthis_button_preferred_4"></a>
						<a class="addthis_button_compact"></a>
						<a class="addthis_counter addthis_bubble_style"></a>
						</div>
						<!-- AddThis Button END -->
						';
                        break;
                    case 4:
                        $addthis_code .= '
						<!-- AddThis Button BEGIN -->
						<a class="addthis_button" href="//www.addthis.com/bookmark.php?v=300&pubid=' . $addthis_pubid . '"><img src="//s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="' . JText::_('FLEXI_FIELD_TOOLBAR_SHARE') . '" style="border:0"/></a>
						<!-- AddThis Button END -->
						';
                        break;
                    case 5:
                        $addthis_code .= '
						<!-- AddThis Button BEGIN -->
						<div class="addthis_toolbox addthis_floating_style addthis_counter_style" style="left:50px;top:50px;" addthis:url="' . $item_link . '" addthis:title="' . htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8') . '">
						<a class="addthis_button_facebook_like" fb:like:layout="box_count"></a>
						<a class="addthis_button_tweet" tw:count="vertical"></a>
						<a class="addthis_button_google_plusone" g:plusone:size="tall"></a>
						<a class="addthis_counter"></a>
						</div>
						<!-- AddThis Button END -->
						';
                        break;
                    case 6:
                        $addthis_code .= '
						<!-- AddThis Button BEGIN -->
						<div class="addthis_toolbox addthis_floating_style addthis_32x32_style" style="left:50px;top:50px;" addthis:url="' . $item_link . '" addthis:title="' . htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8') . '">
						<a class="addthis_button_preferred_1"></a>
						<a class="addthis_button_preferred_2"></a>
						<a class="addthis_button_preferred_3"></a>
						<a class="addthis_button_preferred_4"></a>
						<a class="addthis_button_compact"></a>
						</div>
						<!-- AddThis Button END -->
						';
                        break;
                    case 7:
                        $addthis_code .= '
						<!-- AddThis Button BEGIN -->
						<div class="addthis_toolbox addthis_floating_style addthis_16x16_style" style="left:50px;top:50px;" addthis:url="' . $item_link . '" addthis:title="' . htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8') . '">
						<a class="addthis_button_preferred_1"></a>
						<a class="addthis_button_preferred_2"></a>
						<a class="addthis_button_preferred_3"></a>
						<a class="addthis_button_preferred_4"></a>
						<a class="addthis_button_compact"></a>
						</div>
						<!-- AddThis Button END -->
						';
                        break;
                }
            }
            if ($addthis_outside_toolbar) {
                $display .= '<div class="flexi-socials-outside">' . $addthis_code . '</div>';
            } else {
                $display .= '<div class="flexi-socials toolbar-element">' . $addthis_code . '</div>';
            }
            if (!$addthis) {
                $document->addCustomTag('	
					<script type="text/javascript">
					var addthis_config = {
						services_exclude: "print,email"
					}
					</script>
					<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js' . ($addthis_pubid ? '#pubid=' . $addthis_pubid : '') . '"></script>
				');
                $addthis = 1;
            }
        }
        $display .= '</div>';
        // end of the toolbar container
        $field->{$prop} = $display;
    }
 /**
  * Search method
  *
  * The sql must return the following fields that are used in a common display routine:
  *
  *   href, title, section, created, text, browsernav
  *
  * @param string Target search string
  * @param string matching option, natural|natural_expanded|exact|any|all
  * @param string ordering option, newest|oldest|popular|alpha|category
  * @param mixed An array if restricted to areas, null if search all
  */
 function onContentSearch($text, $phrase = '', $ordering = '', $areas = null)
 {
     $app = JFactory::getApplication();
     $view = JRequest::getCMD('view');
     $app->setUserState('fc_view_total_' . $view, 0);
     $app->setUserState('fc_view_limit_max_' . $view, 0);
     // Check if not requested search areas, inside this search areas of this plugin
     if (is_array($areas) && !array_intersect($areas, array_keys($this->onContentSearchAreas()))) {
         return array();
     }
     // Initialize some variables
     $db = JFactory::getDBO();
     $user = JFactory::getUser();
     $menu = $app->getMenu()->getActive();
     // Get the COMPONENT only parameters and merge current menu item parameters
     $params = clone JComponentHelper::getParams('com_flexicontent');
     if ($menu) {
         $params->merge($menu->params);
     }
     // some parameter shortcuts for SQL query
     $show_noauth = $params->get('show_noauth', 0);
     $orderby_override = $params->get('orderby_override', 1);
     // Compatibility text search (LIKE %word%) for language without spaces
     $filter_word_like_any = $params->get('filter_word_like_any', 0);
     // ************************************************
     // some parameter shortcuts common with search view
     // ************************************************
     $canseltypes = $params->get('canseltypes', 1);
     $txtmode = $params->get('txtmode', 0);
     // 0: BASIC Index, 1: ADVANCED Index without search fields user selection, 2: ADVANCED Index with search fields user selection
     // Get if text searching according to specific (single) content type
     $show_txtfields = $params->get('show_txtfields', 1);
     //0:hide, 1:according to content, 2:use custom configuration
     $show_txtfields = $txtmode ? 0 : $show_txtfields;
     // disable this flag if using BASIC index for text search
     // Get if filtering according to specific (single) content type
     $show_filters = $params->get('show_filters', 1);
     //0:hide, 1:according to content, 2:use custom configuration
     // Force single type selection and showing the content type selector
     $type_based_search = $show_filters == 1 || $show_txtfields == 1;
     $canseltypes = $type_based_search ? 1 : $canseltypes;
     // ********************************************************************
     // Get Content Types allowed for user selection in the Search Form
     // Also retrieve their configuration, plus the currently selected types
     // ********************************************************************
     // Get them from configuration
     $contenttypes = $params->get('contenttypes', array());
     // Sanitize them
     $contenttypes = !is_array($contenttypes) ? array($contenttypes) : $contenttypes;
     $contenttypes = array_unique(array_map('intval', $contenttypes));
     // Make sure these are integers since we will be using them UNQUOTED
     // Force hidden content type selection if only 1 content type was initially configured
     $canseltypes = count($contenttypes) == 1 ? 0 : $canseltypes;
     // Type data and configuration (parameters), if no content types specified then all will be retrieved
     $typeData = flexicontent_db::getTypeData(implode(",", $contenttypes));
     $contenttypes = array();
     foreach ($typeData as $tdata) {
         $contenttypes[] = $tdata->id;
     }
     // Get Content Types to use either those currently selected in the Search Form, or those hard-configured in the search menu item
     if ($canseltypes) {
         $form_contenttypes = JRequest::getVar('contenttypes', array());
         // Sanitize them
         $form_contenttypes = !is_array($form_contenttypes) ? array($form_contenttypes) : $form_contenttypes;
         $form_contenttypes = array_unique(array_map('intval', $form_contenttypes));
         // Make sure these are integers since we will be using them UNQUOTED
         $_contenttypes = array_intersect($contenttypes, $form_contenttypes);
         if (!empty($_contenttypes)) {
             $contenttypes = $_contenttypes;
         }
         // catch empty case: no content types were given or not-allowed content types were passed
     }
     // Check for zero content type (can occur during sanitizing content ids to integers)
     if (!empty($contenttypes)) {
         foreach ($contenttypes as $i => $v) {
             if (!strlen($contenttypes[$i])) {
                 unset($contenttypes[$i]);
             }
         }
     }
     // Type based seach, get a single content type (first one, if more than 1 were given ...)
     if ($type_based_search && !empty($contenttypes)) {
         $single_contenttype = reset($contenttypes);
         $contenttypes = array($single_contenttype);
     } else {
         $single_contenttype = false;
     }
     // *************************************
     // Text Search Fields of the search form
     // *************************************
     if (!$txtmode) {
         $txtflds = array();
         $fields_text = array();
     } else {
         $txtflds = '';
         if ($show_txtfields) {
             if ($show_txtfields == 1) {
                 $txtflds = $single_contenttype ? $typeData[$single_contenttype]->params->get('searchable', '') : '';
             } else {
                 $txtflds = $params->get('txtflds', '');
             }
         }
         // Sanitize them
         $txtflds = preg_replace("/[\"'\\\\]/u", "", $txtflds);
         $txtflds = array_unique(preg_split("/\\s*,\\s*/u", $txtflds));
         if (!strlen($txtflds[0])) {
             unset($txtflds[0]);
         }
         // Create a comma list of them
         $txtflds_list = count($txtflds) ? "'" . implode("','", $txtflds) . "'" : '';
         // Retrieve field properties/parameters, verifying the support to be used as Text Search Fields
         // This will return all supported fields if field limiting list is empty
         $fields_text = FlexicontentFields::getSearchFields($key = 'id', $indexer = 'advanced', $txtflds_list, $contenttypes, $load_params = true, 0, 'search');
         if (empty($fields_text)) {
             // all entries of field limiting list were invalid , get ALL
             if (!empty($contenttypes)) {
                 $fields_text = FlexicontentFields::getSearchFields($key = 'id', $indexer = 'advanced', null, $contenttypes, $load_params = true, 0, 'search');
             } else {
                 $fields_text = array();
             }
         }
     }
     // ********************************
     // Filter Fields of the search form
     // ********************************
     // Get them from type configuration or from search menu item
     $filtflds = '';
     if ($show_filters) {
         if ($show_filters == 1) {
             $filtflds = $single_contenttype ? $typeData[$single_contenttype]->params->get('filters', '') : '';
         } else {
             $filtflds = $params->get('filtflds', '');
         }
     }
     // Sanitize them
     $filtflds = preg_replace("/[\"'\\\\]/u", "", $filtflds);
     $filtflds = array_unique(preg_split("/\\s*,\\s*/u", $filtflds));
     if (!strlen($filtflds[0])) {
         unset($filtflds[0]);
     }
     // Create a comma list of them
     $filtflds_list = count($filtflds) ? "'" . implode("','", $filtflds) . "'" : '';
     // Retrieve field properties/parameters, verifying the support to be used as Filter Fields
     // This will return all supported fields if field limiting list is empty
     if (count($filtflds)) {
         $filters_tmp = FlexicontentFields::getSearchFields($key = 'name', $indexer = 'advanced', $filtflds_list, $contenttypes, $load_params = true, 0, 'filter');
         // Use custom order
         $filters = array();
         if ($canseltypes && $show_filters) {
             foreach ($filtflds as $field_name) {
                 if (empty($filters_tmp[$field_name])) {
                     continue;
                 }
                 $filter_id = $filters_tmp[$field_name]->id;
                 $filters[$filter_id] = $filters_tmp[$field_name];
             }
         } else {
             foreach ($filters_tmp as $filter) {
                 $filters[$filter->id] = $filter;
                 // index by filter_id in this case too (for consistency, although we do not use the array index ?)
             }
         }
         unset($filters_tmp);
     }
     // If configured filters were not found/invalid for the current content type(s)
     // then retrieve all fields marked as filterable for the give content type(s) this is useful to list per content type filters automatically, even when not set or misconfigured
     if (empty($filters)) {
         if (!empty($contenttypes)) {
             $filters = FlexicontentFields::getSearchFields($key = 'id', $indexer = 'advanced', null, $contenttypes, $load_params = true, 0, 'filter');
         } else {
             $filters = array();
         }
     }
     // **********************
     // Load Plugin parameters
     // **********************
     $plugin = JPluginHelper::getPlugin('search', 'flexiadvsearch');
     $pluginParams = new JRegistry($plugin->params);
     // Shortcuts for plugin parameters
     $search_limit = $params->get('search_limit', $pluginParams->get('search_limit', 20));
     // Limits the returned results of this seach plugin
     $filter_lang = $params->get('filter_lang', $pluginParams->get('filter_lang', 1));
     // Language filtering enabled
     $search_archived = $params->get('search_archived', $pluginParams->get('search_archived', 1));
     // Include archive items into the search
     $browsernav = $params->get('browsernav', $pluginParams->get('browsernav', 2));
     // Open search in window (for value 1)
     // ***************************************************************************************************************
     // Varous other variable USED in the SQL query like (a) current frontend language and (b) -this- plugin specific ordering, (c) null / now dates, (d) etc
     // ***************************************************************************************************************
     // Get current frontend language (fronted user selected)
     $lang = flexicontent_html::getUserCurrentLang();
     // NULL and CURRENT dates,
     // NOTE: the current date needs to use built-in MYSQL function, otherwise filter caching can not work because the CURRENT DATETIME is continuously different !!!
     //$now = JFactory::getDate()->toSql();
     $_nowDate = 'UTC_TIMESTAMP()';
     //$db->Quote($now);
     $nullDate = $db->getNullDate();
     // Section name
     $searchFlexicontent = JText::_('FLEXICONTENT');
     // REMOVED / COMMENTED OUT this feature:
     // Require any OR all Filters ... this can be user selectable
     //$show_filtersop = $params->get('show_filtersop', 1);
     //$default_filtersop = $params->get('default_filtersop', 'all');
     //$FILTERSOP = !$show_filtersop ? $default_filtersop : JRequest::getVar('filtersop', $default_filtersop);
     // ****************************************
     // Create WHERE clause part for Text Search
     // ****************************************
     $si_tbl = !$txtmode ? 'flexicontent_items_ext' : 'flexicontent_advsearch_index';
     $search_prefix = JComponentHelper::getParams('com_flexicontent')->get('add_search_prefix') ? 'vvv' : '';
     // SEARCH WORD Prefix
     $text = preg_replace('/(\\b[^\\s,\\.]+\\b)/u', $search_prefix . '$0', trim($text));
     if (strlen($text)) {
         $ts = !$txtmode ? 'ie' : 'ts';
         $escaped_text = $db->escape($text, true);
         $quoted_text = $db->Quote($escaped_text, false);
         switch ($phrase) {
             case 'natural':
                 if ($filter_word_like_any) {
                     $_text_match = ' LOWER (' . $ts . '.search_index) LIKE ' . $db->Quote('%' . $escaped_text . '%', false);
                 } else {
                     $_text_match = ' MATCH (' . $ts . '.search_index) AGAINST (' . $quoted_text . ') ';
                 }
                 break;
             case 'natural_expanded':
                 $_text_match = ' MATCH (' . $ts . '.search_index) AGAINST (' . $quoted_text . ' WITH QUERY EXPANSION) ';
                 break;
             case 'exact':
                 $words = preg_split('/\\s\\s*/u', $text);
                 $stopwords = array();
                 $shortwords = array();
                 if (!$search_prefix) {
                     $words = flexicontent_db::removeInvalidWords($words, $stopwords, $shortwords, $si_tbl, 'search_index', $isprefix = 0);
                 }
                 if (empty($words)) {
                     // All words are stop-words or too short, we could try to execute a query that only contains a LIKE %...% , but it would be too slow
                     JRequest::setVar('ignoredwords', implode(' ', $stopwords));
                     JRequest::setVar('shortwords', implode(' ', $shortwords));
                     $_text_match = ' 0=1 ';
                 } else {
                     // speed optimization ... 2-level searching: first require ALL words, then require exact text
                     $newtext = '+' . implode(' +', $words);
                     $quoted_text = $db->escape($newtext, true);
                     $quoted_text = $db->Quote($quoted_text, false);
                     $exact_text = $db->Quote('%' . $escaped_text . '%', false);
                     $_text_match = ' MATCH (' . $ts . '.search_index) AGAINST (' . $quoted_text . ' IN BOOLEAN MODE) AND ' . $ts . '.search_index LIKE ' . $exact_text;
                 }
                 break;
             case 'all':
                 $words = preg_split('/\\s\\s*/u', $text);
                 $stopwords = array();
                 $shortwords = array();
                 if (!$search_prefix) {
                     $words = flexicontent_db::removeInvalidWords($words, $stopwords, $shortwords, $si_tbl, 'search_index', $isprefix = 1);
                 }
                 JRequest::setVar('ignoredwords', implode(' ', $stopwords));
                 JRequest::setVar('shortwords', implode(' ', $shortwords));
                 $newtext = '+' . implode('* +', $words) . '*';
                 $quoted_text = $db->escape($newtext, true);
                 $quoted_text = $db->Quote($quoted_text, false);
                 $_text_match = ' MATCH (' . $ts . '.search_index) AGAINST (' . $quoted_text . ' IN BOOLEAN MODE) ';
                 break;
             case 'any':
             default:
                 if ($filter_word_like_any) {
                     $_text_match = ' LOWER (' . $ts . '.search_index) LIKE ' . $db->Quote('%' . $escaped_text . '%', false);
                 } else {
                     $words = preg_split('/\\s\\s*/u', $text);
                     $stopwords = array();
                     $shortwords = array();
                     if (!$search_prefix) {
                         $words = flexicontent_db::removeInvalidWords($words, $stopwords, $shortwords, $si_tbl, 'search_index', $isprefix = 1);
                     }
                     JRequest::setVar('ignoredwords', implode(' ', $stopwords));
                     JRequest::setVar('shortwords', implode(' ', $shortwords));
                     $newtext = implode('* ', $words) . '*';
                     $quoted_text = $db->escape($newtext, true);
                     $quoted_text = $db->Quote($quoted_text, false);
                     $_text_match = ' MATCH (' . $ts . '.search_index) AGAINST (' . $quoted_text . ' IN BOOLEAN MODE) ';
                 }
                 break;
         }
         // Construct TEXT SEARCH limitation SUB-QUERY (contained in a AND-WHERE clause)
         $text_where = ' AND ' . $_text_match;
     } else {
         $text_where = '';
     }
     // *******************
     // Create ORDER clause
     // *******************
     // FLEXIcontent search view, use FLEXIcontent ordering
     $orderby_join = '';
     $orderby_col = '';
     if (JRequest::getVar('option') == 'com_flexicontent') {
         $order = '';
         $orderby = flexicontent_db::buildItemOrderBy($params, $order, $_request_var = 'orderby', $_config_param = 'orderby', $_item_tbl_alias = 'i', $_relcat_tbl_alias = 'rel', $_default_order = '', $_default_order_dir = '', $sfx = '', $support_2nd_lvl = false);
         // Create JOIN for ordering items by a custom field (Level 1)
         if ('field' == $order[1]) {
             $orderbycustomfieldid = (int) $params->get('orderbycustomfieldid', 0);
             $orderby_join .= ' LEFT JOIN #__flexicontent_fields_item_relations AS f ON f.item_id = i.id AND f.field_id=' . $orderbycustomfieldid;
         }
         // Create JOIN for ordering items by a custom field (Level 2)
         if ('field' == $order[2]) {
             $orderbycustomfieldid_2nd = (int) $params->get('orderbycustomfieldid' . '_2nd', 0);
             $orderby_join .= ' LEFT JOIN #__flexicontent_fields_item_relations AS f2 ON f2.item_id = i.id AND f2.field_id=' . $orderbycustomfieldid_2nd;
         }
         // Create JOIN for ordering items by author's name
         if (in_array('author', $order) || in_array('rauthor', $order)) {
             $orderby_col = '';
             $orderby_join .= ' LEFT JOIN #__users AS u ON u.id = i.created_by';
         }
         // Create JOIN for ordering items by a most commented
         if (in_array('commented', $order)) {
             $orderby_col = ', count(com.object_id) AS comments_total';
             $orderby_join .= ' LEFT JOIN #__jcomments AS com ON com.object_id = i.id';
         }
         // Create JOIN for ordering items by a most rated
         if (in_array('rated', $order)) {
             $orderby_col = ', (cr.rating_sum / cr.rating_count) * 20 AS votes';
             $orderby_join .= ' LEFT JOIN #__content_rating AS cr ON cr.content_id = i.id';
         }
         // Create JOIN for ordering items by their ordering attribute (in item's main category)
         if (in_array('order', $order)) {
             $orderby_join .= ' LEFT JOIN #__flexicontent_cats_item_relations AS rel ON rel.itemid = i.id AND rel.catid = i.catid';
         }
     } else {
         switch ($ordering) {
             //case 'relevance': $orderby = ' ORDER BY score DESC, i.title ASC'; break;
             case 'oldest':
                 $orderby = 'i.created ASC';
                 break;
             case 'popular':
                 $orderby = 'i.hits DESC';
                 break;
             case 'alpha':
                 $orderby = 'i.title ASC';
                 break;
             case 'category':
                 $orderby = 'c.title ASC, i.title ASC';
                 break;
             case 'newest':
                 $orderby = 'i.created DESC';
                 break;
             default:
                 $orderby = 'i.created DESC';
                 break;
         }
         $orderby = ' ORDER BY ' . $orderby;
     }
     // ****************************************************************************************
     // Create JOIN clause and WHERE clause part for filtering by current (viewing) access level
     // ****************************************************************************************
     $joinaccess = '';
     $andaccess = '';
     $select_access = '';
     // Extra access columns for main category and content type (item access will be added as 'access')
     $select_access .= ',  c.access as category_access, ty.access as type_access';
     if (!$show_noauth) {
         // User not allowed to LIST unauthorized items
         $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
         $aid_list = implode(",", $aid_arr);
         $andaccess .= ' AND ty.access IN (0,' . $aid_list . ')';
         $andaccess .= ' AND  c.access IN (0,' . $aid_list . ')';
         $andaccess .= ' AND  i.access IN (0,' . $aid_list . ')';
         $select_access .= ', 1 AS has_access';
     } else {
         // Access Flags for: content type, main category, item
         $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
         $aid_list = implode(",", $aid_arr);
         $select_access .= ', ' . ' CASE WHEN ' . '  ty.access IN (' . $aid_list . ') AND ' . '   c.access IN (' . $aid_list . ') AND ' . '   i.access IN (' . $aid_list . ') ' . ' THEN 1 ELSE 0 END AS has_access';
     }
     // **********************************************************************************************************************************************************
     // Create WHERE clause part for filtering by current active language, and current selected contend types ( !! although this is possible via a filter too ...)
     // **********************************************************************************************************************************************************
     $andlang = '';
     if ($app->isSite() && (FLEXI_FISH || FLEXI_J16GE && $app->getLanguageFilter()) && $filter_lang) {
         $andlang .= ' AND ( ie.language LIKE ' . $db->Quote($lang . '%') . (FLEXI_J16GE ? ' OR ie.language="*" ' : '') . ' ) ';
     }
     // Filter by currently selected content types
     $andcontenttypes = count($contenttypes) ? ' AND ie.type_id IN (' . implode(",", $contenttypes) . ') ' : '';
     // ***********************************************************************
     // Create the AND-WHERE clause parts for the currentl active Field Filters
     // ***********************************************************************
     $return_sql = 2;
     $filters_where = array();
     foreach ($filters as $field) {
         // Get value of current filter, and SKIP it if value is EMPTY
         $filtervalue = JRequest::getVar('filter_' . $field->id, '');
         $empty_filtervalue_array = is_array($filtervalue) && !strlen(trim(implode('', $filtervalue)));
         $empty_filtervalue_string = !is_array($filtervalue) && !strlen(trim($filtervalue));
         if ($empty_filtervalue_array || $empty_filtervalue_string) {
             continue;
         }
         // Call field filtering of advanced search to find items matching the field filter (an SQL SUB-QUERY is returned)
         $field_filename = $field->iscore ? 'core' : $field->field_type;
         $filtered = FLEXIUtilities::call_FC_Field_Func($field_filename, 'getFilteredSearch', array(&$field, &$filtervalue, &$return_sql));
         // An empty return value means no matching values were found
         $filtered = empty($filtered) ? ' AND 0 ' : $filtered;
         // A string mean a subquery was returned, while an array means that item ids we returned
         $filters_where[$field->id] = is_array($filtered) ? ' AND i.id IN (' . implode(',', $filtered) . ')' : $filtered;
         /*if ($filters_where[$field->id]) {
         			echo "\n<br/>Filter:". $field->name ." : ";   print_r($filtervalue);
         			echo "<br>".$filters_where[$field->id]."<br/>";
         		}*/
     }
     //echo "\n<br/><br/>Filters Active: ". count($filters_where)."<br/>";
     //echo "<pre>"; print_r($filters_where);
     //exit;
     // ******************************************************
     // Create Filters JOIN clauses and AND-WHERE clause parts
     // ******************************************************
     // JOIN clause - USED - to limit returned 'text' to the text of TEXT-SEARCHABLE only fields ... (NOT shared with filters)
     if (!$txtmode) {
         $onBasic_textsearch = $text_where;
         $onAdvanced_textsearch = '';
         $join_textsearch = '';
         $join_textfields = '';
     } else {
         $onBasic_textsearch = '';
         $onAdvanced_textsearch = $text_where;
         $join_textsearch = ' JOIN #__flexicontent_advsearch_index as ts ON ts.item_id = i.id ' . (count($fields_text) ? 'AND ts.field_id IN (' . implode(',', array_keys($fields_text)) . ')' : '');
         $join_textfields = ' JOIN #__flexicontent_fields as f ON f.id=ts.field_id';
     }
     // JOIN clauses ... (shared with filters)
     $join_clauses = '' . ' JOIN #__categories AS c ON c.id = i.catid' . ' JOIN #__flexicontent_items_ext AS ie ON ie.item_id = i.id' . ' JOIN #__flexicontent_types AS ty ON ie.type_id = ty.id';
     $join_clauses_with_text = '' . ' JOIN #__categories AS c ON c.id = i.catid' . ' JOIN #__flexicontent_items_ext AS ie ON ie.item_id = i.id' . $onBasic_textsearch . ' JOIN #__flexicontent_types AS ty ON ie.type_id = ty.id' . ($text_where ? $join_textsearch . $onAdvanced_textsearch . $join_textfields : '');
     // AND-WHERE sub-clauses ... (shared with filters)
     $where_conf = ' WHERE 1 ' . ' AND i.state IN (1,-5' . ($search_archived ? ',' . (FLEXI_J16GE ? 2 : -1) : '') . ') ' . ' AND c.published = 1 ' . ' AND ( i.publish_up = ' . $db->Quote($nullDate) . ' OR i.publish_up <= ' . $_nowDate . ' )' . ' AND ( i.publish_down = ' . $db->Quote($nullDate) . ' OR i.publish_down >= ' . $_nowDate . ' )' . $andaccess . $andlang . $andcontenttypes;
     // AND-WHERE sub-clauses for text search ... (shared with filters)
     $and_where_filters = count($filters_where) ? implode(" ", $filters_where) : '';
     // ************************************************
     // Set variables used by filters creation mechanism
     // ************************************************
     global $fc_searchview;
     $fc_searchview['join_clauses'] = $join_clauses;
     $fc_searchview['join_clauses_with_text'] = $join_clauses_with_text;
     $fc_searchview['where_conf_only'] = $where_conf;
     // WHERE of the view (mainly configuration dependent)
     $fc_searchview['filters_where'] = $filters_where;
     // WHERE of the filters
     $fc_searchview['search'] = $text_where;
     // WHERE for text search
     $fc_searchview['params'] = $params;
     // view's parameters
     // *****************************************************************************************************
     // Execute search query.  NOTE this is skipped it if (a) no text-search and no (b) no filters are active
     // *****************************************************************************************************
     // Do not check for 'contentypes' this are based on configuration and not on form submitted data,
     // considering contenttypes or other configuration based parameters, will return all items on initial search view display !
     if (!count($filters_where) && !strlen($text)) {
         return array();
     }
     $print_logging_info = $params->get('print_logging_info');
     if ($print_logging_info) {
         global $fc_run_times;
         $start_microtime = microtime(true);
     }
     // *****************************************
     // Overcome possible group concat limitation
     // *****************************************
     $query = "SET SESSION group_concat_max_len = 9999999";
     $db->setQuery($query);
     $db->execute();
     // *************
     // Get the items
     // *************
     $query = 'SELECT SQL_CALC_FOUND_ROWS i.id' . $orderby_col . ' FROM #__content AS i' . $join_clauses_with_text . $orderby_join . $joinaccess . $where_conf . $and_where_filters . ' GROUP BY i.id ' . $orderby;
     //echo "Adv search plugin main SQL query: ".nl2br($query)."<br/><br/>";
     // NOTE: The plugin will return a PRECONFIGURED limited number of results, the SEARCH VIEW to do the pagination, splicing (appropriately) the data returned by all search plugins
     try {
         // Get items, we use direct query because some extensions break the SQL_CALC_FOUND_ROWS, so let's bypass them (at this point it is OK)
         // *** Usage of FOUND_ROWS() will fail when (e.g.) Joom!Fish or Falang are installed, in this case we will be forced to re-execute the query ...
         // PLUS, we don't need Joom!Fish or Falang layer at --this-- STEP which may slow down the query considerably in large sites
         $query_limited = $query . ' LIMIT ' . $search_limit . ' OFFSET 0';
         $rows = flexicontent_db::directQuery($query_limited);
         $item_ids = array();
         foreach ($rows as $row) {
             $item_ids[] = $row->id;
         }
         // Get current items total for pagination
         $db->setQuery("SELECT FOUND_ROWS()");
         $fc_searchview['view_total'] = $db->loadResult();
         $app->setUserState('fc_view_total_' . $view, $fc_searchview['view_total']);
     } catch (Exception $e) {
         // Get items via normal joomla SQL layer
         $db->setQuery(str_replace('SQL_CALC_FOUND_ROWS', '', $query), 0, $search_limit);
         $item_ids = $db->loadColumn(0);
     }
     if (!count($item_ids)) {
         return array();
     }
     // No items found
     // *****************
     // Get the item data
     // *****************
     $query_data = 'SELECT i.id, i.title AS title, i.created, i.id AS fc_item_id, i.access, ie.type_id, i.language' . (!$txtmode ? ', ie.search_index AS text' : ', GROUP_CONCAT(ts.search_index ORDER BY f.ordering ASC SEPARATOR \' \') AS text') . ', CASE WHEN CHAR_LENGTH(i.alias) THEN CONCAT_WS(\':\', i.id, i.alias) ELSE i.id END as slug' . ', CASE WHEN CHAR_LENGTH(c.alias) THEN CONCAT_WS(\':\', c.id, c.alias) ELSE c.id END as categoryslug' . ', CONCAT_WS( " / ", ' . $db->Quote($searchFlexicontent) . ', c.title, i.title ) AS section' . $select_access . ' FROM #__content AS i' . $join_clauses . $join_textsearch . $join_textfields . ' WHERE i.id IN (' . implode(',', $item_ids) . ') ' . ' GROUP BY i.id ' . ' ORDER BY FIELD(i.id, ' . implode(',', $item_ids) . ')';
     //echo nl2br($query)."<br/><br/>";
     $db->setQuery($query_data);
     $list = $db->loadObjectList();
     if ($db->getErrorNum()) {
         echo $db->getErrorMsg();
     }
     if ($print_logging_info) {
         @($fc_run_times['search_query_runtime'] += round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
     }
     // *************************************
     // Create item links and other variables
     // *************************************
     //echo "<pre>"; print_r($list); echo "</pre>";
     if ($list) {
         if (count($list) >= $search_limit) {
             $app->setUserState('fc_view_limit_max_' . $view, $search_limit);
         }
         $item_cats = FlexicontentFields::_getCategories($list);
         foreach ($list as $key => $item) {
             $item->text = preg_replace('/\\b' . $search_prefix . '/', '', $item->text);
             $item->categories = isset($item_cats[$item->id]) ? $item_cats[$item->id] : array();
             // in case of item categories missing
             // If joomla article view is allowed allowed and then search view may optional create Joomla article links
             if ($typeData[$item->type_id]->params->get('allow_jview', 0) && $typeData[$item->type_id]->params->get('search_jlinks', 1)) {
                 $item->href = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->categoryslug, $item->language));
             } else {
                 $item->href = JRoute::_(FlexicontentHelperRoute::getItemRoute($item->slug, $item->categoryslug, 0, $item));
             }
             $item->browsernav = $browsernav;
         }
     }
     return $list;
 }
        }
        ?>
			</ul>
		</div>
		<!-- EOF bottom block -->
	<?php 
    }
    ?>
	
	
	<?php 
    if ($readmore_shown) {
        ?>
	<span class="readmore group">
		<a href="<?php 
        echo JRoute::_(FlexicontentHelperRoute::getItemRoute($item->slug, $item->categoryslug, 0, $item));
        ?>
" class="readon">
			<?php 
        echo ' ' . ($item->params->get('readmore') ? $item->params->get('readmore') : JText::sprintf('FLEXI_READ_MORE', $item->title));
        ?>
		</a>
	</span>
	<?php 
    }
    ?>
	
	
	<?php 
    if ($item->event->afterDisplayContent) {
        ?>
    function onDisplayFieldValue(&$field, $item, $values = null, $prop = 'display')
    {
        if (!in_array($field->field_type, self::$field_types)) {
            return;
        }
        $field->label = JText::_($field->label);
        // Some variables
        $is_ingroup = !empty($field->ingroup);
        $use_ingroup = $field->parameters->get('use_ingroup', 0);
        $multiple = $use_ingroup || (int) $field->parameters->get('allow_multiple', 0);
        $image_source = $field->parameters->get('image_source', 0);
        // ***********************
        // One time initialization
        // ***********************
        static $initialized = null;
        static $app, $document, $option;
        static $isMobile, $isTablet, $useMobile;
        if ($initialized === null) {
            $app = JFactory::getApplication();
            $document = JFactory::getDocument();
            $option = JRequest::getVar('option');
            jimport('joomla.filesystem');
            // *****************************
            // Get isMobile / isTablet Flags
            // *****************************
            $cparams = JComponentHelper::getParams('com_flexicontent');
            $force_desktop_layout = $cparams->get('force_desktop_layout', 0);
            //$start_microtime = microtime(true);
            $mobileDetector = flexicontent_html::getMobileDetector();
            $isMobile = $mobileDetector->isMobile();
            $isTablet = $mobileDetector->isTablet();
            $useMobile = $force_desktop_layout ? $isMobile && !$isTablet : $isMobile;
            //$time_passed = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
            //printf('<br/>-- [Detect Mobile: %.3f s] ', $time_passed/1000000);
        }
        // **********************************************
        // Static FLAGS indicating if JS libs were loaded
        // **********************************************
        static $multiboxadded = false;
        static $fancyboxadded = false;
        static $gallerifficadded = false;
        static $elastislideadded = false;
        static $photoswipeadded = false;
        // *****************************
        // Current view variable / FLAGs
        // *****************************
        $realview = JRequest::getVar('view', FLEXI_ITEMVIEW);
        $view = JRequest::getVar('flexi_callview', $realview);
        $isFeedView = JRequest::getCmd('format', null) == 'feed';
        $isItemsManager = $app->isAdmin() && $realview == 'items' && $option == 'com_flexicontent';
        $isSite = $app->isSite();
        // *************************************************
        // TODO:  implement MODES >= 2, and remove this CODE
        // *************************************************
        if ($image_source > 1) {
            global $fc_folder_mode_err;
            if (empty($fc_folder_mode_err[$field->id])) {
                echo __FUNCTION__ . "(): folder-mode: " . $image_source . " not implemented please change image-source mode in image/gallery field with id: " . $field->id;
                $fc_folder_mode_err[$field->id] = 1;
                $image_source = 1;
            }
        }
        $all_media = $field->parameters->get('list_all_media_files', 0);
        $unique_thumb_method = $field->parameters->get('unique_thumb_method', 0);
        $dir = $field->parameters->get('dir');
        $dir_url = str_replace('\\', '/', $dir);
        // Check if using folder of original content being translated
        $of_usage = $field->untranslatable ? 1 : $field->parameters->get('of_usage', 0);
        $u_item_id = $of_usage && $item->lang_parent_id && $item->lang_parent_id != $item->id ? $item->lang_parent_id : $item->id;
        // FLAG to indicate if images are shared across fields, has the effect of adding field id to image thumbnails
        $multiple_image_usages = !$image_source && $all_media && $unique_thumb_method == 0;
        $extra_prefix = $multiple_image_usages ? 'fld' . $field->id . '_' : '';
        $usealt = $field->parameters->get('use_alt', 1);
        $alt_usage = $field->parameters->get('alt_usage', 0);
        $default_alt = $alt_usage == 2 ? $field->parameters->get('default_alt', '') : '';
        $usetitle = $field->parameters->get('use_title', 1);
        $title_usage = $field->parameters->get('title_usage', 0);
        $default_title = $title_usage == 2 ? JText::_($field->parameters->get('default_title', '')) : '';
        $usedesc = $field->parameters->get('use_desc', 1);
        $desc_usage = $field->parameters->get('desc_usage', 0);
        $default_desc = $desc_usage == 2 ? $field->parameters->get('default_desc', '') : '';
        $usecust1 = $field->parameters->get('use_cust1', 0);
        $cust1_usage = $field->parameters->get('cust1_usage', 0);
        $default_cust1 = $cust1_usage == 2 ? JText::_($field->parameters->get('default_cust1', '')) : '';
        $usecust2 = $field->parameters->get('use_cust2', 0);
        $cust2_usage = $field->parameters->get('cust2_usage', 0);
        $default_cust2 = $cust2_usage == 2 ? JText::_($field->parameters->get('default_cust2', '')) : '';
        // Separators / enclosing characters
        $remove_space = $field->parameters->get('remove_space', 0);
        $pretext = FlexicontentFields::replaceFieldValue($field, $item, $field->parameters->get('pretext', ''), 'pretext');
        $posttext = FlexicontentFields::replaceFieldValue($field, $item, $field->parameters->get('posttext', ''), 'posttext');
        $separatorf = $field->parameters->get('separatorf', 0);
        $opentag = FlexicontentFields::replaceFieldValue($field, $item, $field->parameters->get('opentag', ''), 'opentag');
        $closetag = FlexicontentFields::replaceFieldValue($field, $item, $field->parameters->get('closetag', ''), 'closetag');
        if ($pretext) {
            $pretext = $remove_space ? $pretext : $pretext . ' ';
        }
        if ($posttext) {
            $posttext = $remove_space ? $posttext : ' ' . $posttext;
        }
        switch ($separatorf) {
            case 0:
                $separatorf = '&nbsp;';
                break;
            case 1:
                $separatorf = '<br />';
                break;
            case 2:
                $separatorf = '&nbsp;|&nbsp;';
                break;
            case 3:
                $separatorf = ',&nbsp;';
                break;
            case 4:
                $separatorf = $closetag . $opentag;
                break;
            case 5:
                $separatorf = '';
                break;
            default:
                $separatorf = '&nbsp;';
                break;
        }
        // **************************************************
        // SETUP VALUES: retrieve, verify, load defaults, etc
        // **************************************************
        $values = $values ? $values : $field->value;
        // Intro-full mode get their values from item's parameters
        if ($image_source == -1) {
            $values = array();
            $_image_name = $view == 'item' ? 'fulltext' : 'intro';
            if ($item->images) {
                if (!is_object($item->images)) {
                    $item->images = new JRegistry($item->images);
                }
                //echo "<pre>"; print_r($item->images); echo "</pre>";
                $_image_path = $item->images->get('image_' . $_image_name, '');
                $image_by_params = array();
                // field attributes (mode-specific)
                $image_by_params['image_size'] = $_image_name;
                $image_by_params['image_path'] = $_image_path;
                // field attributes (value)
                $image_by_params['originalname'] = basename($_image_path);
                $image_by_params['alt'] = $item->images->get('image_' . $_image_name . '_alt', '');
                $image_by_params['title'] = $item->images->get('image_' . $_image_name . '_alt', '');
                $image_by_params['desc'] = $item->images->get('image_' . $_image_name . '_caption', '');
                $image_by_params['cust1'] = '';
                $image_by_params['cust2'] = '';
                $image_by_params['urllink'] = '';
                $values = array(serialize($image_by_params));
                //echo "<pre>"; print_r($image_by_params); echo "</pre>"; exit;
            }
        }
        // Check for deleted image files or image files that cannot be thumbnailed,
        // rebuilding thumbnails as needed, and then assigning checked values to a new array
        $usable_values = array();
        if ($values) {
            foreach ($values as $index => $value) {
                $value = unserialize($value);
                if (plgFlexicontent_fieldsImage::rebuildThumbs($field, $value, $item)) {
                    $usable_values[] = $values[$index];
                }
            }
        }
        $values =& $usable_values;
        // Allow for thumbnailing of the default image
        $field->using_default_value = false;
        if (!count($values)) {
            // Create default image to be used if  (a) no image assigned  OR  (b) images assigned have been deleted
            $default_image = $field->parameters->get('default_image', '');
            if ($default_image) {
                $default_image_val = array();
                // field attributes (default value specific)
                $default_image_val['default_image'] = $default_image;
                // holds complete relative path and indicates that it is default image for field
                // field attributes (value)
                $default_image_val['originalname'] = basename($default_image);
                $default_image_val['alt'] = $default_alt;
                $default_image_val['title'] = $default_title;
                $default_image_val['desc'] = $default_desc;
                $default_image_val['cust1'] = $default_cust1;
                $default_image_val['cust2'] = $default_cust2;
                $default_image_val['urllink'] = '';
                // Create thumbnails for default image
                if (plgFlexicontent_fieldsImage::rebuildThumbs($field, $default_image_val, $item)) {
                    $values = array(serialize($default_image_val));
                }
                // Also default image can (possibly) be used across multiple fields, so set flag to add field id to filenames of thumbnails
                $multiple_image_usages = true;
                $extra_prefix = 'fld' . $field->id . '_';
                $field->using_default_value = true;
            }
        }
        // *********************************************
        // Check for no values, and return empty display
        // *********************************************
        if (!count($values)) {
            $field->{$prop} = $is_ingroup ? array() : '';
            return;
        }
        // Assign (possibly) altered value array to back to the field
        $field->value = $values;
        // This is not done for onDisplayFieldValue, TODO check if this is needed
        // **************************************
        // Default display method depends on view
        // **************************************
        if ($prop == 'display' && ($view == FLEXI_ITEMVIEW || $view == 'category')) {
            $_method = $view == FLEXI_ITEMVIEW ? $field->parameters->get('default_method_item', 'display') : $field->parameters->get('default_method_cat', 'display_single_total');
        } else {
            $_method = $prop;
        }
        $cat_link_single_to = $field->parameters->get('cat_link_single_to', 1);
        // Calculate some flags, SINGLE image display and Link-to-Item FLAG
        $isSingle = isset(self::$single_displays[$_method]);
        $linkToItem = $_method == 'display_link' || $_method == 'display_single_link' || $_method == 'display_single_total_link' || $view != 'item' && $cat_link_single_to && $isSingle;
        // ************************
        // JS gallery configuration
        // ************************
        $usepopup = (int) $field->parameters->get('usepopup', 1);
        // use JS gallery
        $popuptype = (int) $field->parameters->get('popuptype', 1);
        // JS gallery type
        // Different for mobile clients
        $popuptype_mobile = (int) $field->parameters->get('popuptype_mobile', $popuptype);
        // this defaults to desktop when empty
        $popuptype = $useMobile ? $popuptype_mobile : $popuptype;
        // Enable/Disable GALLERY JS according to current view and according to other parameters
        $popupinview = $field->parameters->get('popupinview', array(FLEXI_ITEMVIEW, 'category', 'backend'));
        $popupinview = FLEXIUtilities::paramToArray($popupinview);
        if ($view == FLEXI_ITEMVIEW && !in_array(FLEXI_ITEMVIEW, $popupinview)) {
            $usepopup = 0;
        }
        if ($view == 'category' && !in_array('category', $popupinview)) {
            $usepopup = 0;
        }
        if ($view == 'module' && !in_array('module', $popupinview)) {
            $usepopup = 0;
        }
        if ($isItemsManager && !in_array('backend', $popupinview)) {
            $usepopup = 0;
        }
        // Enable/Disable GALLERY JS if linking to item view
        if ($linkToItem) {
            $usepopup = 0;
        }
        // Only allow multibox and fancybox in items manager, in other cases force fancybox
        if ($isItemsManager && !in_array($popuptype, array(1, 4))) {
            $popuptype = 4;
        }
        // Displays that need special container are not allowed when field in a group, force fancybox
        $no_container_needed = array(1, 2, 3, 4, 6);
        if ($is_ingroup && !in_array($popuptype, $no_container_needed)) {
            $popuptype = 4;
        }
        // Optionally group images from all image fields of current item ... or of all items in view too
        $grouptype = $field->parameters->get('grouptype', 1);
        $grouptype = $multiple ? 0 : $grouptype;
        // Field in gallery mode: Force grouping of images per field (current item)
        // Needed by some js galleries
        $thumb_w_s = $field->parameters->get('w_s', 120);
        $thumb_h_s = $field->parameters->get('h_s', 90);
        // ******************************
        // Hovering ToolTip configuration
        // ******************************
        $uselegend = $field->parameters->get('uselegend', 1);
        $tip_class = FLEXI_J30GE ? ' hasTooltip' : ' hasTip';
        // Enable/disable according to current view
        $legendinview = $field->parameters->get('legendinview', array(FLEXI_ITEMVIEW, 'category'));
        $legendinview = FLEXIUtilities::paramToArray($legendinview);
        if ($view == FLEXI_ITEMVIEW && !in_array(FLEXI_ITEMVIEW, $legendinview)) {
            $uselegend = 0;
        }
        if ($view == 'category' && !in_array('category', $legendinview)) {
            $uselegend = 0;
        }
        if ($isItemsManager && !in_array('backend', $legendinview)) {
            $uselegend = 0;
        }
        // load the tooltip library if required
        if ($uselegend && !FLEXI_J30GE) {
            JHTML::_('behavior.tooltip');
        }
        // **************************************
        // Title/Description in inline thumbnails
        // **************************************
        $showtitle = $field->parameters->get('showtitle', 0);
        $showdesc = $field->parameters->get('showdesc', 0);
        // *************************
        // Link to URL configuration
        // *************************
        $linkto_url = $field->parameters->get('linkto_url', 0);
        $url_target = $field->parameters->get('url_target', '_self');
        $isLinkToPopup = $linkto_url && ($url_target == 'multibox' || $url_target == 'fancybox');
        // Force opening in new window in backend, if URL target is _self
        if ($isItemsManager && $url_target == '_self') {
            $url_target = "_blank";
        }
        // Only allow multibox (and TODO: add fancybox) when linking to URL, in other cases force fancybox
        if ($isLinkToPopup && $url_target == 'multibox') {
            $popuptype = 1;
        }
        if ($isLinkToPopup && $url_target == 'fancybox') {
            $popuptype = 4;
        } else {
            if ($linkto_url) {
                $usepopup = 0;
            }
        }
        // ************************************
        // Social website sharing configuration
        // ************************************
        $useogp = $field->parameters->get('useogp', 0);
        $ogpinview = $field->parameters->get('ogpinview', array());
        $ogpinview = FLEXIUtilities::paramToArray($ogpinview);
        $ogpthumbsize = $field->parameters->get('ogpthumbsize', 2);
        // **********************************************
        // Load the configured (or the forced) JS gallery
        // **********************************************
        // Do not load JS, for value only displays
        if (!isset(self::$value_only_displays[$prop])) {
            // MultiBox maybe added in extra cases besides popup
            // (a) in Item manager, (b) When linking to URL in popup target
            $view_allows_mb = $isItemsManager || $isSite && !$isFeedView;
            $config_needs_mb = $isLinkToPopup || $usepopup && $popuptype == 1;
            if ($view_allows_mb && $config_needs_mb) {
                if (!$multiboxadded) {
                    flexicontent_html::loadFramework('jmultibox');
                    //echo $field->name.": multiboxadded";
                    $js = "\n\t\t\t\t\twindow.addEvent('domready', function(){\n\t\t\t\t\t\tjQuery('a.mb').jmultibox({\n\t\t\t\t\t\t\tinitialWidth: 250,  //(number) the width of the box when it first opens while loading the item. Default: 250\n\t\t\t\t\t\t\tinitialHeight: 250, //(number) the width of the box when it first opens while loading the item. Default: 250\n\t\t\t\t\t\t\tcontainer: document.body, //(element) the element that the box will take it coordinates from. Default: document.body\n\t\t\t\t\t\t\tcontentColor: '#000', //(string) the color of the content area inside the box. Default: #000\n\t\t\t\t\t\t\tshowNumbers: " . ($isItemsManager ? 'false' : 'true') . ",    //(boolean) show the number of the item e.g. 2/10. Default: true\n\t\t\t\t\t\t\tshowControls: " . ($isItemsManager ? 'false' : 'true') . ",   //(boolean) show the navigation controls. Default: true\n\t\t\t\t\t\t\tdescClassName: 'multiBoxDesc',  //(string) the classname of the divs that contain the description for the item. Default: false\n\t\t\t\t\t\t\tdescMinWidth: 400,     //(number) the min width of the description text, useful when the item is small. Default: 400\n\t\t\t\t\t\t\tdescMaxWidth: 600,     //(number) the max width of the description text, so it can wrap to multiple lines instead of being on a long single line. Useful when the item is large. Default: 600\n\t\t\t\t\t\t\tmovieWidth: 576,    //(number) the default width of the box that contains content of a movie type. Default: 576\n\t\t\t\t\t\t\tmovieHeight: 324,   //(number) the default height of the box that contains content of a movie type. Default: 324\n\t\t\t\t\t\t\toffset: {x: 0, y: 0},  //(object) containing x & y coords that adjust the positioning of the box. Default: {x:0, y:0}\n\t\t\t\t\t\t\tfixedTop: false,       //(number) gives the box a fixed top position relative to the container. Default: false\n\t\t\t\t\t\t\tpath: '',            //(string) location of the resources files, e.g. flv player, etc. Default: ''\n\t\t\t\t\t\t\topenFromLink: true,  //(boolean) opens the box relative to the link location. Default: true\n\t\t\t\t\t\t\topac:0.7,            //(decimal) overlay opacity Default: 0.7\n\t\t\t\t\t\t\tuseOverlay:false,    //(boolean) use a semi-transparent background. Default: false\n\t\t\t\t\t\t\toverlaybg:'01.png',  //(string) overlay image in 'overlays' folder. Default: '01.png'\n\t\t\t\t\t\t\tonOpen:function(){},   //(object) a function to call when the box opens. Default: function(){} \n\t\t\t\t\t\t\tonClose:function(){},  //(object) a function to call when the box closes. Default: function(){} \n\t\t\t\t\t\t\teasing:'swing',        //(string) effect of jQuery Default: 'swing'\n\t\t\t\t\t\t\tuseratio:false,        //(boolean) windows size follows ratio. (iframe or Youtube) Default: false\n\t\t\t\t\t\t\tratio:'90'             //(number) window ratio Default: '90'\n\t\t\t\t\t\t});\n\t\t\t\t\t})";
                    $document->addScriptDeclaration($js);
                    $multiboxadded = true;
                }
            }
            // Regardless if above has added multibox , we will add a different JS gallery if so configured because it maybe needed
            if (!$isSite || $isFeedView) {
                // Is backend OR it is a feed view, do not add any JS library
            } else {
                if ($usepopup) {
                    switch ($popuptype) {
                        // Add Fancybox image popup
                        case 4:
                            if (!$fancyboxadded) {
                                $fancyboxadded = true;
                                flexicontent_html::loadFramework('fancybox');
                            }
                            break;
                            // Add Galleriffic inline slideshow gallery
                        // Add Galleriffic inline slideshow gallery
                        case 5:
                            $inline_gallery = 1;
                            // unused
                            if (!$gallerifficadded) {
                                flexicontent_html::loadFramework('galleriffic');
                                $gallerifficadded = true;
                                $js = "\n\t\t\t\t\t\t//document.write('<style>.noscript { display: none; }</style>');\n\t\t\t\t\t\tjQuery(document).ready(function() {\n\t\t\t\t\t\t\t// We only want these styles applied when javascript is enabled\n\t\t\t\t\t\t\tjQuery('div.navigation').css({'width' : '150px', 'float' : 'left'});\n\t\t\t\t\t\t\tjQuery('div.content').css({'display' : 'inline-block', 'float' : 'none'});\n\t\t\t\n\t\t\t\t\t\t\t// Initially set opacity on thumbs and add\n\t\t\t\t\t\t\t// additional styling for hover effect on thumbs\n\t\t\t\t\t\t\tvar onMouseOutOpacity = 0.67;\n\t\t\t\t\t\t\tjQuery('#gf_thumbs ul.thumbs li').opacityrollover({\n\t\t\t\t\t\t\t\tmouseOutOpacity:   onMouseOutOpacity,\n\t\t\t\t\t\t\t\tmouseOverOpacity:  1.0,\n\t\t\t\t\t\t\t\tfadeSpeed:         'fast',\n\t\t\t\t\t\t\t\texemptionSelector: '.selected'\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// Initialize Advanced Galleriffic Gallery\n\t\t\t\t\t\t\tjQuery('#gf_thumbs').galleriffic({\n\t\t\t\t\t\t\t\t/*enableFancybox: true,*/\n\t\t\t\t\t\t\t\tdelay:                     2500,\n\t\t\t\t\t\t\t\tnumThumbs:                 4,\n\t\t\t\t\t\t\t\tpreloadAhead:              10,\n\t\t\t\t\t\t\t\tenableTopPager:            true,\n\t\t\t\t\t\t\t\tenableBottomPager:         true,\n\t\t\t\t\t\t\t\tmaxPagesToShow:            20,\n\t\t\t\t\t\t\t\timageContainerSel:         '#gf_slideshow',\n\t\t\t\t\t\t\t\tcontrolsContainerSel:      '#gf_controls',\n\t\t\t\t\t\t\t\tcaptionContainerSel:       '#gf_caption',\n\t\t\t\t\t\t\t\tloadingContainerSel:       '#gf_loading',\n\t\t\t\t\t\t\t\trenderSSControls:          true,\n\t\t\t\t\t\t\t\trenderNavControls:         true,\n\t\t\t\t\t\t\t\tplayLinkText:              'Play Slideshow',\n\t\t\t\t\t\t\t\tpauseLinkText:             'Pause Slideshow',\n\t\t\t\t\t\t\t\tprevLinkText:              '&lsaquo; Previous Photo',\n\t\t\t\t\t\t\t\tnextLinkText:              'Next Photo &rsaquo;',\n\t\t\t\t\t\t\t\tnextPageLinkText:          'Next &rsaquo;',\n\t\t\t\t\t\t\t\tprevPageLinkText:          '&lsaquo; Prev',\n\t\t\t\t\t\t\t\tenableHistory:             false,\n\t\t\t\t\t\t\t\tautoStart:                 false,\n\t\t\t\t\t\t\t\tsyncTransitions:           true,\n\t\t\t\t\t\t\t\tdefaultTransitionDuration: 900,\n\t\t\t\t\t\t\t\tonSlideChange:             function(prevIndex, nextIndex) {\n\t\t\t\t\t\t\t\t\t// 'this' refers to the gallery, which is an extension of jQuery('#gf_thumbs')\n\t\t\t\t\t\t\t\t\tthis.find('ul.thumbs').children()\n\t\t\t\t\t\t\t\t\t\t.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()\n\t\t\t\t\t\t\t\t\t\t.eq(nextIndex).fadeTo('fast', 1.0);\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tonPageTransitionOut:       function(callback) {\n\t\t\t\t\t\t\t\t\tthis.fadeTo('fast', 0.0, callback);\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tonPageTransitionIn:        function() {\n\t\t\t\t\t\t\t\t\tthis.fadeTo('fast', 1.0);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t});\n\t\t\t\t\t\t\t";
                                $document->addScriptDeclaration($js);
                            }
                            break;
                            // Add Elastislide inline carousel gallery (Responsive image gallery with togglable thumbnail-strip, plus previewer and description)
                        // Add Elastislide inline carousel gallery (Responsive image gallery with togglable thumbnail-strip, plus previewer and description)
                        case 7:
                            if (!$elastislideadded) {
                                flexicontent_html::loadFramework('elastislide');
                                $elastislideadded = true;
                            }
                            $uid = 'es_' . $field->name . "_fcitem" . $item->id;
                            $js = file_get_contents(JPATH_SITE . DS . 'components' . DS . 'com_flexicontent' . DS . 'librairies' . DS . 'elastislide' . DS . 'js' . DS . 'gallery_tmpl.js');
                            $js = str_replace('unique_gal_id', $uid, $js);
                            $js = str_replace('__thumb_width__', $field->parameters->get('w_s', 120), $js);
                            $document->addScriptDeclaration($js);
                            $document->addCustomTag('
					<script id="img-wrapper-tmpl_' . $uid . '" type="text/x-jquery-tmpl">	
						<div class="rg-image-wrapper">
							{{if itemsCount > 1}}
								<div class="rg-image-nav">
									<a href="#" class="rg-image-nav-prev">' . JText::_('FLEXI_PREVIOUS') . '</a>
									<a href="#" class="rg-image-nav-next">' . JText::_('FLEXI_NEXT') . '</a>
								</div>
							{{/if}}
							<div class="rg-image"></div>
							<div class="rg-loading"></div>
							<div class="rg-caption-wrapper">
								<div class="rg-caption" style="display:none;">
									<p></p>
								</div>
							</div>
						</div>
					</script>
					');
                            break;
                            // Add PhotoSwipe popup carousel gallery
                        // Add PhotoSwipe popup carousel gallery
                        case 8:
                            if (!$photoswipeadded) {
                                flexicontent_html::loadFramework('photoswipe');
                                $photoswipeadded = true;
                            }
                            break;
                    }
                }
            }
        }
        // *******************************
        // Prepare for value handling loop
        // *******************************
        // Extra thumbnails sub-folder for various
        if ($field->using_default_value) {
            $extra_folder = '';
            // default value
        } else {
            if ($image_source == -1) {
                $extra_folder = 'intro_full';
                // intro-full images mode
            } else {
                if ($image_source > 0) {
                    $extra_folder = 'item_' . $u_item_id . '_field_' . $field->id;
                    // folder-mode 1
                    if ($image_source > 1) {
                    }
                    // TODO
                } else {
                    $extra_folder = '';
                    // db-mode
                }
            }
        }
        // Create thumbs/image Folder and URL paths
        $thumb_folder = JPATH_SITE . DS . JPath::clean($dir . ($extra_folder ? DS . $extra_folder : ''));
        $thumb_urlpath = $dir_url . ($extra_folder ? '/' . $extra_folder : '');
        if ($field->using_default_value) {
            // default image of this field, these are relative paths up to site root
            $orig_urlpath = str_replace('\\', '/', dirname($default_image_val['default_image']));
        } else {
            if ($image_source == -1) {
                // intro-full image values, these are relative paths up to the site root, must be calculated later !!
                $orig_urlpath = str_replace('\\', '/', dirname($image_by_params['image_path']));
            } else {
                if ($image_source > 0) {
                    // various folder-mode(s)
                    $orig_urlpath = $thumb_urlpath . '/original';
                } else {
                    // db-mode
                    $cparams = JComponentHelper::getParams('com_flexicontent');
                    $orig_urlpath = str_replace('\\', '/', JPath::clean($cparams->get('file_path', 'components/com_flexicontent/uploads')));
                }
            }
        }
        // Initialize value handling arrays and loop's common variables
        $i = -1;
        $field->{$prop} = array();
        $field->thumbs_src['backend'] = array();
        $field->thumbs_src['small'] = array();
        $field->thumbs_src['medium'] = array();
        $field->thumbs_src['large'] = array();
        $field->thumbs_src['original'] = array();
        $field->{"display_backend_src"} = array();
        $field->{"display_small_src"} = array();
        $field->{"display_medium_src"} = array();
        $field->{"display_large_src"} = array();
        $field->{"display_original_src"} = array();
        $cust1_label = JText::_('FLEXI_FIELD_IMG_CUST1');
        $cust2_label = JText::_('FLEXI_FIELD_IMG_CUST2');
        // Decide thumbnail to use
        $thumb_size = 0;
        if ($isItemsManager) {
            $thumb_size = -1;
        } else {
            if ($view == 'category') {
                $thumb_size = $field->parameters->get('thumbincatview', 1);
            } else {
                if ($view == FLEXI_ITEMVIEW) {
                    $thumb_size = $field->parameters->get('thumbinitemview', 2);
                }
            }
        }
        // ***************
        // The values loop
        // ***************
        foreach ($values as $val) {
            // Unserialize value's properties and check for empty original name property
            $value = unserialize($val);
            $image_name = trim(@$value['originalname']);
            if (!strlen($image_name)) {
                if ($is_ingroup) {
                    $field->{$prop}[] = '';
                }
                // add empty position to the display array
                continue;
            }
            $i++;
            // Create thumbnails urls, note thumbnails have already been verified above
            $wl = $field->parameters->get('w_l', 800);
            $hl = $field->parameters->get('h_l', 600);
            // Optional properties
            $title = $usetitle && @$value['title'] ? $value['title'] : '';
            $alt = $usealt && @$value['alt'] ? $value['alt'] : flexicontent_html::striptagsandcut($item->title, 60);
            $desc = $usedesc && @$value['desc'] ? $value['desc'] : '';
            // Optional custom properties
            $cust1 = $usecust1 && @$value['cust1'] ? $value['cust1'] : '';
            $desc .= $cust1 ? $cust1_label . ': ' . $cust1 : '';
            // ... Append custom properties to description
            $cust2 = $usecust2 && @$value['cust2'] ? $value['cust2'] : '';
            $desc .= $cust2 ? $cust2_label . ': ' . $cust2 : '';
            // ... Append custom properties to description
            // HTML encode output
            $title = htmlspecialchars($title, ENT_COMPAT, 'UTF-8');
            $alt = htmlspecialchars($alt, ENT_COMPAT, 'UTF-8');
            $desc = htmlspecialchars($desc, ENT_COMPAT, 'UTF-8');
            $srcb = $thumb_urlpath . '/b_' . $extra_prefix . $image_name;
            // backend
            $srcs = $thumb_urlpath . '/s_' . $extra_prefix . $image_name;
            // small
            $srcm = $thumb_urlpath . '/m_' . $extra_prefix . $image_name;
            // medium
            $srcl = $thumb_urlpath . '/l_' . $extra_prefix . $image_name;
            // large
            $srco = $orig_urlpath . '/' . $image_name;
            // original image
            // Create a popup url link
            $urllink = @$value['urllink'] ? $value['urllink'] : '';
            if ($urllink && false === strpos($urllink, '://')) {
                $urllink = 'http://' . $urllink;
            }
            // Create a popup tooltip (legend)
            $class = 'fc_field_image';
            if ($uselegend && (!empty($title) || !empty($desc))) {
                $class .= $tip_class;
                $legend = ' title="' . flexicontent_html::getToolTip($title, $desc, 0, 1) . '"';
            } else {
                $legend = '';
            }
            // Handle single image display, with/without total, TODO: verify all JS handle & ignore display none on the img TAG
            $style = $i != 0 && $isSingle ? 'display:none;' : '';
            // Create a unique id for the link tags, and a class name for image tags
            $uniqueid = $item->id . '_' . $field->id . '_' . $i;
            switch ($thumb_size) {
                case -1:
                    $src = $srcb;
                    break;
                case 1:
                    $src = $srcs;
                    break;
                case 2:
                    $src = $srcm;
                    break;
                case 3:
                    $src = $srcl;
                    break;
                    // this makes little sense, since both thumbnail and popup image are size 'large'
                // this makes little sense, since both thumbnail and popup image are size 'large'
                case 4:
                    $src = $srco;
                    break;
                default:
                    $src = $srcs;
                    break;
            }
            // Create a grouping name
            switch ($grouptype) {
                case 0:
                    $group_name = 'fcview_' . $view . '_fcitem_' . $item->id . '_fcfield_' . $field->id;
                    break;
                case 1:
                    $group_name = 'fcview_' . $view . '_fcitem_' . $item->id;
                    break;
                case 2:
                    $group_name = 'fcview_' . $view;
                    break;
                default:
                    $group_name = '';
                    break;
            }
            // ADD some extra (display) properties that point to all sizes, currently SINGLE IMAGE only
            if ($is_ingroup) {
                // In case of field displayed via in fieldgroup, this is an array
                $field->{"display_backend_src"}[] = JURI::root(true) . '/' . $srcb;
                $field->{"display_small_src"}[] = JURI::root(true) . '/' . $srcs;
                $field->{"display_medium_src"}[] = JURI::root(true) . '/' . $srcm;
                $field->{"display_large_src"}[] = JURI::root(true) . '/' . $srcl;
                $field->{"display_original_src"}[] = JURI::root(true) . '/' . $srco;
            } else {
                if ($i == 0) {
                    // Field displayed not via fieldgroup return only the 1st value
                    $field->{"display_backend_src"} = JURI::root(true) . '/' . $srcb;
                    $field->{"display_small_src"} = JURI::root(true) . '/' . $srcs;
                    $field->{"display_medium_src"} = JURI::root(true) . '/' . $srcm;
                    $field->{"display_large_src"} = JURI::root(true) . '/' . $srcl;
                    $field->{"display_original_src"} = JURI::root(true) . '/' . $srco;
                }
            }
            $field->thumbs_src['backend'][] = JURI::root(true) . '/' . $srcb;
            $field->thumbs_src['small'][] = JURI::root(true) . '/' . $srcs;
            $field->thumbs_src['medium'][] = JURI::root(true) . '/' . $srcm;
            $field->thumbs_src['large'][] = JURI::root(true) . '/' . $srcl;
            $field->thumbs_src['original'][] = JURI::root(true) . '/' . $srco;
            $field->thumbs_path['backend'][] = JPATH_SITE . DS . $srcb;
            $field->thumbs_path['small'][] = JPATH_SITE . DS . $srcs;
            $field->thumbs_path['medium'][] = JPATH_SITE . DS . $srcm;
            $field->thumbs_path['large'][] = JPATH_SITE . DS . $srcl;
            $field->thumbs_path['original'][] = JPATH_SITE . DS . $srco;
            // Suggest image for external use, e.g. for Facebook etc
            if ($isSite && !$isFeedView && $useogp) {
                if (in_array($view, $ogpinview)) {
                    switch ($ogpthumbsize) {
                        case 1:
                            $ogp_src = $field->thumbs_src['small'][$i];
                            break;
                            // this maybe problematic, since it maybe too small or not accepted by social website
                        // this maybe problematic, since it maybe too small or not accepted by social website
                        case 2:
                            $ogp_src = $field->thumbs_src['medium'][$i];
                            break;
                        case 3:
                            $ogp_src = $field->thumbs_src['large'][$i];
                            break;
                        case 4:
                            $ogp_src = $field->thumbs_src['original'][$i];
                            break;
                        default:
                            $ogp_src = $field->thumbs_src['medium'][$i];
                            break;
                    }
                    $document->addCustomTag('<link rel="image_src" href="' . $ogp_src . '" />');
                    $document->addCustomTag('<meta property="og:image" content="' . $ogp_src . '" />');
                }
            }
            // ****************************************************************
            // CHECK if we were asked for value only display (e.g. image source)
            // if so we will not be creating the HTML code for Image / Gallery
            // ****************************************************************
            if (isset(self::$value_only_displays[$prop])) {
                continue;
            }
            // *********************************************************
            // Create image tags (according to configuration parameters)
            // that will be used for the requested 'display' variable
            // *********************************************************
            switch ($prop) {
                case 'display_backend':
                    $img_legend = '<img src="' . JURI::root(true) . '/' . $srcb . '" alt="' . $alt . '"' . $legend . ' class="' . $class . '" itemprop="image"/>';
                    $img_nolegend = '<img src="' . JURI::root(true) . '/' . $srcb . '" alt="' . $alt . '" class="' . $class . '" itemprop="image"/>';
                    break;
                case 'display_small':
                    $img_legend = '<img src="' . JURI::root(true) . '/' . $srcs . '" alt="' . $alt . '"' . $legend . ' class="' . $class . '" itemprop="image"/>';
                    $img_nolegend = '<img src="' . JURI::root(true) . '/' . $srcs . '" alt="' . $alt . '" class="' . $class . '" itemprop="image"/>';
                    break;
                case 'display_medium':
                    $img_legend = '<img src="' . JURI::root(true) . '/' . $srcm . '" alt="' . $alt . '"' . $legend . ' class="' . $class . '" itemprop="image"/>';
                    $img_nolegend = '<img src="' . JURI::root(true) . '/' . $srcm . '" alt="' . $alt . '" class="' . $class . '" itemprop="image"/>';
                    break;
                case 'display_large':
                    $img_legend = '<img src="' . JURI::root(true) . '/' . $srcl . '" alt="' . $alt . '"' . $legend . ' class="' . $class . '" itemprop="image"/>';
                    $img_nolegend = '<img src="' . JURI::root(true) . '/' . $srcl . '" alt="' . $alt . '" class="' . $class . '" itemprop="image"/>';
                    break;
                case 'display_original':
                    $img_legend = '<img src="' . JURI::root(true) . '/' . $srco . '" alt="' . $alt . '"' . $legend . ' class="' . $class . '" itemprop="image"/>';
                    $img_nolegend = '<img src="' . JURI::root(true) . '/' . $srco . '" alt="' . $alt . '" class="' . $class . '" itemprop="image"/>';
                    break;
                case 'display':
                default:
                    $img_legend = '<img src="' . JURI::root(true) . '/' . $src . '" alt="' . $alt . '"' . $legend . ' class="' . $class . '" itemprop="image"/>';
                    $img_nolegend = '<img src="' . JURI::root(true) . '/' . $src . '" alt="' . $alt . '" class="' . $class . '" itemprop="image"/>';
                    break;
            }
            // *************************************************
            // Create thumbnail appending text (not linked text)
            // *************************************************
            // For galleries that are not inline/special, we can have inline text ??
            $inline_info = '';
            if ($linkto_url || ($prop == 'display_large' || $prop == 'display_original') || !$usepopup || $popuptype != 5 && $popuptype != 7) {
                // Add inline display of title/desc
                if ($showtitle && $title || $showdesc && $desc) {
                    $inline_info = '<div class="fc_img_tooltip_data alert alert-info" style="' . $style . '" >';
                }
                if ($showtitle && $title) {
                    $inline_info .= '<div class="fc_img_tooltip_title" style="line-height:1em; font-weight:bold;">' . $title . '</div>';
                }
                if ($showdesc && $desc) {
                    $inline_info .= '<div class="fc_img_tooltip_desc" style="line-height:1em;">' . $desc . '</div>';
                }
                if ($showtitle && $title || $showdesc && $desc) {
                    $inline_info .= '</div>';
                }
            }
            // *********************************************
            // FINALLY CREATE the field display variable ...
            // *********************************************
            if ($linkToItem) {
                // CASE 0: Add single image display information (e.g. image count)
                $item_link = JRoute::_(FlexicontentHelperRoute::getItemRoute($item->slug, $item->categoryslug, 0, $item));
                $field->{$prop}[] = '<span style="display: inline-block; text-align:center; ">
					<a href="' . $item_link . '" style="display: inline-block;">
					' . $img_nolegend . '
					</a><br/>' . ($_method == 'display_single_total' || $_method == 'display_single_total_link' ? '
					<span class="fc_img_total_data badge badge-info" style="display: inline-block;" >
						' . count($values) . ' ' . JText::_('FLEXI_IMAGES') . '
					</span>' : '') . '
				</span>';
                // If single display and not in field group then do not add more images
                if (!$is_ingroup && $isSingle) {
                    break;
                }
            } else {
                if ($linkto_url) {
                    // CASE 1: Handle linking to a URL instead of image zooming popup
                    if (!$urllink) {
                        // CASE: Just image thumbnail since url link is empty
                        $field->{$prop}[] = $pretext . '<div class="fc_img_container">' . $img_legend . $inline_info . '</div>' . $posttext;
                    } else {
                        if ($url_target == 'multibox') {
                            // CASE: Link to URL that opens inside a popup via multibox
                            $field->{$prop}[] = $pretext . '
					<script>document.write(\'<a style="' . $style . '" href="' . $urllink . '" id="mb' . $uniqueid . '" class="mb" rel="width:\'+(jQuery(window).width()-150)+\',height:\'+(jQuery(window).height()-150)+\'">\')</script>
						' . $img_legend . '
					<script>document.write(\'</a>\')</script>
					<div class="multiBoxDesc mbox_img_url mb' . $uniqueid . '">' . ($desc ? $desc : $title) . '</div>
					' . $inline_info . $posttext;
                        } else {
                            if ($url_target == 'fancybox') {
                                // CASE: Link to URL that opens inside a popup via fancybox
                                $field->{$prop}[] = $pretext . '
					<span class="fc_image_thumb" style="' . $style . '; cursor: pointer;" ' . 'onclick="jQuery.fancybox.open([{ type: \'iframe\', href: \'' . $urllink . '\', topRatio: 0.9, leftRatio: 0.9, title: \'' . ($desc ? $title . ': ' . $desc : $title) . '\' }], { padding : 0});"
					>
						' . $img_legend . '
					</span>
					' . $inline_info . $posttext;
                            } else {
                                // CASE: Just link to URL without popup
                                $field->{$prop}[] = $pretext . '
					<a href="' . $urllink . '" target="' . $url_target . '">
						' . $img_legend . '
					</a>
					' . $inline_info . $posttext;
                            }
                        }
                    }
                } else {
                    if (!$usepopup || ($prop == 'display_large' || $prop == 'display_original')) {
                        // CASE 2: // No gallery code ... just apply pretext/posttext
                        $field->{$prop}[] = $pretext . $img_legend . $inline_info . $posttext;
                    } else {
                        if ($popuptype == 5 || $popuptype == 7) {
                            // CASE 3: Inline/special galleries OR --> GALLERIES THAT NEED SPECIAL ENCLOSERS
                            // !!! ... pretext/posttext/inline_info/etc not meaningful or not supported or not needed
                            switch ($popuptype) {
                                case 5:
                                    // Galleriffic inline slideshow gallery
                                    $group_str = '';
                                    // image grouping: not needed / not applicatble
                                    $field->{$prop}[] = '<a href="' . $srcl . '" class="fc_image_thumb thumb" name="drop">
							' . $img_legend . '
						</a>
						<div class="caption">
							<b>' . $title . '</b>
							<br/>' . $desc . '
						</div>';
                                    break;
                                case 7:
                                    // Elastislide inline carousel gallery (Responsive image gallery with togglable thumbnail-strip, plus previewer and description)
                                    // *** NEEDS: thumbnail list must be created with large size thubmnails, these will be then thumbnailed by the JS gallery code
                                    $title_attr = $desc ? $desc : $title;
                                    $img_legend_custom = '
						 <img src="' . JURI::root(true) . '/' . $src . '" alt ="' . $alt . '"' . $legend . ' class="' . $class . '"
						 	data-large="' . JURI::root(true) . '/' . $srcl . '" data-description="' . $title_attr . '" itemprop="image"/>
					';
                                    $group_str = $group_name ? 'rel="[' . $group_name . ']"' : '';
                                    $field->{$prop}[] = '
						<li><a href="javascript:;" class="fc_image_thumb">
							' . $img_legend_custom . '
						</a></li>';
                                    break;
                                default:
                                    // ERROR unhandled INLINE GALLERY case
                                    $field->{$prop}[] = ' Unhandled INLINE GALLERY case in image with field name: {$field->name} ';
                                    break;
                            }
                        } else {
                            // CASE 4: Popup galleries
                            switch ($popuptype) {
                                case 1:
                                    // Multibox image popup
                                    $group_str = $group_name ? 'rel="[' . $group_name . ']"' : '';
                                    $field->{$prop}[] = $pretext . '<a style="' . $style . '" href="' . $srcl . '" id="mb' . $uniqueid . '" class="fc_image_thumb mb" ' . $group_str . ' >
							' . $img_legend . '
						</a>
						<div class="multiBoxDesc mb' . $uniqueid . '">' . ($desc ? '<span class="badge">' . $title . '</span> ' . $desc : $title) . '</div>' . $inline_info . $posttext;
                                    break;
                                case 2:
                                    // Rokbox image popup
                                    $title_attr = $desc ? $desc : $title;
                                    $group_str = '';
                                    // no support for image grouping
                                    $field->{$prop}[] = $pretext . '<a style="' . $style . '" href="' . $srcl . '" rel="rokbox[' . $wl . ' ' . $hl . ']" ' . $group_str . ' title="' . $title_attr . '" class="fc_image_thumb" data-rokbox data-rokbox-caption="' . $title_attr . '">
							' . $img_legend . '
						</a>' . $inline_info . $posttext;
                                    break;
                                case 3:
                                    // JCE popup image popup
                                    $title_attr = $desc ? $title . ': ' . $desc : $title;
                                    // does not support HTML
                                    $group_str = $group_name ? 'rel="group[' . $group_name . ']"' : '';
                                    $field->{$prop}[] = $pretext . '<a style="' . $style . '" href="' . $srcl . '"  class="fc_image_thumb jcepopup" ' . $group_str . ' title="' . $title_attr . '">
							' . $img_nolegend . '
						</a>' . $inline_info . $posttext;
                                    break;
                                case 4:
                                    // Fancybox image popup
                                    $title_attr = $desc ? '<span class=\'badge\'>' . $title . '</span> ' . $desc : $title;
                                    $group_str = $group_name ? 'data-fancybox-group="' . $group_name . '"' : '';
                                    $field->{$prop}[] = $pretext . '<a style="' . $style . '" href="' . $srcl . '"  class="fc_image_thumb fancybox" ' . $group_str . ' title="' . $title_attr . '">
							' . $img_legend . '
						</a>' . $inline_info . $posttext;
                                    break;
                                case 6:
                                    // (Widgetkit) SPOTlight image popup
                                    $title_attr = $desc ? $desc : $title;
                                    $group_str = $group_name ? 'data-spotlight-group="' . $group_name . '"' : '';
                                    $field->{$prop}[] = $pretext . '<a style="' . $style . '" href="' . $srcl . '" class="fc_image_thumb" data-lightbox="on" data-spotlight="effect:bottom" ' . $group_str . ' title="' . $title_attr . '">
							' . $img_legend . '
							<div class="overlay">
								' . '<b>' . $title . '</b>: ' . $desc . '
							</div>
						</a>' . $inline_info . $posttext;
                                    break;
                                case 8:
                                    // PhotoSwipe popup carousel gallery
                                    $group_str = $group_name ? 'rel="[' . $group_name . ']"' : '';
                                    $field->{$prop}[] = $pretext . '<a style="' . $style . '" href="' . $srcl . '" ' . $group_str . ' class="fc_image_thumb">
							' . $img_legend . '
						</a>' . $inline_info . $posttext;
                                    break;
                                default:
                                    // Unknown / Other Gallery Type, just add thumbails ... maybe pretext/posttext/separator/opentag/closetag will add a gallery
                                    $field->{$prop}[] = $pretext . $img_legend . $inline_info . $posttext;
                                    break;
                            }
                        }
                    }
                }
            }
        }
        // **************************************************************
        // Apply separator and open/close tags and handle SPECIAL CASEs:
        // by adding (container) HTML required by some JS image libraries
        // **************************************************************
        // Using in field group, return array
        if ($is_ingroup) {
            return;
        }
        // Check for value only displays and return
        if (isset(self::$value_only_displays[$prop])) {
            return;
        }
        // Check for no values found
        if (!count($field->{$prop})) {
            $field->{$prop} = '';
            return;
        }
        // Galleriffic inline slideshow gallery
        if ($usepopup && $popuptype == 5) {
            $field->{$prop} = '
			<div id="gf_container">
				<div id="gallery" class="content">
					<div id="gf_controls" class="controls"></div>
					<div class="slideshow-container">
						<div id="gf_loading" class="loader"></div>
						<div id="gf_slideshow" class="slideshow"></div>
					</div>
					<div id="gf_caption" class="caption-container"></div>
				</div>
				<div id="gf_thumbs" class="navigation">
					<ul class="thumbs noscript">
						<li>
						' . implode("</li>\n<li>", $field->{$prop}) . '
						</li>
					</ul>
				</div>
				<div style="clear: both;"></div>
			</div>
			';
        } else {
            if ($usepopup && $popuptype == 7) {
                //$max_width = $field->parameters->get( 'w_l', 800 );
                // this should be size of previewer aka size of large image thumbnail
                $uid = 'es_' . $field->name . "_fcitem" . $item->id;
                $field->{$prop} = '
			<div id="rg-gallery_' . $uid . '" class="rg-gallery" >
				<div class="rg-thumbs">
					<!-- Elastislide Carousel Thumbnail Viewer -->
					<div class="es-carousel-wrapper">
						<div class="es-nav">
							<span class="es-nav-prev">' . JText::_('FLEXI_PREVIOUS') . '</span>
							<span class="es-nav-next">' . JText::_('FLEXI_NEXT') . '</span>
						</div>
						<div class="es-carousel">
							<ul>
								' . implode('', $field->{$prop}) . '
							</ul>
						</div>
					</div>
					<!-- End Elastislide Carousel Thumbnail Viewer -->
				</div><!-- rg-thumbs -->
			</div><!-- rg-gallery -->
			';
            } else {
                if ($usepopup && $popuptype == 8) {
                    $field->{$prop} = '
			<span class="photoswipe_fccontainer" >
				' . implode($separatorf, $field->{$prop}) . '
			</span>
			';
                } else {
                    $field->{$prop} = implode($separatorf, $field->{$prop});
                }
            }
        }
        // Apply open/close tags
        $field->{$prop} = $opentag . $field->{$prop} . $closetag;
    }
			<?php //echo @ $item->editbutton; ?>
			<?php //echo @ $item->statebutton; ?>
			<?php //echo @ $item->approvalbutton; ?>
			
			<?php if ($this->params->get('show_comments_count')) : ?>
				<?php if ( isset($this->comments[ $item->id ]->total) ) : ?>
				<div class="fc_comments_count_nopad hasTip" alt="<?php echo JText::_('FLEXI_NUM_OF_COMMENTS');?>" title="<?php echo JText::_('FLEXI_NUM_OF_COMMENTS');?>::<?php echo JText::_('FLEXI_NUM_OF_COMMENTS_TIP');?>">
					<?php echo $this->comments[ $item->id ]->total; ?>
				</div>
				<?php endif; ?>
			<?php endif; ?>
			
			<!-- BOF item title -->
			<?php if ($show_title) : ?>
				<?php if ($link_titles) : ?>
					<a class="fc_item_title" href="<?php echo JRoute::_(FlexicontentHelperRoute::getItemRoute($item->slug, $item->categoryslug, 0, $item)); ?>"><?php echo $item->title; ?></a>
				<?php else : echo $item->title; endif; ?>
			<?php endif; ?>
			<!-- EOF item title -->
			
			<?php echo $markup_tags; ?>
			
			</td>
		<?php endif; ?>
	
	
		<!-- BOF item fields -->
<?php foreach ($columns as $name => $label) : ?>

   <?php
   $link='';
 static function createItemsListHTML(&$params, &$item_list, $isform = 0, &$parentfield, &$parentitem, &$_item_data = null)
 {
     $db = JFactory::getDBO();
     global $globalcats, $globalnoroute, $fc_run_times;
     if (!is_array($globalnoroute)) {
         $globalnoroute = array();
     }
     // Get fields of type relation
     static $disallowed_fieldnames = null;
     $disallowed_fields = array('relation', 'relation_reverse');
     if ($disallowed_fieldnames === null) {
         $query = "SELECT name FROM #__flexicontent_fields WHERE field_type IN ('" . implode("','", $disallowed_fields) . "')";
         $db->setQuery($query);
         $field_name_col = FLEXI_J16GE ? $db->loadColumn() : $db->loadResultArray();
         $disallowed_fieldnames = !$field_name_col ? array() : array_flip($field_name_col);
     }
     // Prefix - Suffix - Separator parameters, replacing other field values if found
     $remove_space = $params->get('remove_space', 0);
     $pretext = $params->get($isform ? 'pretext_form' : 'pretext', '');
     $posttext = $params->get($isform ? 'posttext_form' : 'posttext', '');
     $separatorf = $params->get($isform ? 'separator' : 'separatorf');
     $opentag = $params->get($isform ? 'opentag_form' : 'opentag', '');
     $closetag = $params->get($isform ? 'closetag_form' : 'closetag', '');
     if ($pretext) {
         $pretext = $remove_space ? $pretext : $pretext . ' ';
     }
     if ($posttext) {
         $posttext = $remove_space ? $posttext : ' ' . $posttext;
     }
     switch ($separatorf) {
         case 0:
             $separatorf = '&nbsp;';
             break;
         case 1:
             $separatorf = '<br />';
             break;
         case 2:
             $separatorf = '&nbsp;|&nbsp;';
             break;
         case 3:
             $separatorf = ',&nbsp;';
             break;
         case 4:
             $separatorf = $closetag . $opentag;
             break;
         case 5:
             $separatorf = '';
             break;
         default:
             $separatorf = '&nbsp;';
             break;
     }
     // some parameter shortcuts
     $relitem_html = $params->get($isform ? 'relitem_html_form' : 'relitem_html', '__display_text__');
     $displayway = $params->get($isform ? 'displayway_form' : 'displayway', 1);
     $addlink = $params->get($isform ? 'addlink_form' : 'addlink', 1);
     $addtooltip = $params->get($isform ? 'addtooltip_form' : 'addtooltip', 1);
     // Parse and identify custom fields
     $result = preg_match_all("/\\{\\{([a-zA-Z_0-9]+)(##)?([a-zA-Z_0-9]+)?\\}\\}/", $relitem_html, $field_matches);
     $custom_field_reps = $result ? $field_matches[0] : array();
     $custom_field_names = $result ? $field_matches[1] : array();
     $custom_field_methods = $result ? $field_matches[3] : array();
     /*foreach ($custom_field_names as $i => $custom_field_name)
     			$parsed_fields[] = $custom_field_names[$i] . ($custom_field_methods[$i] ? "->". $custom_field_methods[$i] : "");
     		echo "$relitem_html :: Fields for Related Items List: ". implode(", ", $parsed_fields ? $parsed_fields : array() ) ."<br/>\n";*/
     // Parse and identify language strings and then make language replacements
     $result = preg_match_all("/\\%\\%([^%]+)\\%\\%/", $relitem_html, $translate_matches);
     $translate_strings = $result ? $translate_matches[1] : array('FLEXI_READ_MORE_ABOUT');
     foreach ($translate_strings as $translate_string) {
         $relitem_html = str_replace('%%' . $translate_string . '%%', JText::_($translate_string), $relitem_html);
     }
     foreach ($item_list as $result) {
         // Check if related item is published and skip if not published
         if ($result->state != 1 && $result->state != -5) {
             continue;
         }
         $itemslug = $result->id . ":" . $result->alias;
         $catslug = "";
         // Check if removed from category or inside a noRoute category or inside a non-published category
         // and use main category slug or other routable & published category slug
         $catid_arr = explode(",", $result->catidlist);
         $catalias_arr = explode(",", $result->cataliaslist);
         for ($i = 0; $i < count($catid_arr); $i++) {
             $itemcataliases[$catid_arr[$i]] = $catalias_arr[$i];
         }
         $rel_itemid = $result->id;
         $rel_catid = !empty($result->rel_catid) ? $result->rel_catid : $result->catid;
         if (isset($itemcataliases[$rel_catid]) && !in_array($rel_catid, $globalnoroute) && $globalcats[$rel_catid]->published) {
             $catslug = $rel_catid . ":" . $itemcataliases[$rel_catid];
         } else {
             if (!in_array($result->catid, $globalnoroute) && $globalcats[$result->catid]->published) {
                 $catslug = $globalcats[$result->catid]->slug;
             } else {
                 foreach ($catid_arr as $catid) {
                     if (!in_array($catid, $globalnoroute) && $globalcats[$catid]->published) {
                         $catslug = $globalcats[$catid]->slug;
                         break;
                     }
                 }
             }
         }
         $result->slug = $itemslug;
         $result->categoryslug = $catslug;
     }
     // Perform field's display replacements
     if ($i_slave = $parentfield ? $parentitem->id . "_" . $parentfield->id : '') {
         $fc_run_times['render_subfields'][$i_slave] = 0;
     }
     foreach ($custom_field_names as $i => $custom_field_name) {
         if (isset($disallowed_fieldnames[$custom_field_name])) {
             continue;
         }
         if ($custom_field_methods[$i] == 'label') {
             continue;
         }
         if ($i_slave) {
             $start_microtime = microtime(true);
         }
         $display_var = $custom_field_methods[$i] ? $custom_field_methods[$i] : 'display';
         FlexicontentFields::getFieldDisplay($item_list, $custom_field_name, $custom_field_values = null, $display_var);
         if ($i_slave) {
             $fc_run_times['render_subfields'][$i_slave] += round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
         }
     }
     $tooltip_class = FLEXI_J30GE ? 'hasTooltip' : 'hasTip';
     $display = array();
     foreach ($item_list as $result) {
         $url_read_more = JText::_(isset($_item_data->url_read_more) ? $_item_data->url_read_more : 'FLEXI_READ_MORE_ABOUT', 1);
         $url_class = isset($_item_data->url_class) ? $_item_data->url_class : 'relateditem';
         // Check if related item is published and skip if not published
         if ($result->state != 1 && $result->state != -5) {
             continue;
         }
         // a. Replace some custom made strings
         $item_url = JRoute::_(FlexicontentHelperRoute::getItemRoute($result->slug, $result->categoryslug, 0, $result));
         $item_title_escaped = htmlspecialchars($result->title, ENT_COMPAT, 'UTF-8');
         $tooltip_title = flexicontent_html::getToolTip($url_read_more, $item_title_escaped, $translate = 0, $escape = 0);
         $item_tooltip = ' class="' . $tooltip_class . ' ' . $url_class . '" title="' . $tooltip_title . '" ';
         $display_text = $displayway ? $result->title : $result->id;
         $display_text = !$addlink ? $display_text : '<a href="' . $item_url . '"' . ($addtooltip ? $item_tooltip : '') . ' >' . $display_text . '</a>';
         $curr_relitem_html = $relitem_html;
         $curr_relitem_html = str_replace('__item_url__', $item_url, $curr_relitem_html);
         $curr_relitem_html = str_replace('__item_title_escaped__', $item_title_escaped, $curr_relitem_html);
         $curr_relitem_html = str_replace('__item_tooltip__', $item_tooltip, $curr_relitem_html);
         $curr_relitem_html = str_replace('__display_text__', $display_text, $curr_relitem_html);
         // b. Replace item properties, e.g. {item->id}, (item->title}, etc
         $null_field = null;
         FlexicontentFields::doQueryReplacements($curr_relitem_html, $null_field, $result);
         // c. Replace HTML display of various item fields
         $err_mssg = 'Cannot replace field: "%s" because it is of not allowed field type: "%s", which can cause loop or other problem';
         foreach ($custom_field_names as $i => $custom_field_name) {
             $_field = @$result->fields[$custom_field_name];
             $custom_field_display = '';
             if ($is_disallowed_field = isset($disallowed_fieldnames[$custom_field_name])) {
                 $custom_field_display .= sprintf($err_mssg, $custom_field_name, @$_field->field_type);
             } else {
                 $display_var = $custom_field_methods[$i] ? $custom_field_methods[$i] : 'display';
                 $custom_field_display .= @$_field->{$display_var};
             }
             $curr_relitem_html = str_replace($custom_field_reps[$i], $custom_field_display, $curr_relitem_html);
         }
         $display[] = trim($pretext . $curr_relitem_html . $posttext);
     }
     $display = $opentag . implode($separatorf, $display) . $closetag;
     return $display;
 }
    function onDisplayFieldValue(&$field, $item, $values = null, $prop = 'display')
    {
        if (!in_array($field->field_type, self::$field_types)) {
            return;
        }
        $field->{$prop} = '';
        $option = JRequest::getCmd('option');
        $view = JRequest::getString('view', FLEXI_ITEMVIEW);
        $print = JRequest::getCMD('print');
        // No output if it is not FLEXIcontent item view or view is "print"
        if ($view != FLEXI_ITEMVIEW || $option != 'com_flexicontent' || $print) {
            return;
        }
        // parameters shortcuts
        $load_css = $field->parameters->get('load_css', 1);
        $use_tooltip = $field->parameters->get('use_tooltip', 1);
        $use_title = $field->parameters->get('use_title', 0);
        $use_category_link = $field->parameters->get('use_category_link', 0);
        $show_prevnext_count = $field->parameters->get('show_prevnext_count', 1);
        $tooltip_title_next = JText::_($field->parameters->get('tooltip_title_next', 'FLEXI_FIELDS_PAGENAV_GOTONEXT'));
        $tooltip_title_prev = JText::_($field->parameters->get('tooltip_title_prev', 'FLEXI_FIELDS_PAGENAV_GOTOPREV'));
        $prev_label = JText::_($field->parameters->get('prev_label', 'FLEXI_FIELDS_PAGENAV_GOTOPREV'));
        $next_label = JText::_($field->parameters->get('next_label', 'FLEXI_FIELDS_PAGENAV_GOTONEXT'));
        $category_label = JText::_($field->parameters->get('category_label', 'FLEXI_FIELDS_PAGENAV_CATEGORY'));
        $cid = JRequest::getInt('cid');
        $cid = $cid ? $cid : (int) $item->catid;
        // Get active category parameters
        $db = JFactory::getDBO();
        $query = 'SELECT * FROM #__categories WHERE id = ' . $cid;
        $db->setQuery($query);
        $catdata = $db->loadObject();
        $catdata->parameters = FLEXI_J16GE ? new JRegistry($catdata->params) : new JParameter($catdata->params);
        // Get list of ids of selected, TODO retrieve item ids from view:
        // --> this will allow special navigating layouts "mcats,author,myitems,tags,favs" and also utilize current filtering
        $ids = null;
        $list = $this->getItemList($field, $item, $ids, $cid, $catdata->parameters);
        // Location of current content item in array list
        $loc_to_ids = array_keys($list);
        $ids_to_loc = array_flip($loc_to_ids);
        $location = isset($ids_to_loc[$item->id]) ? $ids_to_loc[$item->id] : false;
        // Get previous and next item data
        $field->prev = null;
        $field->prevtitle = null;
        $field->prevurl = null;
        $field->next = null;
        $field->nexttitle = null;
        $field->nexturl = null;
        $field->category = null;
        $field->categorytitle = null;
        $field->categoryurl = null;
        // Get item data
        $rows = false;
        $prev_id = null;
        $next_id = null;
        if ($location !== false) {
            $prev_id = $location - 1 >= 0 ? $loc_to_ids[$location - 1] : null;
            $next_id = $location + 1 < count($list) ? $loc_to_ids[$location + 1] : null;
            $ids = array();
            // Previous item if it exists
            if ($prev_id) {
                $ids[] = $prev_id;
            }
            // Current item may belong may not be list in main category so retrieve it to get a proper categoryslug
            $ids[] = $item->id;
            // Next item if it exists
            if ($next_id) {
                $ids[] = $next_id;
            }
            // Query specific ids
            $rows = $this->getItemList($field, $item, $ids, $cid, $catdata->parameters);
            // previous content item
            if ($prev_id) {
                $field->prev = $rows[$prev_id];
                $field->prevtitle = $field->prev->title;
                $field->prevurl = JRoute::_(FlexicontentHelperRoute::getItemRoute($field->prev->slug, $field->prev->categoryslug, 0, $field->prev));
            }
            // next content item
            if ($next_id) {
                $field->next = $rows[$next_id];
                $field->nexttitle = $field->next->title;
                $field->nexturl = JRoute::_(FlexicontentHelperRoute::getItemRoute($field->next->slug, $field->next->categoryslug, 0, $field->next));
            }
        }
        // Check if displaying nothing and stop
        if (!$field->prev && !$field->next && !$use_category_link) {
            return;
        }
        $html = '<span class="flexi fc-pagenav">';
        $tooltip_class = FLEXI_J30GE ? ' hasTooltip' : ' hasTip';
        // CATEGORY back link
        if ($use_category_link) {
            $cat_image = $this->getCatThumb($catdata, $field->parameters);
            $limit = count($list);
            $limit = $limit ? $limit : 10;
            $start = floor($location / $limit) * $limit;
            if (!empty($rows[$item->id]->categoryslug)) {
                $html .= '
				<span class="fc-pagenav-return">
					<a class="btn btn-info" href="' . JRoute::_(FlexicontentHelperRoute::getCategoryRoute($rows[$item->id]->categoryslug)) . '?start=' . $start . '">' . htmlspecialchars($category_label, ENT_NOQUOTES, 'UTF-8') . ($cat_image ? '
						<br/>
						<img src="' . $cat_image . '" alt="Return"/>' : '') . '
					</a>
				</span>';
            }
        }
        // Item location and total count
        $html .= $show_prevnext_count ? '<span class="fc-pagenav-items-cnt badge badge-info">' . ($location + 1) . '/' . count($list) . '</span>' : '';
        // Get images
        $items_arr = array();
        if ($field->prev) {
            $items_arr[$field->prev->id] = $field->prev;
        }
        if ($field->next) {
            $items_arr[$field->next->id] = $field->next;
        }
        $thumbs = $this->getItemThumbs($field->parameters, $items_arr);
        // Next item linking
        if ($field->prev) {
            $tooltip = $use_tooltip ? ' title="' . flexicontent_html::getToolTip($tooltip_title_prev, $field->prevtitle, 0) . '"' : '';
            $html .= '
			<span class="fc-pagenav-prev' . ($use_tooltip ? $tooltip_class : '') . '" ' . ($use_tooltip ? $tooltip : '') . '>
				<a class="btn" href="' . $field->prevurl . '">
					<i class="icon-previous"></i>
					' . ($use_title ? $field->prevtitle : htmlspecialchars($prev_label, ENT_NOQUOTES, 'UTF-8')) . '
					' . (isset($thumbs[$field->prev->id]) ? '
						<br/>
						<img src="' . $thumbs[$field->prev->id] . '" alt="Previous"/>
					' : '') . '
				</a>
			</span>';
        } else {
            $html .= '
			<span class="fc-pagenav-prev">
				<span class="btn disabled">
					<i class="icon-previous"></i>
					' . htmlspecialchars($prev_label, ENT_NOQUOTES, 'UTF-8') . '
				</span>
			</span>';
        }
        // Previous item linking
        if ($field->next) {
            $tooltip = $use_tooltip ? ' title="' . flexicontent_html::getToolTip($tooltip_title_next, $field->nexttitle, 0) . '"' : '';
            $html .= '
			<span class="fc-pagenav-next' . ($use_tooltip ? $tooltip_class : '') . '" ' . ($use_tooltip ? $tooltip : '') . '>
				<a class="btn" href="' . $field->nexturl . '">
					<i class="icon-next"></i>
					' . ($use_title ? $field->nexttitle : htmlspecialchars($next_label, ENT_NOQUOTES, 'UTF-8')) . '
					' . (isset($thumbs[$field->next->id]) ? '
						<br/>
						<img src="' . $thumbs[$field->next->id] . '" alt="Next"/>
					' : '') . '
				</a>
			</span>';
        } else {
            $html .= '
			<span class="fc-pagenav-next">
				<span class="btn disabled">
					<i class="icon-next"></i>
					' . htmlspecialchars($next_label, ENT_NOQUOTES, 'UTF-8') . '
				</span>
			</span>';
        }
        $html .= '</span>';
        // Load needed JS/CSS
        if ($use_tooltip) {
            FLEXI_J30GE ? JHtml::_('bootstrap.tooltip') : JHTML::_('behavior.tooltip');
        }
        if ($load_css) {
            JFactory::getDocument()->addStyleSheet(JURI::root(true) . '/plugins/flexicontent_fields/fcpagenav/' . (FLEXI_J16GE ? 'fcpagenav/' : '') . 'fcpagenav.css');
        }
        $field->{$prop} = $html;
    }