Example #1
0
 /**
  * Method to get the assigned items for a category
  *
  * @access private
  * @return int
  */
 function _getassigned($id)
 {
     global $globalcats;
     $user = JFactory::getUser();
     $db = JFactory::getDBO();
     // Get the view's parameters
     $params = $this->_params;
     $use_tmp = true;
     // Date-Times are stored as UTC, we should use current UTC time to compare and not user time (requestTime),
     //  thus the items are published globally at the time the author specified in his/her local clock
     //$app  = JFactory::getApplication();
     //$now  = FLEXI_J16GE ? $app->requestTime : $app->get('requestTime');   // NOT correct behavior it should be UTC (below)
     //$date = JFactory::getDate();
     //$now  = FLEXI_J16GE ? $date->toSql() : $date->toMySQL();              // NOT good if string passed to function that will be cached, because string continuesly different
     $_nowDate = 'UTC_TIMESTAMP()';
     //$db->Quote($now);
     $nullDate = $db->getNullDate();
     // Get some parameters and other info
     $catlang = $params->get('language', '');
     // Category language (currently UNUSED)
     $lang = flexicontent_html::getUserCurrentLang();
     // Get user current language
     $filtercat = $params->get('filtercat', 0);
     // Filter items using currently selected language
     $show_noauth = $params->get('show_noauth', 0);
     // Show unauthorized items
     // First thing we need to do is to select only the requested items
     $where = ' WHERE 1 ';
     if ($this->_authorid) {
         $where .= ' AND i.created_by = ' . $db->Quote($this->_authorid);
     }
     // Filter the category view with the current user language
     if ($filtercat) {
         $lta = $use_tmp ? 'i' : 'ie';
         $where .= ' AND ( ' . $lta . '.language LIKE ' . $db->Quote($lang . '%') . ' OR ' . $lta . '.language="*" ) ';
     }
     // Get privilege to view non viewable items (upublished, archived, trashed, expired, scheduled).
     // NOTE:  ACL view level is checked at a different place
     $ignoreState = $user->authorise('flexicontent.ignoreviewstate', 'com_flexicontent');
     if (!$ignoreState) {
         // Limit by publication state. Exception: when displaying personal user items or items modified by the user
         $where .= ' AND ( i.state IN (1, -5) OR ( i.created_by = ' . $user->id . ' AND i.created_by != 0 ) )';
         //.' OR ( i.modified_by = '.$user->id.' AND i.modified_by != 0 ) )';
         // Limit by publish up/down dates. Exception: when displaying personal user items or items modified by the user
         $where .= ' AND ( ( i.publish_up = ' . $db->Quote($nullDate) . ' OR i.publish_up <= ' . $_nowDate . ' ) OR ( i.created_by = ' . $user->id . ' AND i.created_by != 0 ) )';
         //.' OR ( i.modified_by = '.$user->id.' AND i.modified_by != 0 ) )';
         $where .= ' AND ( ( i.publish_down = ' . $db->Quote($nullDate) . ' OR i.publish_down >= ' . $_nowDate . ' ) OR ( i.created_by = ' . $user->id . ' AND i.created_by != 0 ) )';
         //.' OR ( i.modified_by = '.$user->id.' AND i.modified_by != 0 ) )';
     }
     // Count items according to full depth level !!!
     $catlist = !empty($globalcats[$id]->descendants) ? $globalcats[$id]->descendants : $id;
     $where .= ' AND rel.catid IN (' . $catlist . ')';
     // Select only items that user has view access, if listing of unauthorized content is not enabled
     // Checking item, category, content type access level
     if (!$show_noauth) {
         $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
         $aid_list = implode(",", $aid_arr);
         $where .= ' AND ty.access IN (0,' . $aid_list . ')';
         $where .= ' AND mc.access IN (0,' . $aid_list . ')';
         $where .= ' AND  i.access IN (0,' . $aid_list . ')';
     }
     $query = 'SELECT COUNT(DISTINCT rel.itemid)' . ' FROM #__flexicontent_cats_item_relations AS rel' . (!$use_tmp ? ' JOIN #__content AS i ON rel.itemid = i.id' : ' JOIN #__flexicontent_items_tmp AS i ON rel.itemid = i.id') . (!$use_tmp ? ' JOIN #__flexicontent_items_ext AS ie ON rel.itemid = ie.item_id' : '') . ' JOIN #__flexicontent_types AS ty ON ' . (!$use_tmp ? 'ie' : 'i') . '.type_id = ty.id' . ' JOIN #__categories AS mc ON mc.id =   i.catid AND mc.published = 1' . $where;
     $db->setQuery($query);
     $assigneditems = $db->loadResult();
     if ($db->getErrorNum()) {
         JFactory::getApplication()->enqueueMessage(__FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($db->getErrorMsg()), 'error');
     }
     return $assigneditems;
 }
 static function doQueryReplacements(&$query, &$field, &$item, &$item_pros = true, $canCache = null)
 {
     // replace item properties
     preg_match_all("/{item->[^}]+}/", $query, $matches);
     $canCache = count($matches[0]) == 0;
     if (!$item_pros && count($matches[0])) {
         $item_pros = count($matches[0]);
         return '';
     }
     // If needed replace item properties, loading the item if not already loaded
     if (count($matches[0]) && !$item) {
         if (!@$field->item_id) {
             echo __FUNCTION__ . "(): field->item_id is not set";
             return;
         }
         $item = JTable::getInstance($type = 'flexicontent_items', $prefix = '', $config = array());
         $item->load($field->item_id);
     }
     foreach ($matches[0] as $replacement_tag) {
         $replacement_value = '$' . substr($replacement_tag, 1, -1);
         eval("\$replacement_value = \"{$replacement_value}\";");
         $query = str_replace($replacement_tag, $replacement_value, $query);
     }
     // replace field properties
     if ($field) {
         preg_match_all("/{field->[^}]+}/", $query, $matches);
         foreach ($matches[0] as $replacement_tag) {
             $replacement_value = '$' . substr($replacement_tag, 1, -1);
             eval("\$replacement_value = \" {$replacement_value}\";");
             $query = str_replace($replacement_tag, $replacement_value, $query);
         }
     }
     // replace current user language
     $query = str_replace("{curr_userlang_shorttag}", flexicontent_html::getUserCurrentLang(), $query);
     $query = str_replace("{curr_userlang_fulltag}", flexicontent_html::getUserCurrentLang(), $query);
     return $query;
 }
Example #3
0
 /**
  * Method to build the WHERE clause
  *
  * @access private
  * @return string
  */
 function _buildItemWhere()
 {
     $user = JFactory::getUser();
     $db = JFactory::getDBO();
     // Get the view's parameters
     $cparams = $this->_params;
     // Date-Times are stored as UTC, we should use current UTC time to compare and not user time (requestTime),
     //  thus the items are published globally at the time the author specified in his/her local clock
     //$app  = JFactory::getApplication();
     //$now  = FLEXI_J16GE ? $app->requestTime : $app->get('requestTime');   // NOT correct behavior it should be UTC (below)
     //$date = JFactory::getDate();
     //$now  = FLEXI_J16GE ? $date->toSql() : $date->toMySQL();              // NOT good if string passed to function that will be cached, because string continuesly different
     $_nowDate = 'UTC_TIMESTAMP()';
     //$db->Quote($now);
     $nullDate = $db->getNullDate();
     // First thing we need to do is to select only the requested TAGGED items
     $where = ' WHERE tag.tid = ' . $this->_id;
     // User current language
     $lang = flexicontent_html::getUserCurrentLang();
     $filtertag = $cparams->get('filtertag', 0);
     // Filter the tag view with the active language
     if ((FLEXI_FISH || FLEXI_J16GE) && $filtertag) {
         $lta = FLEXI_J16GE ? 'i' : 'ie';
         $where .= ' AND ( ' . $lta . '.language LIKE ' . $db->Quote($lang . '%') . (FLEXI_J16GE ? ' OR ' . $lta . '.language="*" ' : '') . ' ) ';
     }
     // Get privilege to view non viewable items (upublished, archived, trashed, expired, scheduled).
     // NOTE:  ACL view level is checked at a different place
     $ignoreState = $user->authorise('flexicontent.ignoreviewstate', 'com_flexicontent');
     if (!$ignoreState) {
         // Limit by publication state. Exception: when displaying personal user items or items modified by the user
         $where .= ' AND ( i.state IN (1, -5) OR ( i.created_by = ' . $user->id . ' AND i.created_by != 0 ) )';
         //.' OR ( i.modified_by = '.$user->id.' AND i.modified_by != 0 ) )';
         // Limit by publish up/down dates. Exception: when displaying personal user items or items modified by the user
         $where .= ' AND ( ( i.publish_up = ' . $this->_db->Quote($nullDate) . ' OR i.publish_up <= ' . $_nowDate . ' ) OR ( i.created_by = ' . $user->id . ' AND i.created_by != 0 ) )';
         //.' OR ( i.modified_by = '.$user->id.' AND i.modified_by != 0 ) )';
         $where .= ' AND ( ( i.publish_down = ' . $this->_db->Quote($nullDate) . ' OR i.publish_down >= ' . $_nowDate . ' ) OR ( i.created_by = ' . $user->id . ' AND i.created_by != 0 ) )';
         //.' OR ( i.modified_by = '.$user->id.' AND i.modified_by != 0 ) )';
     }
     $where .= !FLEXI_J16GE ? ' AND i.sectionid = ' . FLEXI_SECTION : '';
     /*
      * If we have a filter, and this is enabled... lets tack the AND clause
      * for the filter onto the WHERE clause of the item query.
      */
     // ****************************************
     // Create WHERE clause part for Text Search
     // ****************************************
     $text = JRequest::getString('filter', JRequest::getString('q', ''), 'default');
     // Check for LIKE %word% search, for languages without spaces
     $filter_word_like_any = $cparams->get('filter_word_like_any', 0);
     $phrase = $filter_word_like_any ? JRequest::getWord('searchphrase', JRequest::getWord('p', 'any'), 'default') : JRequest::getWord('searchphrase', JRequest::getWord('p', 'exact'), 'default');
     $si_tbl = 'flexicontent_items_ext';
     $search_prefix = $cparams->get('add_search_prefix') ? 'vvv' : '';
     // SEARCH WORD Prefix
     $text = !$search_prefix ? trim($text) : preg_replace('/(\\b[^\\s,\\.]+\\b)/u', $search_prefix . '$0', trim($text));
     $words = preg_split('/\\s\\s*/u', $text);
     if (strlen($text)) {
         $ts = 'ie';
         $escaped_text = $db->escape($text, true);
         $quoted_text = $db->Quote($escaped_text, false);
         switch ($phrase) {
             case 'natural':
                 $_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':
                 $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':
                 $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:
                 $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;
         }
         $where .= ' AND ' . $_text_match;
     }
     return $where;
 }
 /**
  * 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;
 }
Example #5
0
 public static function getItems(&$params, $ordering)
 {
     global $dump, $globalcats;
     global $modfc_jprof, $mod_fc_run_times;
     $app = JFactory::getApplication();
     // For specific cache issues
     if (empty($globalcats)) {
         if (FLEXI_SECTION || FLEXI_CAT_EXTENSION) {
             JPluginHelper::importPlugin('system', 'flexisystem');
             if (FLEXI_CACHE) {
                 // add the category tree to categories cache
                 $catscache = JFactory::getCache('com_flexicontent_cats');
                 $catscache->setCaching(1);
                 //force cache
                 $catscache->setLifeTime(84600);
                 //set expiry to one day
                 $globalcats = $catscache->call(array('plgSystemFlexisystem', 'getCategoriesTree'));
             } else {
                 $globalcats = plgSystemFlexisystem::getCategoriesTree();
             }
         }
     }
     // Initialize variables
     $db = JFactory::getDBO();
     $user = JFactory::getUser();
     $view = JRequest::getVar('view');
     $option = JRequest::getVar('option');
     $fparams = $app->getParams('com_flexicontent');
     $show_noauth = $fparams->get('show_noauth', 0);
     // Date-Times are stored as UTC, we should use current UTC time to compare and not user time (requestTime),
     //  thus the items are published globally at the time the author specified in his/her local clock
     //$now		= $app->get('requestTime');
     $now = JFactory::getDate()->toSql();
     $nullDate = $db->getNullDate();
     // $display_category_data
     $apply_config_per_category = (int) $params->get('apply_config_per_category', 0);
     // *** METHODS that their 'ALL' value is 0, (these do not use current item information)
     // current item scope parameters
     $method_curitem = (int) $params->get('method_curitem', 0);
     // current language scope parameters
     $method_curlang = (int) $params->get('method_curlang', 0);
     // current item scope parameters
     $method_curuserfavs = (int) $params->get('method_curuserfavs', 0);
     // featured items scope parameters
     $method_featured = (int) $params->get('method_featured', 0);
     // featured items scope parameters
     $method_states = (int) $params->get('method_states', 0);
     $item_states = $params->get('item_states');
     $show_nocontent_msg = (int) $params->get('show_nocontent_msg', 1);
     // *** METHODS that their 'ALL' value is 1, that also have behaviour variable (most of them)
     // categories scope parameters
     $method_cat = (int) $params->get('method_cat', 1);
     $catids = $params->get('catids', array());
     $behaviour_cat = $params->get('behaviour_cat', 0);
     $treeinclude = $params->get('treeinclude');
     // types scope parameters
     $method_types = (int) $params->get('method_types', 1);
     $types = $params->get('types');
     $behaviour_types = $params->get('behaviour_types', 0);
     // authors scope parameters
     $method_auth = (int) $params->get('method_auth', 1);
     $authors = trim($params->get('authors'));
     $behaviour_auth = $params->get('behaviour_auth');
     // items scope parameters
     $method_items = (int) $params->get('method_items', 1);
     $items = trim($params->get('items'));
     $behaviour_items = $params->get('behaviour_items', 0);
     $excluded_tags = $params->get('excluded_tags', array());
     $excluded_tags = !is_array($excluded_tags) ? array($excluded_tags) : $excluded_tags;
     $relitems_fields = $params->get('relitems_fields', array());
     $relitems_fields = !is_array($relitems_fields) ? array($relitems_fields) : $relitems_fields;
     // tags scope parameters
     $method_tags = (int) $params->get('method_tags', 1);
     $tag_ids = $params->get('tag_ids', array());
     $tag_combine = $params->get('tag_combine', 0);
     // date scope parameters
     $method_dates = (int) $params->get('method_dates', 1);
     // parameter added later, maybe not to break compatibility this should be INCLUDE=3 by default ?
     $date_type = (int) $params->get('date_type', 0);
     $nulldates = (int) $params->get('nulldates', 0);
     $bdate = $params->get('bdate', '');
     $edate = $params->get('edate', '');
     $raw_bdate = $params->get('raw_bdate', 0);
     $raw_edate = $params->get('raw_edate', 0);
     $behaviour_dates = $params->get('behaviour_dates', 0);
     $date_compare = $params->get('date_compare', 0);
     $datecomp_field = (int) $params->get('datecomp_field', 0);
     // Server date
     $sdate = explode(' ', $now);
     $cdate = $sdate[0] . ' 00:00:00';
     // Set date comparators
     if ($date_type == 0) {
         // created
         $comp = 'i.created';
     } else {
         if ($date_type == 1) {
             // modified
             $comp = 'i.modified';
         } else {
             if ($date_type == 2) {
                 // publish up
                 $comp = 'i.publish_up';
             } else {
                 if ($date_type == 4) {
                     // publish down
                     $comp = 'i.publish_down';
                 } else {
                     // $date_type == 3
                     $comp = 'dfrel.value';
                 }
             }
         }
     }
     // custom field scope
     $method_filt = (int) $params->get('method_filt', 1);
     // parameter added later, maybe not to break compatibility this should be INCLUDE=3 by default ?
     $behaviour_filt = (int) $params->get('behaviour_filt', 0);
     $static_filters = $params->get('static_filters', '');
     $dynamic_filters = $params->get('dynamic_filters', '');
     // get module fetching parameters
     if ($params->get('skip_items', 0)) {
         $count = (int) $params->get('maxskipcount', 50);
     } else {
         $count = (int) $params->get('count', 5);
     }
     // get module display parameters
     $mod_image = $params->get('mod_image');
     // ************************************************************************************
     // filter by publication state, (except for item state which is a special scope, below)
     // ************************************************************************************
     $where = ' WHERE c.published = 1';
     $where .= FLEXI_J16GE ? '' : ' AND i.sectionid = ' . FLEXI_SECTION;
     $ignore_up_down_dates = $params->get('ignore_up_down_dates', 0);
     // 1: ignore publish_up, 2: ignore publish_donw, 3: ignore both
     $ignoreState = $params->get('use_list_items_in_any_state_acl', 0) && $user->authorise('flexicontent.ignoreviewstate', 'com_flexicontent');
     if (!$ignoreState && $ignore_up_down_dates != 3 && $ignore_up_down_dates != 1) {
         $where .= ' AND ( i.publish_up = ' . $db->Quote($nullDate) . ' OR i.publish_up <= ' . $db->Quote($now) . ' )';
     }
     if (!$ignoreState && $ignore_up_down_dates != 3 && $ignore_up_down_dates != 2) {
         $where .= ' AND ( i.publish_down = ' . $db->Quote($nullDate) . ' OR i.publish_down >= ' . $db->Quote($now) . ' )';
     }
     // *********************
     // filter by permissions
     // *********************
     $joinaccess = '';
     if (!$show_noauth) {
         $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
         $aid_list = implode(",", $aid_arr);
         $where .= ' AND ty.access IN (0,' . $aid_list . ')';
         $where .= ' AND mc.access IN (0,' . $aid_list . ')';
         $where .= ' AND  i.access IN (0,' . $aid_list . ')';
     }
     // *******************************************************
     // NON-STATIC behaviors that need current item information
     // *******************************************************
     $isflexi_itemview = $option == 'com_flexicontent' && $view == FLEXI_ITEMVIEW && JRequest::getInt('id');
     $isflexi_catview = $option == 'com_flexicontent' && $view == 'category' && (JRequest::getInt('cid') || JRequest::getVar('cids'));
     $curritem_date_field_needed = $behaviour_dates && $date_compare && $date_type == 3 && $datecomp_field;
     // Date field selected
     if (($behaviour_cat || $behaviour_types || $behaviour_auth || $behaviour_items || $curritem_date_field_needed || $behaviour_filt) && $isflexi_itemview) {
         // initialize variables
         $cid = JRequest::getInt('cid');
         $id = JRequest::getInt('id');
         $Itemid = JRequest::getInt('Itemid');
         // Check for new item nothing to retrieve,
         // NOTE: aborting execution if current view is not item view, but item view is required
         // and also proper usage of current item, both of these will be handled by SCOPEs
         $sel_date = '';
         $join_date = '';
         if ($curritem_date_field_needed) {
             $sel_date = ', dfrel.value as custom_date';
             $join_date = '	LEFT JOIN #__flexicontent_fields_item_relations AS dfrel' . '   ON ( i.id = dfrel.item_id AND dfrel.valueorder = 1 AND dfrel.field_id = ' . $datecomp_field . ' )';
         }
         if ($id) {
             $query = 'SELECT i.*, ie.*, GROUP_CONCAT(ci.catid SEPARATOR ",") as itemcats' . $sel_date . ' FROM #__content as i' . ' LEFT JOIN #__flexicontent_items_ext AS ie on ie.item_id = i.id' . ' LEFT JOIN #__flexicontent_cats_item_relations AS ci on ci.itemid = i.id' . $join_date . ' WHERE i.id = ' . $id . ' GROUP BY ci.itemid';
             $db->setQuery($query);
             $curitem = $db->loadObject();
             // Get item dates
             $idate = null;
             if ($date_type == 0) {
                 // created
                 $idate = $curitem->created;
             } else {
                 if ($date_type == 1) {
                     // modified
                     $idate = $curitem->modified;
                 } else {
                     if ($date_type == 2) {
                         // publish up
                         $idate = $curitem->publish_up;
                     } else {
                         if (isset($curitem->custom_date)) {
                             // $date_type == 3
                             $idate = $curitem->custom_date;
                         }
                     }
                 }
             }
             if ($idate) {
                 $idate = explode(' ', $idate);
                 $cdate = $idate[0] . ' 00:00:00';
             }
             $curritemcats = explode(',', $curitem->itemcats);
         }
     }
     // ******************
     // current item scope
     // ******************
     $currid = JRequest::getInt('id');
     if ($method_curitem == 1) {
         // exclude method  ---  exclude current item
         $where .= ' AND i.id <> ' . $currid;
     } else {
         if ($method_curitem == 2) {
             // include method  ---  include current item ONLY
             $where .= ' AND i.id = ' . $currid;
         } else {
             // All Items including current
         }
     }
     // **********************
     // current language scope
     // **********************
     $lang = flexicontent_html::getUserCurrentLang();
     if ($method_curlang == 1) {
         // exclude method  ---  exclude items of current language
         $where .= ' AND ie.language NOT LIKE ' . $db->Quote($lang . '%');
     } else {
         if ($method_curlang == 2) {
             // include method  ---  include items of current language ONLY
             $where .= ' AND ( ie.language LIKE ' . $db->Quote($lang . '%') . (FLEXI_J16GE ? ' OR ie.language="*" ' : '') . ' ) ';
         } else {
             // Items of any language
         }
     }
     // *****************************
     // current user favourites scope
     // *****************************
     $curruserid = (int) $user->get('id');
     if ($method_curuserfavs == 1) {
         // exclude method  ---  exclude currently logged user favourites
         $join_favs = ' LEFT OUTER JOIN #__flexicontent_favourites AS fav ON fav.itemid = i.id AND fav.userid = ' . $curruserid;
         $where .= ' AND fav.itemid IS NULL';
     } else {
         if ($method_curuserfavs == 2) {
             // include method  ---  include currently logged user favourites
             $join_favs = ' LEFT JOIN #__flexicontent_favourites AS fav ON fav.itemid = i.id';
             $where .= ' AND fav.userid = ' . $curruserid;
         } else {
             // All Items regardless of being favoured by current user
             $join_favs = '';
         }
     }
     // ******************************
     // joomla featured property scope
     // ******************************
     if ($method_featured == 1) {
         // exclude method  ---  exclude currently logged user favourites
         $where .= ' AND i.featured=0';
     } else {
         if ($method_featured == 2) {
             // include method  ---  include currently logged user favourites
             $where .= ' AND i.featured=1';
         } else {
             // All Items regardless of being featured or not
         }
     }
     // *****************
     // item states scope
     // *****************
     $item_states = is_array($item_states) ? implode(',', $item_states) : $item_states;
     if ($method_states == 0) {
         if (!$ignoreState) {
             // method normal: Published item states
             $where .= ' AND i.state IN ( 1, -5 )';
         }
     } else {
         // exclude trashed
         $where .= ' AND i.state <> -2';
         if ($item_states) {
             if ($method_states == 1) {
                 // exclude method  ---  exclude specified item states
                 $where .= ' AND i.state NOT IN (' . $item_states . ')';
             } else {
                 if ($method_states == 2) {
                     // include method  ---  include specified item states
                     $where .= ' AND i.state IN (' . $item_states . ')';
                 }
             }
         } else {
             if ($method_states == 2) {
                 // misconfiguration, when using include method with no state selected ...
                 echo "<b>WARNING:</b> Misconfigured item states scope, select at least one state or set states scope to Normal <small>(Published)</small><br/>";
                 return;
             }
         }
     }
     // ****************
     // categories scope
     // ****************
     // ZERO 'behaviour' means statically selected records, but METHOD 1 is ALL records ... so NOTHING to do
     if (!$behaviour_cat && $method_cat == 1) {
         if ($apply_config_per_category) {
             echo "<b>WARNING:</b> Misconfiguration warning, APPLY CONFIGURATION PER CATEGORY is possible only if CATEGORY SCOPE is set to either (a) INCLUDE(static selection of categories) or (b) items in same category as current item / or current category of category view<br/>";
             return;
         }
     } else {
         if (!$behaviour_cat) {
             // Check for empty statically selected records, and abort with error message
             if (empty($catids)) {
                 echo "<b>WARNING:</b> Misconfigured category scope, select at least one category or set category scope to ALL<br/>";
                 return;
             }
             // Make sure categories is an array
             $catids = is_array($catids) ? $catids : array($catids);
             // Retrieve extra categories, such children or parent categories
             $catids_arr = flexicontent_cats::getExtraCats($catids, $treeinclude, array());
             if (empty($catids_arr)) {
                 if ($show_nocontent_msg) {
                     echo JText::_("No viewable content in Current View for your Access Level");
                 }
                 return;
             }
             if ($method_cat == 2) {
                 // exclude method
                 if ($apply_config_per_category) {
                     echo "<b>WARNING:</b> Misconfiguration warning, APPLY CONFIGURATION PER CATEGORY is possible only if CATEGORY SCOPE is set to either (a) INCLUDE(static selection of categories) or (b) items in same category as current item / or current category of category view<br/>";
                     return;
                 }
                 $where .= ' AND c.id NOT IN (' . implode(',', $catids_arr) . ')';
             } else {
                 if ($method_cat == 3) {
                     // include method
                     if (!$apply_config_per_category) {
                         $where .= ' AND c.id IN (' . implode(',', $catids_arr) . ')';
                     } else {
                         // *** Applying configuration per category ***
                         foreach ($catids_arr as $catid) {
                             // The items retrieval query will be executed ... once per EVERY category
                             $multiquery_cats[$catid] = ' AND c.id = ' . $catid;
                         }
                         $params->set('dynamic_catids', serialize($catids_arr));
                         // Set dynamic catids to be used by the getCategoryData
                     }
                 }
             }
         } else {
             if (($behaviour_cat == 2 || $behaviour_cat == 4) && $apply_config_per_category) {
                 echo "<b>WARNING:</b> Misconfiguration warning, APPLY CONFIGURATION PER CATEGORY is possible only if CATEGORY SCOPE is set to either (a) INCLUDE(static selection of categories) or (b) items in same category as current item / or current category of category view<br/>";
                 return;
             }
             $currcat_valid_case = $behaviour_cat == 1 && $isflexi_itemview || $behaviour_cat == 3 && $isflexi_catview;
             if (!$currcat_valid_case) {
                 return;
                 // current view is not item OR category view ... , nothing to display
             }
             // IF $cid is not set then use the main category id of the (current) item
             if ($isflexi_itemview) {
                 $cid = $cid ? $cid : $curitem->catid;
                 // Retrieve extra categories, such children or parent categories
                 $catids_arr = flexicontent_cats::getExtraCats(array($cid), $treeinclude, $curritemcats);
             } else {
                 if ($isflexi_catview) {
                     $cid = JRequest::getInt('cid', 0);
                     if (!$cid) {
                         $_cids = JRequest::getVar('cids', '');
                         if (!is_array($_cids)) {
                             $_cids = preg_replace('/[^0-9,]/i', '', (string) $_cids);
                             $_cids = explode(',', $_cids);
                         }
                         // make sure given data are integers ... !!
                         $cids = array();
                         foreach ($_cids as $i => $_id) {
                             if ((int) $_id) {
                                 $cids[] = (int) $_id;
                             }
                         }
                         // Retrieve extra categories, such children or parent categories
                         $catids_arr = flexicontent_cats::getExtraCats(array($cid), $treeinclude, array());
                     }
                 } else {
                     return;
                     // nothing to display
                 }
             }
             // Retrieve extra categories, such children or parent categories
             $catids_arr = flexicontent_cats::getExtraCats(array($cid), $treeinclude, $isflexi_itemview ? $curritemcats : array());
             if (empty($catids_arr)) {
                 if ($show_nocontent_msg) {
                     echo JText::_("No viewable content in Current View for your Access Level");
                 }
                 return;
             }
             if ($behaviour_cat == 1 || $behaviour_cat == 3) {
                 if (!$apply_config_per_category) {
                     $where .= ' AND c.id IN (' . implode(',', $catids_arr) . ')';
                 } else {
                     // *** Applying configuration per category ***
                     foreach ($catids_arr as $catid) {
                         // The items retrieval query will be executed ... once per EVERY category
                         $multiquery_cats[$catid] = ' AND c.id = ' . $catid;
                     }
                     $params->set('dynamic_catids', serialize($catids_arr));
                     // Set dynamic catids to be used by the getCategoryData
                 }
             } else {
                 $where .= ' AND c.id NOT IN (' . implode(',', $catids_arr) . ')';
             }
         }
     }
     // Now check if no items need to be retrieved
     if ($count == 0) {
         return;
     }
     // ***********
     // types scope
     // ***********
     // ZERO 'behaviour' means statically selected records, but METHOD 1 is ALL records ... so NOTHING to do
     if (!$behaviour_types && $method_types == 1) {
     } else {
         if (!$behaviour_types) {
             // Check for empty statically selected records, and abort with error message
             if (empty($types)) {
                 echo "<b>WARNING:</b> Misconfigured types scope, select at least one item type or set types scope to ALL<br/>";
                 return;
             }
             // Make types a comma separated string of ids
             $types = is_array($types) ? implode(',', $types) : $types;
             if ($method_types == 2) {
                 // exclude method
                 $where .= ' AND ie.type_id NOT IN (' . $types . ')';
             } else {
                 if ($method_types == 3) {
                     // include method
                     $where .= ' AND ie.type_id IN (' . $types . ')';
                 }
             }
         } else {
             if (!$isflexi_itemview) {
                 return;
                 // current view is not item view ... , nothing to display
             }
             if ($behaviour_types == 1) {
                 $where .= ' AND ie.type_id = ' . (int) $curitem->type_id;
             } else {
                 $where .= ' AND ie.type_id <> ' . (int) $curitem->type_id;
             }
         }
     }
     // ************
     // author scope
     // ************
     // ZERO 'behaviour' means statically selected records, but METHOD 1 is ALL records ... so NOTHING to do
     if (!$behaviour_auth && $method_auth == 1) {
     } else {
         if (!$behaviour_auth) {
             // Check for empty statically selected records, and abort with error message
             if (empty($authors)) {
                 echo "<b>WARNING:</b> Misconfigured author scope, select at least one author or set author scope to ALL<br/>";
                 return;
             }
             if ($method_auth == 2) {
                 // exclude method
                 $where .= ' AND i.created_by NOT IN (' . $authors . ')';
             } else {
                 if ($method_auth == 3) {
                     // include method
                     $where .= ' AND i.created_by IN (' . $authors . ')';
                 }
             }
         } else {
             if (!$isflexi_itemview && $behaviour_auth < 3) {
                 // Behaviour 3 is current user thus not related to current item
                 return;
                 // current view is not item view ... , nothing to display
             }
             if ($behaviour_auth == 1) {
                 $where .= ' AND i.created_by = ' . (int) $curitem->created_by;
             } else {
                 if ($behaviour_auth == 2) {
                     $where .= ' AND i.created_by <> ' . (int) $curitem->created_by;
                 } else {
                     // $behaviour_auth == 3
                     $where .= ' AND i.created_by = ' . (int) $user->id;
                 }
             }
         }
     }
     // ***********
     // items scope
     // ***********
     // ZERO 'behaviour' means statically selected records, but METHOD 1 is ALL records ... so NOTHING to do
     if (!$behaviour_items && $method_items == 1) {
     } else {
         if (!$behaviour_items) {
             // Check for empty statically selected records, and abort with error message
             if (empty($items)) {
                 echo "<b>WARNING:</b> Misconfigured items scope, select at least one item or set items scope to ALL<br/>";
                 return;
             }
             if ($method_items == 2) {
                 // exclude method
                 $where .= ' AND i.id NOT IN (' . $items . ')';
             } else {
                 if ($method_items == 3) {
                     // include method
                     $where .= ' AND i.id IN (' . $items . ')';
                 }
             }
         } else {
             if ($behaviour_items == 2 || $behaviour_items == 3) {
                 if (!$isflexi_itemview) {
                     return;
                     // current view is not item view ... , nothing to display
                 }
                 unset($related);
                 // make sure this is no set ...
                 if (count($relitems_fields)) {
                     $where2 = count($relitems_fields) > 1 ? ' AND field_id IN (' . implode(',', $relitems_fields) . ')' : ' AND field_id = ' . $relitems_fields[0];
                     // select the item ids related to current item via the relation fields
                     $query2 = 'SELECT DISTINCT ' . ($behaviour_items == 2 ? 'value' : 'item_id') . ' FROM #__flexicontent_fields_item_relations' . ' WHERE ' . ($behaviour_items == 2 ? 'item_id' : 'value') . ' = ' . (int) $id . $where2;
                     $db->setQuery($query2);
                     $related = $db->loadColumn();
                     $related = is_array($related) ? array_map('intval', $related) : $related;
                 }
                 if (isset($related) && count($related)) {
                     $where .= count($related) > 1 ? ' AND i.id IN (' . implode(',', $related) . ')' : ' AND i.id = ' . $related[0];
                 } else {
                     // No related items were found
                     return;
                 }
             } else {
                 if ($behaviour_items == 1) {
                     if (!$isflexi_itemview) {
                         return;
                         // current view is not item view ... , nothing to display
                     }
                     // select the tags associated to the item
                     $query2 = 'SELECT tid' . ' FROM #__flexicontent_tags_item_relations' . ' WHERE itemid = ' . (int) $id;
                     $db->setQuery($query2);
                     $tags = $db->loadColumn();
                     $tags = array_diff($tags, $excluded_tags);
                     unset($related);
                     if ($tags) {
                         $where2 = count($tags) > 1 ? ' AND tid IN (' . implode(',', $tags) . ')' : ' AND tid = ' . $tags[0];
                         // select the item ids related to current item via common tags
                         $query2 = 'SELECT DISTINCT itemid' . ' FROM #__flexicontent_tags_item_relations' . ' WHERE itemid <> ' . (int) $id . $where2;
                         $db->setQuery($query2);
                         $related = $db->loadColumn();
                     }
                     if (isset($related) && count($related)) {
                         $where .= count($related) > 1 ? ' AND i.id IN (' . implode(',', $related) . ')' : ' AND i.id = ' . $related[0];
                     } else {
                         // No related items were found
                         return;
                     }
                 }
             }
         }
     }
     // **********
     // tags scope
     // **********
     if ($method_tags > 1) {
         // Check for empty statically selected records, and abort with error message
         if (empty($tag_ids)) {
             echo "<b>WARNING:</b> Misconfigured tags scope, select at least one tag or set tags scope to ALL<br/>";
             return;
         }
         // Make sure tag_ids is an array
         $tag_ids = !is_array($tag_ids) ? array($tag_ids) : $tag_ids;
         // Create query to match item ids using the selected tags
         $query2 = 'SELECT ' . ($tag_combine ? 'itemid' : 'DISTINCT itemid') . ' FROM #__flexicontent_tags_item_relations' . ' WHERE tid IN (' . implode(',', $tag_ids) . ')' . ($tag_combine ? ' GROUP by itemid HAVING COUNT(*) >= ' . count($tag_ids) : '');
         if ($method_tags == 2) {
             // exclude method
             $where .= ' AND i.id NOT IN (' . $query2 . ')';
         } else {
             if ($method_tags == 3) {
                 // include method
                 $where .= ' AND i.id IN (' . $query2 . ')';
             }
         }
     }
     // **********
     // date scope
     // **********
     // ZERO 'behaviour' means statically selected records, but METHOD 1 is ALL records ... so NOTHING to do
     // NOTE: currently we only have ALL, INCLUDE methods
     if (!$behaviour_dates && $method_dates == 1) {
     } else {
         if (!$behaviour_dates) {
             $negate_op = $method_dates == 2 ? 'NOT' : '';
             if (!$raw_edate && $edate && !FLEXIUtilities::isSqlValidDate($edate)) {
                 echo "<b>WARNING:</b> Misconfigured date scope, you have entered invalid -END- date:<br>(a) Enter a valid date via callendar OR <br>(b) leave blank OR <br>(c) choose (non-static behavior 'custom offset') and enter custom offset e.g. five days ago (be careful with space character): -5 d<br/>";
                 return;
             } else {
                 if ($edate) {
                     $where .= ' AND ( ' . $negate_op . ' ( ' . $comp . ' <= ' . (!$raw_edate ? $db->Quote($edate) : $edate) . ' )' . ($nulldates ? ' OR ' . $comp . ' IS NULL OR ' . $comp . '="" ' : '') . ' )';
                 }
             }
             if (!$raw_bdate && $bdate && !FLEXIUtilities::isSqlValidDate($bdate)) {
                 echo "<b>WARNING:</b> Misconfigured date scope, you have entered invalid -BEGIN- date:<br>(a) Enter a valid date via callendar OR <br>(b) leave blank OR <br>(c) choose (non-static behavior 'custom offset') and enter custom offset e.g. five days ago (be careful with space character): -5 d<br/>";
                 return;
             } else {
                 if ($bdate) {
                     $where .= ' AND ( ' . $negate_op . ' ( ' . $comp . ' >= ' . (!$raw_bdate ? $db->Quote($bdate) : $bdate) . ' )' . ($nulldates ? ' OR ' . $comp . ' IS NULL OR ' . $comp . '="" ' : '') . ' )';
                 }
             }
         } else {
             if (!$isflexi_itemview && $date_compare == 1) {
                 return;
                 // date_compare == 1 means compare to current item, but current view is not an item view so we terminate
             }
             // FOR date_compare==0, $cdate is SERVER DATE
             // FOR date_compare==1, $cdate is CURRENT ITEM DATE of type created or modified or publish_up or CUSTOM date field
             switch ($behaviour_dates) {
                 case '1':
                     // custom offset
                     if ($edate) {
                         $edate = array(0 => preg_replace("/[^-+0-9\\s]/", "", $edate), 1 => preg_replace("/[0-9-+\\s]/", "", $edate));
                         if (empty($edate[1])) {
                             echo "<b>WARNING:</b> Misconfigured date scope, you have entered invalid -END- date:Custom offset is invalid e.g. in order to enter five days ago (be careful with space character) use: -5 d (DO NOT FORGET the space between e.g. '-5 d')<br/>";
                             return;
                         } else {
                             $where .= ' AND ( ' . $comp . ' < ' . $db->Quote(date_time::shift_dates($cdate, $edate[0], $edate[1])) . ($nulldates ? ' OR ' . $comp . ' IS NULL OR ' . $comp . '="" ' : '') . ' )';
                         }
                     }
                     if ($bdate) {
                         $bdate = array(0 => preg_replace("/[^-+0-9]/", "", $bdate), 1 => preg_replace("/[0-9-+]/", "", $bdate));
                         if (empty($bdate[1])) {
                             echo "<b>WARNING:</b> Misconfigured date scope, you have entered invalid -BEGIN- date: Custom offset is invalid e.g. in order to enter five days ago (be careful with space character) use: -5 d (DO NOT FORGET the space between e.g. '-5 d')<br/>";
                             return;
                         } else {
                             $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote(date_time::shift_dates($cdate, $bdate[0], $bdate[1])) . ($nulldates ? ' OR ' . $comp . ' IS NULL OR ' . $comp . '="" ' : '') . ' )';
                         }
                     }
                     break;
                 case '8':
                     // same day
                     $cdate = explode(' ', $cdate);
                     $cdate = explode('-', $cdate[0]);
                     $cdate = $cdate[0] . '-' . $cdate[1] . '-' . $cdate[2] . ' 00:00:00';
                     $where .= ' AND ( ' . $comp . ' < ' . $db->Quote(date_time::shift_dates($cdate, 1, 'd')) . ' )';
                     $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote($cdate) . ' )';
                     break;
                 case '2':
                     // same month
                     $cdate = explode(' ', $cdate);
                     $cdate = explode('-', $cdate[0]);
                     $cdate = $cdate[0] . '-' . $cdate[1] . '-01 00:00:00';
                     $where .= ' AND ( ' . $comp . ' < ' . $db->Quote(date_time::shift_dates($cdate, 1, 'm')) . ' )';
                     $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote($cdate) . ' )';
                     break;
                 case '3':
                     // same year
                     $cdate = explode(' ', $cdate);
                     $cdate = explode('-', $cdate[0]);
                     $cdate = $cdate[0] . '-01-01 00:00:00';
                     $where .= ' AND ( ' . $comp . ' < ' . $db->Quote(date_time::shift_dates($cdate, 1, 'Y')) . ' )';
                     $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote($cdate) . ' )';
                     break;
                 case '9':
                     // previous day
                     $cdate = explode(' ', $cdate);
                     $cdate = explode('-', $cdate[0]);
                     $cdate = $cdate[0] . '-' . $cdate[1] . '-' . $cdate[2] . ' 00:00:00';
                     $where .= ' AND ( ' . $comp . ' < ' . $db->Quote($cdate) . ' )';
                     $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote(date_time::shift_dates($cdate, -1, 'd')) . ' )';
                     break;
                 case '4':
                     // previous month
                     $cdate = explode(' ', $cdate);
                     $cdate = explode('-', $cdate[0]);
                     $cdate = $cdate[0] . '-' . $cdate[1] . '-01 00:00:00';
                     $where .= ' AND ( ' . $comp . ' < ' . $db->Quote($cdate) . ' )';
                     $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote(date_time::shift_dates($cdate, -1, 'm')) . ' )';
                     break;
                 case '5':
                     // previous year
                     $cdate = explode(' ', $cdate);
                     $cdate = explode('-', $cdate[0]);
                     $cdate = $cdate[0] . '-01-01 00:00:00';
                     $where .= ' AND ( ' . $comp . ' < ' . $db->Quote($cdate) . ' )';
                     $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote(date_time::shift_dates($cdate, -1, 'Y')) . ' )';
                     break;
                 case '10':
                     // next day
                     $cdate = explode(' ', $cdate);
                     $cdate = explode('-', $cdate[0]);
                     $cdate = $cdate[0] . '-' . $cdate[1] . '-' . $cdate[2] . ' 00:00:00';
                     $where .= ' AND ( ' . $comp . ' < ' . $db->Quote(date_time::shift_dates($cdate, 2, 'd')) . ' )';
                     $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote(date_time::shift_dates($cdate, 1, 'd')) . ' )';
                     break;
                 case '6':
                     // next month
                     $cdate = explode(' ', $cdate);
                     $cdate = explode('-', $cdate[0]);
                     $cdate = $cdate[0] . '-' . $cdate[1] . '-01 00:00:00';
                     $where .= ' AND ( ' . $comp . ' < ' . $db->Quote(date_time::shift_dates($cdate, 2, 'm')) . ' )';
                     $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote(date_time::shift_dates($cdate, 1, 'm')) . ' )';
                     break;
                 case '7':
                     // next year
                     $cdate = explode(' ', $cdate);
                     $cdate = explode('-', $cdate[0]);
                     $cdate = $cdate[0] . '-01-01 00:00:00';
                     $where .= ' AND ( ' . $comp . ' < ' . $db->Quote(date_time::shift_dates($cdate, 2, 'Y')) . ' )';
                     $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote(date_time::shift_dates($cdate, 1, 'Y')) . ' )';
                     break;
                 case '11':
                     // same day of month, ignore year
                     $where .= ' AND ( DAYOFMONTH(' . $comp . ') = ' . 'DAYOFMONTH(' . $db->Quote($cdate) . ') AND MONTH(' . $comp . ') = ' . 'MONTH(' . $db->Quote($cdate) . ') )';
                     break;
                 case '12':
                     // [-3d,+3d] days of month, IGNORE YEAR
                     $where .= ' AND ((DAYOFMONTH(' . $db->Quote($cdate) . ')-3) <= DAYOFMONTH(' . $comp . ') AND DAYOFMONTH(' . $comp . ') <= (DAYOFMONTH(' . $db->Quote($cdate) . ')+4) AND MONTH(' . $comp . ') = ' . 'MONTH(' . $db->Quote($cdate) . ') )';
                     break;
                 case '13':
                     // same week of month, IGNORE YEAR
                     $week_start = (int) $params->get('week_start', 0);
                     // 0 is sunday, 5 is monday
                     $week_of_month = '(WEEK(%s,5) - WEEK(DATE_SUB(%s, INTERVAL DAYOFMONTH(%s)-1 DAY),5)+1)';
                     $where .= ' AND (' . str_replace('%s', $comp, $week_of_month) . ' = ' . str_replace('%s', $db->Quote($cdate), $week_of_month) . ' AND ( MONTH(' . $comp . ') = ' . 'MONTH(' . $db->Quote($cdate) . ') ) )';
                     break;
                 case '14':
                     // same week of year, IGNORE YEAR
                     $week_start = (int) $params->get('week_start', 0);
                     // 0 is sunday, 5 is monday
                     $where .= ' AND ( WEEK(' . $comp . ') = ' . 'WEEK(' . $db->Quote($cdate) . ',' . $week_start . ') )';
                     break;
                 case '15':
                     // same month of year, IGNORE YEAR
                     $where .= ' AND ( MONTH(' . $comp . ') = ' . 'MONTH(' . $db->Quote($cdate) . ') )';
                     break;
                 case '16':
                     // same day of month, IGNORE MONTH, YEAR
                     $where .= ' AND ( DAYOFMONTH(' . $comp . ') = ' . 'DAYOFMONTH(' . $db->Quote($cdate) . ') )';
                     break;
                 case '17':
                     // [-3d,+3d] days of month, IGNORE  MONTH, YEAR
                     $where .= ' AND ((DAYOFMONTH(' . $db->Quote($cdate) . ')-3) <= DAYOFMONTH(' . $comp . ') AND DAYOFMONTH(' . $comp . ') <= (DAYOFMONTH(' . $db->Quote($cdate) . ')+4) )';
                     break;
                 case '18':
                     // same week of month, IGNORE MONTH, YEAR
                     $week_start = (int) $params->get('week_start', 0);
                     // 0 is sunday, 5 is monday
                     $week_of_month = '(WEEK(%s,5) - WEEK(DATE_SUB(%s, INTERVAL DAYOFMONTH(%s)-1 DAY),5)+1)';
                     $where .= ' AND (' . str_replace('%s', $comp, $week_of_month) . ' = ' . str_replace('%s', $db->Quote($cdate), $week_of_month) . ' )';
                     break;
             }
         }
     }
     // *****************************
     // EXTRA joins for special cases
     // *****************************
     // EXTRA joins when comparing to custom date field
     $join_date = '';
     if ($behaviour_dates || $method_dates != 1) {
         // using date SCOPE: dynamic behaviour, or static behavior with (static) method != ALL(=1)
         if (($bdate || $edate || $behaviour_dates) && $date_type == 3) {
             if ($datecomp_field) {
                 $join_date = '	LEFT JOIN #__flexicontent_fields_item_relations AS dfrel' . '   ON ( i.id = dfrel.item_id AND dfrel.field_id = ' . $datecomp_field . ' )';
             } else {
                 echo "<b>WARNING:</b> Misconfigured date scope, you have set DATE TYPE as CUSTOM DATE Field, but have not select any specific DATE Field to be used<br/>";
                 //$join_date = '';
                 return;
             }
         }
     }
     // *****************************************************************************************************************************
     // Get orderby SQL CLAUSE ('ordering' is passed by reference but no frontend user override is used (we give empty 'request_var')
     // *****************************************************************************************************************************
     $orderby = flexicontent_db::buildItemOrderBy($params, $ordering, $request_var = '', $config_param = 'ordering', $item_tbl_alias = 'i', $relcat_tbl_alias = 'rel', $default_order = '', $default_order_dir = '', $sfx = '', $support_2nd_lvl = true);
     //echo "<br/>" . print_r($ordering, true) ."<br/>";
     // EXTRA join of field used in custom ordering
     // NOTE: if (1st/2nd level) custom field id is not set, THEN 'field' ordering was changed to level's default, by the ORDER CLAUSE creating function
     $orderby_join = '';
     // Create JOIN for ordering items by a custom field (Level 1)
     if ('field' == $ordering[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' == $ordering[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', $ordering) || in_array('rauthor', $ordering)) {
         $orderby_join .= ' LEFT JOIN #__users AS u ON u.id = i.created_by';
     }
     // *****************************************************
     // Decide Select Sub-Clause and Join-Clause for comments
     // *****************************************************
     $display_comments = $params->get('display_comments');
     $display_comments_feat = $params->get('display_comments_feat');
     // Check (when needed) if jcomments are installed, and also clear 'commented' ordering if they jcomments is missing
     if ($display_comments_feat || $display_comments || in_array('commented', $ordering)) {
         // Handle jcomments integratio. No need to reset 'commented' ordering if jcomments not installed,
         // and neither print message, the ORDER CLAUSE creating function should have done this already
         if (!file_exists(JPATH_SITE . DS . 'components' . DS . 'com_jcomments' . DS . 'jcomments.php')) {
             //echo "jcomments not installed, you need jcomments to use 'Most commented' ordering OR display comments information.<br>\n";
             $jcomments_exist = false;
         } else {
             $jcomments_exist = true;
         }
     }
     // Decide to JOIN (or not) with comments TABLE, needed when displaying comments and/or when ordering by comments
     $add_comments = ($display_comments_feat || $display_comments || in_array('commented', $ordering)) && $jcomments_exist;
     // Additional select and joins for comments
     $select_comments = $add_comments ? ', COUNT(DISTINCT com.id) AS comments_total' : '';
     $join_comments_type = $ordering[1] == 'commented' ? ' INNER JOIN' : ' LEFT JOIN';
     // Do not require most commented for 2nd level ordering
     $join_comments = $add_comments ? $join_comments_type . ' #__jcomments AS com ON com.object_id = i.id AND com.object_group="com_flexicontent" AND com.published="1"' : '';
     // **********************************************************
     // Decide Select Sub-Clause and Join-Clause for voting/rating
     // **********************************************************
     $display_voting = $params->get('display_voting');
     $display_voting_feat = $params->get('display_voting_feat');
     // Decide to JOIN (or not) with rating TABLE, needed when displaying ratings and/or when ordering by ratings
     $add_rated = $display_voting_feat || $display_voting || in_array('rated', $ordering);
     // Additional select and joins for ratings
     $select_rated = in_array('rated', $ordering) ? ', (cr.rating_sum / cr.rating_count) * 20 AS votes' : '';
     $select_rated .= $add_rated ? ', cr.rating_sum as rating_sum, cr.rating_count as rating_count' : '';
     $join_rated_type = in_array('rated', $ordering) ? ' INNER JOIN' : ' LEFT JOIN';
     $join_rated = $add_rated ? $join_rated_type . ' #__content_rating AS cr ON cr.content_id = i.id' : '';
     // ***********************************************************
     // Finally put together the query to retrieve the listed items
     // ***********************************************************
     // ******************
     // Custom FIELD scope
     // ******************
     $where_field_filters = '';
     $join_field_filters = '';
     // ZERO 'behaviour' means statically selected records, but METHOD 1 is ALL records ... so NOTHING to do
     if (!$behaviour_filt && $method_filt == 1) {
     } else {
         if ($behaviour_filt == 0 || $behaviour_filt == 2) {
             $negate_op = $method_filt == 2 ? 'NOT' : '';
             // These field filters apply a STATIC filtering, regardless of current item being displayed.
             // Static Field Filters (These are a string that MAPs filter ID TO filter VALUES)
             $static_filters_data = FlexicontentFields::setFilterValues($params, 'static_filters', $is_persistent = 1, $set_method = "array");
             // Dynamic Field Filters (THIS is filter IDs list)
             // These field filters apply a DYNAMIC filtering, that depend on current item being displayed. The items that have same value as currently displayed item will be included in the list.
             //$dynamic_filters = FlexicontentFields::setFilterValues( $params, 'dynamic_filters', $is_persistent=0);
             foreach ($static_filters_data as $filter_id => $filter_values) {
                 // Handle single-valued filter as multi-valued
                 if (!is_array($filter_values)) {
                     $filter_values = array(0 => $filter_values);
                 }
                 // Single or Multi valued filter
                 if (isset($filter_values[0])) {
                     $in_values = array();
                     foreach ($filter_values as $val) {
                         $in_values[] = $db->Quote($val);
                     }
                     // Quote in case they are strings !!
                     $where_field_filters .= ' AND ' . $negate_op . ' (rel' . $filter_id . '.value IN (' . implode(',', $in_values) . ') ) ';
                 } else {
                     // Special case only one part of range provided ... must MATCH/INCLUDE empty values or NULL values ...
                     $value_empty = !strlen(@$filter_values[1]) && strlen(@$filter_values[2]) ? ' OR rel' . $filter_id . '.value="" OR rel' . $filter_id . '.value IS NULL ' : '';
                     if (strlen(@$filter_values[1]) || strlen(@$filter_values[2])) {
                         $where_field_filters .= ' AND ' . $negate_op . ' ( 1 ';
                         if (strlen(@$filter_values[1])) {
                             $where_field_filters .= ' AND (rel' . $filter_id . '.value >=' . $filter_values[1] . ') ';
                         }
                         if (strlen(@$filter_values[2])) {
                             $where_field_filters .= ' AND (rel' . $filter_id . '.value <=' . $filter_values[2] . $value_empty . ') ';
                         }
                         $where_field_filters .= ' )';
                     }
                 }
                 $join_field_filters .= ' JOIN #__flexicontent_fields_item_relations AS rel' . $filter_id . ' ON rel' . $filter_id . '.item_id=i.id AND rel' . $filter_id . '.field_id = ' . $filter_id;
             }
         }
     }
     if ($behaviour_filt == 1 || $behaviour_filt == 2) {
         if (!$isflexi_itemview) {
             return;
             // current view is not item view ... , nothing to display
         }
         // 1. Get ids of dynamic filters
         //$dynamic_filter_ids = preg_split("/[\s]*,[\s]*/", $dynamic_filters);
         $dynamic_filter_ids = FLEXIUtilities::paramToArray($dynamic_filters, "/[\\s]*,[\\s]*/", "intval");
         if (empty($dynamic_filter_ids)) {
             echo "Please enter at least 1 field in Custom field filtering SCOPE, or set behaviour to static";
         } else {
             // 2. Get values of dynamic filters
             $where2 = count($dynamic_filter_ids) > 1 ? ' AND field_id IN (' . implode(',', $dynamic_filter_ids) . ')' : ' AND field_id = ' . $dynamic_filter_ids[0];
             // select the item ids related to current item via the relation fields
             $query2 = 'SELECT DISTINCT value, field_id' . ' FROM #__flexicontent_fields_item_relations' . ' WHERE item_id = ' . (int) $id . $where2;
             $db->setQuery($query2);
             $curritem_vals = $db->loadObjectList();
             //echo "<pre>"; print_r($curritem_vals); echo "</pre>";
             // 3. Group values by field
             $_vals = array();
             foreach ($curritem_vals as $v) {
                 $_vals[$v->field_id][] = $v->value;
             }
             foreach ($dynamic_filter_ids as $filter_id) {
                 // Handle non-existent value by requiring that matching item do not have a value for this field either
                 if (!isset($_vals[$filter_id])) {
                     $where_field_filters .= ' AND reldyn' . $filter_id . '.value IS NULL';
                 } else {
                     $in_values = array();
                     foreach ($_vals[$filter_id] as $v) {
                         $in_values[] = $db->Quote($v);
                     }
                     $where_field_filters .= ' AND reldyn' . $filter_id . '.value IN (' . implode(',', $in_values) . ') ' . "\n";
                 }
                 $join_field_filters .= ' JOIN #__flexicontent_fields_item_relations AS reldyn' . $filter_id . ' ON reldyn' . $filter_id . '.item_id=i.id AND reldyn' . $filter_id . '.field_id = ' . $filter_id . "\n";
             }
             //echo "<pre>"."\n\n".$join_field_filters ."\n\n".$where_field_filters."</pre>";
         }
     }
     if (empty($items_query)) {
         // If a custom query has not been set above then use the default one ...
         $items_query = 'SELECT ' . ' i.id ' . (in_array('commented', $ordering) ? $select_comments : '') . (in_array('rated', $ordering) ? $select_rated : '') . ' FROM #__flexicontent_items_tmp AS i' . ' JOIN #__flexicontent_items_ext AS ie on ie.item_id = i.id' . ' JOIN #__flexicontent_types AS ty on ie.type_id = ty.id' . ' JOIN #__flexicontent_cats_item_relations AS rel ON rel.itemid = i.id' . ' JOIN #__categories AS  c ON  c.id = rel.catid' . ' JOIN #__categories AS mc ON mc.id = i.catid' . $joinaccess . $join_favs . $join_date . (in_array('commented', $ordering) ? $join_comments : '') . (in_array('rated', $ordering) ? $join_rated : '') . $orderby_join . $join_field_filters . $where . ' ' . ($apply_config_per_category ? '__CID_WHERE__' : '') . $where_field_filters . ' GROUP BY i.id' . $orderby;
         // if using CATEGORY SCOPE INCLUDE ... then link though them ... otherwise via main category
         $_cl = !$behaviour_cat && $method_cat == 3 ? 'c' : 'mc';
         $items_query_data = 'SELECT ' . ' i.*, ie.*, ty.name AS typename' . $select_comments . $select_rated . ', mc.title AS maincat_title, mc.alias AS maincat_alias' . ', 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(\':\', ' . $_cl . '.id, ' . $_cl . '.alias) ELSE ' . $_cl . '.id END as categoryslug' . ', GROUP_CONCAT(rel.catid SEPARATOR ",") as itemcats' . ' FROM #__content AS i' . ' JOIN #__flexicontent_items_ext AS ie on ie.item_id = i.id' . ' JOIN #__flexicontent_types AS ty on ie.type_id = ty.id' . ' JOIN #__flexicontent_cats_item_relations AS rel ON rel.itemid = i.id' . ' JOIN #__categories AS  c ON  c.id = rel.catid' . ' JOIN #__categories AS mc ON mc.id = i.catid' . $joinaccess . $join_favs . $join_date . $join_comments . $join_rated . $orderby_join . ' WHERE i.id IN (__content__)' . ' GROUP BY i.id';
     }
     // **********************************
     // Execute query once OR per category
     // **********************************
     if (!isset($multiquery_cats)) {
         $multiquery_cats = array(0 => "");
     }
     foreach ($multiquery_cats as $catid => $cat_where) {
         $_microtime = $modfc_jprof->getmicrotime();
         // Get content list per given category
         $per_cat_query = str_replace('__CID_WHERE__', $cat_where, $items_query);
         $db->setQuery($per_cat_query, 0, $count);
         $content = $db->loadColumn(0);
         if ($db->getErrorNum()) {
             JFactory::getApplication()->enqueueMessage(__FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($db->getErrorMsg()), 'error');
         }
         @($mod_fc_run_times['query_items'] += $modfc_jprof->getmicrotime() - $_microtime);
         // Check for no content found for given category
         if (empty($content)) {
             $cat_items_arr[$catid] = array();
             continue;
         }
         $_microtime = $modfc_jprof->getmicrotime();
         // Get content list data per given category
         $per_cat_query = str_replace('__content__', implode(',', $content), $items_query_data);
         $db->setQuery($per_cat_query, 0, $count);
         $_rows = $db->loadObjectList('item_id');
         if ($db->getErrorNum()) {
             JFactory::getApplication()->enqueueMessage(__FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($db->getErrorMsg()), 'error');
         }
         @($mod_fc_run_times['query_items_sec'] += $modfc_jprof->getmicrotime() - $_microtime);
         // Secondary content list ordering and assign content list per category
         $rows = array();
         foreach ($content as $_id) {
             $rows[] = $_rows[$_id];
         }
         $cat_items_arr[$catid] = $rows;
         // Get Original content ids for creating some untranslatable fields that have share data (like shared folders)
         flexicontent_db::getOriginalContentItemids($cat_items_arr[$catid]);
     }
     // ************************************************************************************************
     // Return items indexed per category id OR via empty string if not apply configuration per category
     // ************************************************************************************************
     return $cat_items_arr;
 }
 /**
  * Utility function to load each JS Frameworks once
  *
  * @param 	string 		$text
  * @param 	int 		$nb
  * @return 	string
  * @since 1.5
  */
 static function loadFramework($framework, $mode = '')
 {
     // Detect already loaded framework
     static $_loaded = array();
     if (isset($_loaded[$framework])) {
         return $_loaded[$framework];
     }
     $_loaded[$framework] = false;
     // Get frameworks that are configured to be loaded manually in frontend (e.g. via the Joomla template)
     $app = JFactory::getApplication();
     static $load_frameworks = null;
     static $load_jquery = null;
     if (!isset($load_frameworks[$framework])) {
         $flexiparams = JComponentHelper::getParams('com_flexicontent');
         //$load_frameworks = $flexiparams->get('load_frameworks', array('jQuery','image-picker','masonry','select2','inputmask','prettyCheckable','fancybox'));
         //$load_frameworks = FLEXIUtilities::paramToArray($load_frameworks);
         //$load_frameworks = array_flip($load_frameworks);
         //$load_jquery = isset($load_frameworks['jQuery']) || !$app->isSite();
         if ($load_jquery === null) {
             $load_jquery = $flexiparams->get('loadfw_jquery', 1) == 1 || !$app->isSite();
         }
         $load_framework = $flexiparams->get('loadfw_' . strtolower(str_replace('-', '_', $framework)), 1);
         $load_frameworks[$framework] = $load_framework == 1 || $load_framework == 2 && !$app->isSite();
     }
     // Set loaded flag
     $_loaded[$framework] = $load_frameworks[$framework];
     // Do not progress further if it is disabled
     if (!$load_frameworks[$framework]) {
         return false;
     }
     // Load Framework
     $document = JFactory::getDocument();
     $lib_path = '/components/com_flexicontent/librairies';
     $js = "";
     $css = "";
     switch ($framework) {
         case 'jQuery':
             if ($load_jquery) {
                 flexicontent_html::loadJQuery();
             }
             break;
         case 'mCSB':
             if ($load_jquery) {
                 flexicontent_html::loadJQuery();
             }
             $framework_path = JURI::root(true) . $lib_path . '/mCSB';
             $document->addScript($framework_path . '/jquery.mCustomScrollbar.min.js');
             $document->addStyleSheet($framework_path . '/jquery.mCustomScrollbar.css');
             $js .= "\n\t\t\t\t\tjQuery(document).ready(function(){\n\t\t\t\t\t\tjQuery('.fc_add_scroller').mCustomScrollbar({\n\t\t\t\t\t\t\ttheme:'dark-thick',\n\t\t\t\t\t\t\tadvanced:{updateOnContentResize: true}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tjQuery('.fc_add_scroller_horizontal').mCustomScrollbar({\n\t\t\t\t\t\t\ttheme:'dark-thick',\n\t\t\t\t\t\t\thorizontalScroll:true,\n\t\t\t\t\t\t\tadvanced:{updateOnContentResize: true}\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t";
             break;
         case 'image-picker':
             if ($load_jquery) {
                 flexicontent_html::loadJQuery();
             }
             $framework_path = JURI::root(true) . $lib_path . '/image-picker';
             $document->addScript($framework_path . '/image-picker.min.js');
             $document->addStyleSheet($framework_path . '/image-picker.css');
             break;
         case 'masonry':
             $framework_path = JURI::root(true) . $lib_path . '/masonry';
             $document->addScript($framework_path . '/masonry.pkgd.min.js');
             break;
         case 'select2':
             if ($load_jquery) {
                 flexicontent_html::loadJQuery();
             }
             // Replace chosen function (if loaded)
             //JHtml::_('formbehavior.chosen', '#_some_iiidddd_');
             $js .= "\n\t\t\t\tif (typeof jQuery.fn.chosen == 'function') { \n\t\t\t\t\tjQuery.fn.chosen_fc = jQuery.fn.chosen;\n\t\t\t\t\tjQuery.fn.chosen = function(){\n\t\t\t\t\t\tvar args = arguments;\n\t\t\t\t\t\tjQuery(this).each(function() {\n\t\t\t\t\t\t\tif (jQuery(this).hasClass('use_select2_lib')) return;\n\t\t\t\t\t\t\tjQuery(this).chosen_fc(args);\n\t\t\t\t\t\t});\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\t";
             $ver = '3.5.4';
             $framework_path = JURI::root(true) . $lib_path . '/select2';
             $framework_folder = JPATH_SITE . DS . 'components' . DS . 'com_flexicontent' . DS . 'librairies' . DS . 'select2';
             $document->addScriptVersion($framework_path . '/select2.min.js', $ver);
             $document->addStyleSheetVersion($framework_path . '/select2.css', $ver);
             $lang_code = flexicontent_html::getUserCurrentLang();
             if ($lang_code && $lang_code != 'en') {
                 // Try language shortcode
                 if (file_exists($framework_folder . DS . 'select2_locale_' . $lang_code . '.js')) {
                     $document->addScriptVersion($framework_path . '/select2_locale_' . $lang_code . '.js', $ver);
                 } else {
                     $country_code = flexicontent_html::getUserCurrentLang($short_tag = false);
                     if ($country_code && file_exists($framework_folder . DS . 'select2_locale_' . $country_code . '.js')) {
                         $document->addScriptVersion($framework_path . '/select2_locale_' . $country_code . '.js', $ver);
                     }
                 }
             }
             $js .= "\n\t\t\t\t\tjQuery(document).ready(function() {\n\t\t\t\t\t\t\n\t\t\t\t\t\t" . "\n\t\t\t\t\t\tjQuery('select.use_select2_lib').select2({\n\t\t\t\t\t\t\t/*hideSelectionFromResult: function(selectedObject) { selectedObject.removeClass('select2-result-selectable').addClass('select2-result-unselectable').addClass('select2-disabled'); return false; },*/\n\t\t\t\t\t\t\tminimumResultsForSearch: 10\n\t\t\t\t\t\t});\n\t\t\t\t\t\t\n\t\t\t\t\t\tjQuery('div.use_select2_lib').each(function() {\n\t\t\t\t\t\t\tvar el_container = jQuery(this);\n\t\t\t\t\t\t\tvar el_select = el_container.next('select');\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t" . "\n\t\t\t\t\t\t\tvar fc_label_text = el_select.attr('data-fc_label_text');\n\t\t\t\t\t\t\tif (!fc_label_text) fc_label_text = el_select.attr('fc_label_text');\n\t\t\t\t\t\t\tif (fc_label_text) {\n\t\t\t\t\t\t\t\tvar _label = (fc_label_text.length >= 30) ? fc_label_text.substring(0, 28) + '...' : fc_label_text;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tjQuery('<span/>', {\n\t\t\t\t\t\t\t\t\t'class': 'fc_has_inner_label fc_has_inner_label_select2',\n\t\t\t\t\t\t\t\t\t'text': _label\n\t\t\t\t\t\t\t\t}).prependTo(el_container.find('.select2-search-field'));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t" . "\n\t\t\t\t\t\t\tvar fc_prompt_text = el_select.attr('data-fc_prompt_text');\n\t\t\t\t\t\t\tif (!fc_prompt_text) fc_prompt_text = el_select.attr('fc_prompt_text');\n\t\t\t\t\t\t\tif (fc_prompt_text) {\n\t\t\t\t\t\t\t\tvar _prompt = (fc_prompt_text.length >= 30) ? fc_prompt_text.substring(0, 28) + '...' : fc_prompt_text;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tjQuery('<span/>', {\n\t\t\t\t\t\t\t\t\t'class': 'fc_has_inner_prompt fc_has_inner_prompt_select2',\n\t\t\t\t\t\t\t\t\t'text': _prompt\n\t\t\t\t\t\t\t\t}).prependTo(el_container.find('.select2-search-field')).hide();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t" . "\n\t\t\t\t\t\t\tif ( ! el_select.attr('multiple') && !el_select.hasClass('fc_skip_highlight') ) {\n\t\t\t\t\t\t\t\tvar el = el_container.find('.select2-choice');\n\t\t\t\t\t\t\t\tvar val = el_select.val();\n\t\t\t\t\t\t\t\tif (val === null) {\n\t\t\t\t\t\t\t\t\t//el.addClass('fc_highlight_disabled');\n\t\t\t\t\t\t\t\t} else if (!!val && val.length) {\n\t\t\t\t\t\t\t\t\tel.addClass('fc_highlight');\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tel.removeClass('fc_highlight');\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\n\t\t\t\t\t\t" . "\n\t\t\t\t\t\tjQuery('select.use_select2_lib').on('select2-open', function() {\n\t\t\t\t\t\t\t" . "\n\t\t\t\t\t\t\tvar el_container = jQuery(this).parent();\n\t\t\t\t\t\t\tvar el = jQuery(this).parent().find('.select2-input');\n\t\t\t\t\t\t\tvar el_label = el.prevAll('.fc_has_inner_label');\n\t\t\t\t\t\t\tif (el_label) el_label.hide();\n\t\t\t\t\t\t\tvar el_prompt = el.prevAll('.fc_has_inner_prompt');\n\t\t\t\t\t\t\tif (el_prompt) el_prompt.show();\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t" . "\n\t\t\t\t\t\t\tif (jQuery(this).hasClass('select2_list_selected')) {\n\t\t\t\t\t\t\t\tvar els = jQuery('#select2-drop').find('.select2-selected');\n\t\t\t\t\t\t\t\tels.addClass('select2-selected-highlight').addClass('select2-disabled').removeClass('select2-selected').removeClass('select2-result-selectable');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}).on('select2-close', function() {\n\t\t\t\t\t\t\t" . "\n\t\t\t\t\t\t\tvar el_container = jQuery(this).parent();\n\t\t\t\t\t\t\tvar el = jQuery(this).parent().find('.select2-input');\n\t\t\t\t\t\t\tvar el_label = el.prevAll('.fc_has_inner_label');\n\t\t\t\t\t\t\tif (el_label) el_label.show();\n\t\t\t\t\t\t\tvar el_prompt = el.prevAll('.fc_has_inner_prompt');\n\t\t\t\t\t\t\tif (el_prompt) el_prompt.hide();\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t" . "\n\t\t\t\t\t\t\tif (jQuery(this).hasClass('select2_list_selected')) {\n\t\t\t\t\t\t\t\tvar els = jQuery('#select2-drop').find('.select2-selected-highlight');\n\t\t\t\t\t\t\t\tels.removeClass('select2-selected-highlight').removeClass('select2-disabled').addClass('select2-result-selectable');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}).on\n\t\t\t\t\t\t\n\t\t\t\t\t\t" . "\n\t\t\t\t\t\t('change', function() {\n\t\t\t\t\t\t\tvar el_select = jQuery(this);\n\t\t\t\t\t\t\tif ( ! el_select.attr('multiple') && !el_select.hasClass('fc_skip_highlight') ) {\n\t\t\t\t\t\t\t\tvar el = jQuery(this).prev('div').find('.select2-choice');\n\t\t\t\t\t\t\t\tvar val = el_select.val();\n\t\t\t\t\t\t\t\tif (!!val && val.length) {\n\t\t\t\t\t\t\t\t\tel.addClass('fc_highlight');\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tel.removeClass('fc_highlight');\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\n\t\t\t\t\t\t" . "\n\t\t\t\t\t\tjQuery('div.use_select2_lib.select2-container-multi input').on('keydown', function() {\n\t\t\t\t\t\t\tvar el = jQuery(this);\n\t\t\t\t\t\t\tsetTimeout(function() {\n\t\t\t\t\t\t\t\tvar val = el.val();\n\t\t\t\t\t\t\t\tif (!!val && val.length) {\n\t\t\t\t\t\t\t\t\tvar el_prompt = el.prevAll('.fc_has_inner_prompt');\n\t\t\t\t\t\t\t\t\tif (el_prompt) el_prompt.hide();\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tvar el_prompt = el.prevAll('.fc_has_inner_prompt');\n\t\t\t\t\t\t\t\t\tif (el_prompt) el_prompt.show();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}, 0);\n\t\t\t\t\t\t});\n\t\t\t\t\t\t\n\t\t\t\t\t\t" . "\n\t\t\t\t\t\tjQuery('select.use_select2_lib').on('loaded open', function() {\n\t\t\t\t\t\t\tvar ul = jQuery('#select2-drop ul.select2-results');\n\t\t\t\t\t\t\tvar needsScroll= ul.prop('scrollHeight') > ul.prop('clientHeight');\n\t\t\t\t\t\t\tif (needsScroll) ul.css('overflow-y', 'scroll');\n\t\t\t\t\t\t\telse  ul.css('overflow-y', 'auto');\n\t\t\t\t\t\t});\n\t\t\t\t\t\t\n\t\t\t\t\t});\n\t\t\t\t";
             break;
         case 'inputmask':
             if ($load_jquery) {
                 flexicontent_html::loadJQuery();
             }
             $framework_path = JURI::root(true) . $lib_path . '/inputmask';
             $document->addScript($framework_path . '/jquery.inputmask.bundle.min.js');
             // Extra inputmask declarations definitions, e.g. ...
             $js .= "\n\t\t\t\t";
             // Attach inputmask to all input fields that have appropriate tag parameters
             $js .= "\n\t\t\t\t\tjQuery(document).ready(function(){\n\t\t\t\t\t\tInputmask.extendAliases({\n\t\t\t\t\t\t\tdecimal: {\n\t\t\t\t\t\t\t\talias: 'numeric',\n\t\t\t\t\t\t\t\tplaceholder: '_',\n\t\t\t\t\t\t\t\tautoGroup: true,\n\t\t\t\t\t\t\t\tradixPoint: '.',\n\t\t\t\t\t\t\t\tgroupSeparator: ',',\n\t\t\t\t\t\t\t\tclearMaskOnLostFocus: true,\n\t\t\t\t\t\t\t\tremoveMaskOnSubmit: true,\n\t\t\t\t\t\t\t\tunmaskAsNumber: false\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tdecimal_comma: {\n\t\t\t\t\t\t\t\talias: 'numeric',\n\t\t\t\t\t\t\t\tplaceholder: '_',\n\t\t\t\t\t\t\t\tautoGroup: true,\n\t\t\t\t\t\t\t\tradixPoint: ',',\n\t\t\t\t\t\t\t\tgroupSeparator: '.',\n\t\t\t\t\t\t\t\tclearMaskOnLostFocus: true,\n\t\t\t\t\t\t\t\tremoveMaskOnSubmit: true,\n\t\t\t\t\t\t\t\tunmaskAsNumber: false\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tcurrency: {\n\t\t\t\t\t\t\t\talias: 'numeric',\n\t\t\t\t\t\t\t\tplaceholder: '_',\n\t\t\t\t\t\t\t\tprefix: '\$ ',\n\t\t\t\t\t\t\t\tgroupSeparator: ',',\n\t\t\t\t\t\t\t\tautoGroup: true,\n\t\t\t\t\t\t\t\tdigits: 2,\n\t\t\t\t\t\t\t\tdigitsOptional: false,\n\t\t\t\t\t\t\t\tclearMaskOnLostFocus: true,\n\t\t\t\t\t\t\t\tremoveMaskOnSubmit: true,\n\t\t\t\t\t\t\t\tunmaskAsNumber: false\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tcurrency_euro: {\n\t\t\t\t\t\t\t\talias: 'currency',\n\t\t\t\t\t\t\t\tplaceholder: '_',\n\t\t\t\t\t\t\t\tprefix: '\\u20ac ',\n\t\t\t\t\t\t\t\tgroupSeparator: ',',\n\t\t\t\t\t\t\t\tautoGroup: true,\n\t\t\t\t\t\t\t\tdigits: 2,\n\t\t\t\t\t\t\t\tdigitsOptional: false,\n\t\t\t\t\t\t\t\tclearMaskOnLostFocus: false,\n\t\t\t\t\t\t\t\tremoveMaskOnSubmit: true,\n\t\t\t\t\t\t\t\tunmaskAsNumber: false\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tpercentage_zero_nolimit: {\n\t\t\t\t\t\t\t\talias: 'percentage',\n\t\t\t\t\t\t\t\tplaceholder: '_',\n\t\t\t\t\t\t\t\tdigits: 2,\n\t\t\t\t\t\t\t\tradixPoint: '.',\n\t\t\t\t\t\t\t\tautoGroup: true,\n\t\t\t\t\t\t\t\tmin: 0,\n\t\t\t\t\t\t\t\tmax: '',\n\t\t\t\t\t\t\t\tsuffix: ' %',\n\t\t\t\t\t\t\t\tallowPlus: false,\n\t\t\t\t\t\t\t\tallowMinus: false,\n\t\t\t\t\t\t\t\tclearMaskOnLostFocus: true,\n\t\t\t\t\t\t\t\tremoveMaskOnSubmit: true,\n\t\t\t\t\t\t\t\tunmaskAsNumber: false\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tpercentage_nolimit_nolimit: {\n\t\t\t\t\t\t\t\talias: 'percentage',\n\t\t\t\t\t\t\t\tplaceholder: '_',\n\t\t\t\t\t\t\t\tdigits: 2,\n\t\t\t\t\t\t\t\tradixPoint: '.',\n\t\t\t\t\t\t\t\tautoGroup: true,\n\t\t\t\t\t\t\t\tmin: '',\n\t\t\t\t\t\t\t\tmax: '',\n\t\t\t\t\t\t\t\tsuffix: ' %',\n\t\t\t\t\t\t\t\tallowPlus: false,\n\t\t\t\t\t\t\t\tallowMinus: true,\n\t\t\t\t\t\t\t\tclearMaskOnLostFocus: true,\n\t\t\t\t\t\t\t\tremoveMaskOnSubmit: true,\n\t\t\t\t\t\t\t\tunmaskAsNumber: false\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tinteger: {\n\t\t\t\t\t\t\t\talias: 'numeric',\n\t\t\t\t\t\t\t\tplaceholder: '_',\n\t\t\t\t\t\t\t\tdigits: 0,\n\t\t\t\t\t\t\t\tradixPoint: '',\n\t\t\t\t\t\t\t\tclearMaskOnLostFocus: true,\n\t\t\t\t\t\t\t\tremoveMaskOnSubmit: true,\n\t\t\t\t\t\t\t\tunmaskAsNumber: false\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tunsigned: {\n\t\t\t\t\t\t\t\talias: 'numeric',\n\t\t\t\t\t\t\t\tplaceholder: '_',\n\t\t\t\t\t\t\t\tdigits: 0,\n\t\t\t\t\t\t\t\tradixPoint: '',\n\t\t\t\t\t\t\t\tallowPlus: false,\n\t\t\t\t\t\t\t\tallowMinus: false,\n\t\t\t\t\t\t\t\tclearMaskOnLostFocus: true,\n\t\t\t\t\t\t\t\tremoveMaskOnSubmit: true,\n\t\t\t\t\t\t\t\tunmaskAsNumber: false\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t'mobile': {\n\t\t\t\t\t\t\t\t'mask': '9999 999 999',\n\t\t\t\t\t\t\t\t'autounmask': true,\n\t\t\t\t\t\t\t\t'insertMode': true,\n\t\t\t\t\t\t\t\tplaceholder: '_',\n\t\t\t\t\t\t\t\tclearMaskOnLostFocus: true,\n\t\t\t\t\t\t\t\tremoveMaskOnSubmit: true,\n\t\t\t\t\t\t\t\tunmaskAsNumber: false\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t\t\n\t\t\t\t\t\tjQuery('input.has_inputmask').inputmask();\n\t\t\t\t\t\tjQuery('input.inputmask-regex').inputmask('Regex');\n\t\t\t\t\t});\n\t\t\t\t";
             break;
         case 'prettyCheckable':
             if ($load_jquery) {
                 flexicontent_html::loadJQuery();
             }
             $framework_path = JURI::root(true) . $lib_path . '/prettyCheckable';
             $document->addScript($framework_path . '/dev/prettyCheckable.js');
             $document->addStyleSheet($framework_path . '/dist/prettyCheckable.css');
             $js .= "\n\t\t\t\t\tjQuery(document).ready(function(){\n\t\t\t\t\t\tjQuery('input.use_prettycheckable').each(function() {\n\t\t\t\t\t\t\tvar elem = jQuery(this);\n\t\t\t\t\t\t\tvar lbl = elem.next('label');\n\t\t\t\t\t\t\tvar lbl_html = elem.next('label').html();\n\t\t\t\t\t\t\tlbl.remove();\n\t\t\t\t\t\t\telem.prettyCheckable({\n\t\t\t\t\t\t\t\tcolor: 'blue',\n\t\t\t\t\t\t\t\tlabel: lbl_html\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t";
             break;
         case 'multibox':
         case 'jmultibox':
             if ($load_jquery) {
                 flexicontent_html::loadJQuery();
             }
             $framework_path = JURI::root(true) . $lib_path . '/jmultibox';
             // Add JS
             $document->addScript($framework_path . '/js/jmultibox.js');
             $document->addScript($framework_path . '/js/jquery.vegas.js');
             // Add CSS
             $document->addStyleSheet($framework_path . '/styles/multibox.css');
             $document->addStyleSheet($framework_path . '/styles/jquery.vegas.css');
             if (substr($_SERVER['HTTP_USER_AGENT'], 0, 34) == "Mozilla/4.0 (compatible; MSIE 6.0;") {
                 $document->addStyleSheet($framework_path . '/styles/multibox-ie6.css');
             }
             // Attach multibox to ... this will be left to the caller so that it will create a multibox object with custom options
             //$js .= "";
             break;
         case 'fancybox':
             if ($load_jquery) {
                 flexicontent_html::loadJQuery();
             }
             $document->addScript(JURI::root(true) . '/components/com_flexicontent/assets/js/jquery-easing.js');
             $framework_path = JURI::root(true) . $lib_path . '/fancybox';
             // Add mousewheel plugin (this is optional)
             $document->addScript($framework_path . '/lib/jquery.mousewheel-3.0.6.pack.js');
             // Add fancyBox CSS / JS
             $document->addStyleSheet($framework_path . '/source/jquery.fancybox.css');
             $document->addScript($framework_path . '/source/jquery.fancybox.pack.js');
             // Optionally add helpers - button, thumbnail and/or media
             $document->addStyleSheet($framework_path . '/source/helpers/jquery.fancybox-buttons.css');
             $document->addScript($framework_path . '/source/helpers/jquery.fancybox-buttons.js');
             $document->addScript($framework_path . '/source/helpers/jquery.fancybox-media.js');
             $document->addStyleSheet($framework_path . '/source/helpers/jquery.fancybox-thumbs.css');
             $document->addScript($framework_path . '/source/helpers/jquery.fancybox-thumbs.js');
             // Attach fancybox to all elements having a specific CSS class
             $js .= "\n\t\t\t\t\tjQuery(document).ready(function(){\n\t\t\t\t\t\tjQuery('.fancybox').fancybox({\n\t\t\t\t\t\t\t'openEffect'\t: 'elastic',\n\t\t\t\t\t\t\t'closeEffect'\t: 'elastic',\n\t\t\t\t\t\t\t'openEasing'  : 'easeOutCubic',\n\t\t\t\t\t\t\t'closeEasing' : 'easeInCubic',\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t";
             break;
         case 'galleriffic':
             if ($load_jquery) {
                 flexicontent_html::loadJQuery();
             }
             //flexicontent_html::loadFramework('fancybox');
             $framework_path = JURI::root(true) . $lib_path . '/galleriffic';
             //$document->addStyleSheet($framework_path.'/css/basic.css');  // This is too generic and should not be loaded
             $document->addStyleSheet($framework_path . '/css/galleriffic-3.css');
             $document->addScript($framework_path . '/js/jquery.galleriffic.js');
             $document->addScript($framework_path . '/js/jquery.opacityrollover.js');
             break;
         case 'elastislide':
             if ($load_jquery) {
                 flexicontent_html::loadJQuery();
             }
             $framework_path = JURI::root(true) . $lib_path . '/elastislide';
             $document->addStyleSheet($framework_path . '/css/style.css');
             $document->addStyleSheet($framework_path . '/css/elastislide.css');
             $document->addScript($framework_path . '/js/jquery.tmpl.min.js');
             $document->addScript($framework_path . '/js/jquery.easing.1.3.js');
             $document->addScript($framework_path . '/js/jquery.elastislide.js');
             //$document->addScript($framework_path.'/js/gallery.js'); // replace with field specific: gallery_tmpl.js
             break;
         case 'photoswipe':
             if ($load_jquery) {
                 flexicontent_html::loadJQuery();
             }
             $framework_path = JURI::root(true) . $lib_path . '/photoswipe';
             //$document->addStyleSheet($framework_path.'/lib/jquery.mobile/jquery.mobile.css');
             $document->addStyleSheet($framework_path . '/photoswipe.css');
             //$document->addScript($framework_path.'/lib/jquery.mobile/jquery.mobile.js');
             $document->addScript($framework_path . '/lib/simple-inheritance.min.js');
             //$document->addScript($framework_path.'/lib/jquery.animate-enhanced.min.js');
             $document->addScript($framework_path . '/code.photoswipe.min.js');
             $js .= "\n\t\t\t\tjQuery(document).ready(function() {\n\t\t\t\t\tvar myPhotoSwipe = jQuery('.photoswipe_fccontainer a').photoSwipe(); \n\t\t\t\t});\n\t\t\t\t";
             break;
         case 'fcxSlide':
             if ($load_jquery) {
                 flexicontent_html::loadJQuery();
             }
             $framework_path = JURI::root(true) . $lib_path . '/fcxSlide';
             $document->addScriptVersion($framework_path . '/class.fcxSlide.js', FLEXI_VERSION);
             $document->addStyleSheetVersion($framework_path . '/fcxSlide.css', FLEXI_VERSION);
             //$document->addScriptVersion($framework_path.'/class.fcxSlide.packed.js', FLEXI_VERSION);
             break;
         case 'imagesLoaded':
             $framework_path = JURI::root(true) . $lib_path . '/imagesLoaded';
             $document->addScript($framework_path . '/imagesloaded.pkgd.min.js');
             break;
         case 'noobSlide':
             // Make sure mootools are loaded
             FLEXI_J30GE ? JHtml::_('behavior.framework', true) : JHTML::_('behavior.mootools');
             $framework_path = JURI::root(true) . $lib_path . '/noobSlide';
             //$document->addScript($framework_path.'/_class.noobSlide.js');
             $document->addScript($framework_path . '/_class.noobSlide.packed.js');
             break;
         case 'zTree':
             if ($load_jquery) {
                 flexicontent_html::loadJQuery();
             }
             $framework_path = JURI::root(true) . $lib_path . '/zTree';
             $document->addStyleSheet($framework_path . '/css/flexi_ztree.css');
             $document->addStyleSheet($framework_path . '/css/zTreeStyle/zTreeStyle.css');
             $document->addScript($framework_path . '/js/jquery.ztree.all-3.5.min.js');
             //$document->addScript($framework_path.'/js/jquery.ztree.core-3.5.js');
             //$document->addScript($framework_path.'/js/jquery.ztree.excheck-3.5.js');
             //$document->addScript($framework_path.'/js/jquery.ztree.exedit-3.5.js');
             break;
         case 'plupload':
             if ($load_jquery) {
                 flexicontent_html::loadJQuery();
             }
             $framework_path = JURI::root(true) . $lib_path . '/plupload';
             $document->addScript($framework_path . '/js/plupload.full.min.js');
             if ($mode == 'ui') {
                 $document->addStyleSheet($framework_path . '/js/jquery.ui.plupload/css/jquery.ui.plupload.css');
                 $document->addScript($framework_path . '/js/jquery.ui.plupload/jquery.ui.plupload.min.js');
                 $document->addScript($framework_path . '/js/themeswitcher.js');
             } else {
                 $document->addStyleSheet($framework_path . '/js/jquery.plupload.queue/css/jquery.plupload.queue.css');
                 $document->addScript($framework_path . '/js/jquery.plupload.queue/jquery.plupload.queue.js');
             }
             $lang_code = flexicontent_html::getUserCurrentLang();
             if ($lang_code && $lang_code != 'en') {
                 // Try language shortcode
                 if (file_exists($framework_folder . DS . 'js' . DS . $lang_code . '.js')) {
                     $document->addScript($framework_path . '/js/' . $lang_code . '.js');
                 } else {
                     $country_code = flexicontent_html::getUserCurrentLang($short_tag = false);
                     if ($country_code && file_exists($framework_folder . DS . 'js' . DS . $country_code . '.js')) {
                         $document->addScript($framework_path . '/js/' . $country_code . '.js');
                     }
                 }
             }
             // For debugging
             //$document->addScript($framework_path.'/js/moxie.min.js');
             //$document->addScript($framework_path.'/js/plupload.dev.js');
             break;
         case 'nouislider':
             $framework_path = JURI::root(true) . $lib_path . '/nouislider';
             $document->addStyleSheet($framework_path . '/nouislider.min.css');
             $document->addScript($framework_path . '/nouislider.min.js');
             break;
         case 'flexi_tmpl_common':
             if ($load_jquery) {
                 flexicontent_html::loadJQuery();
             }
             flexicontent_html::loadFramework('select2');
             // make sure select2 is loaded
             // Make sure user cookie is set
             $jcookie = $app->input->cookie;
             $fc_uid = $jcookie->get('fc_uid', null);
             $hashedUA = JFactory::getUser()->id ? JUserHelper::getShortHashedUserAgent() : 'p';
             if ($fc_uid != $hashedUA) {
                 $jcookie->set('fc_uid', $hashedUA, 0);
             }
             $js .= "\n\t\t\t\t\tvar _FC_GET = " . json_encode($_GET) . ";\n\t\t\t\t";
             $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/tmpl-common.js', FLEXI_VERSION);
             $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/jquery-easing.js', FLEXI_VERSION);
             JText::script("FLEXI_APPLYING_FILTERING", true);
             JText::script("FLEXI_TYPE_TO_LIST", true);
             JText::script("FLEXI_TYPE_TO_FILTER", true);
             JText::script("FLEXI_UPDATING_CONTENTS", true);
             break;
         case 'flexi-lib':
             if ($load_jquery) {
                 flexicontent_html::loadJQuery();
             }
             $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/flexi-lib.js', FLEXI_VERSION);
             JText::script("FLEXI_NOT_AN_IMAGE_FILE", true);
             break;
         default:
             JFactory::getApplication()->enqueueMessage(__FUNCTION__ . ' Cannot load unknown Framework: ' . $framework, 'error');
             break;
     }
     // Add custom JS & CSS code
     if ($js) {
         $document->addScriptDeclaration($js);
     }
     if ($css) {
         $document->addStyleDeclaration($css);
     }
     return $_loaded[$framework];
 }
 /**
  * Load Template-Specific language file to override or add new language strings
  *
  * @return object
  * @since 1.5
  */
 static function loadTemplateLanguageFile($tmplname = 'default', $view = '')
 {
     // Check that template name was given
     $tmplname = empty($tmplname) ? 'default' : $tmplname;
     // This is normally component/module/plugin name, we could use 'category', 'items', etc to have a view specific language file
     // e.g. en/en.category.ini, but this is an overkill and make result into duplication of strings ... better all in one file
     $extension = '';
     // JRequest::get('view');
     // Current language, we decided to use LL-CC (language-country) format mapping SEF shortcode, e.g. 'en' to 'en-GB'
     $user_lang = flexicontent_html::getUserCurrentLang();
     $languages = FLEXIUtilities::getLanguages($hash = 'shortcode');
     if (!$user_lang || !isset($languages->{$user_lang}->code)) {
         return;
     }
     // Language has been disabled
     $language_tag = $languages->{$user_lang}->code;
     // We will use template folder as BASE of language files instead of joomla's language folder
     // Since FLEXIcontent templates are meant to be user-editable it makes sense to place language files inside them
     $base_dir = JPATH_SITE . DS . 'components' . DS . 'com_flexicontent' . DS . 'templates' . DS . $tmplname;
     // Final use joomla's API to load our template's language files -- (load english template language file then override with current language file)
     JFactory::getLanguage()->load($extension, $base_dir, 'en-GB', $reload = true);
     // Fallback to english language template file
     JFactory::getLanguage()->load($extension, $base_dir, $language_tag, $reload = true);
     // User's current language template file
 }
 /**
  * Logic to get text search autocomplete strings
  *
  * @access public
  * @return void
  * @since 1.0
  */
 function txtautocomplete()
 {
     $app = JFactory::getApplication();
     $cparams = JComponentHelper::getParams('com_flexicontent');
     $option = JRequest::getVar('option');
     $use_tmp = true;
     $min_word_len = $app->getUserState($option . '.min_word_len', 0);
     $filtercat = $cparams->get('filtercat', 0);
     // Filter items using currently selected language
     $show_noauth = $cparams->get('show_noauth', 0);
     // Show unauthorized items
     // Get request variables
     $type = JRequest::getVar('type');
     $text = JRequest::getVar('text');
     $pageSize = JRequest::getInt('pageSize', 20);
     $pageNum = JRequest::getInt('pageNum', 1);
     $cid = JRequest::getInt('cid', 0);
     $cids = array();
     $_cids = JRequest::getVar('cids', '');
     if ($cid) {
         // single category view
         global $globalcats;
         $_cids = $globalcats[$cid]->descendantsarray;
     } else {
         if (empty($_cids)) {
             // try to get category ids from the categories filter
             $_cids = JRequest::getVar('filter_13', '');
             $_cids = empty($_cids) ? array() : $_cids;
             $_cids = !is_array($_cids) ? json_decode($_cids) : $_cids;
         } else {
             if (!is_array($_cids)) {
                 // multi category view
                 $_cids = preg_replace('/[^0-9,]/i', '', (string) $_cids);
                 $_cids = explode(',', $_cids);
             }
         }
     }
     // make sure given data are integers ... !!
     foreach ($_cids as $i => $_id) {
         if ((int) $_id) {
             $cids[] = (int) $_id;
         }
     }
     $cid_list = implode(',', $cids);
     $lang = flexicontent_html::getUserCurrentLang();
     // Nothing to do
     if ($type != 'basic_index' && $type != 'adv_index') {
         jexit();
     }
     if (!strlen($text)) {
         jexit();
     }
     // All starting words are exact words but last word is a ... word prefix
     $search_prefix = JComponentHelper::getParams('com_flexicontent')->get('add_search_prefix') ? 'vvv' : '';
     // SEARCH WORD Prefix
     $words = preg_split('/\\s\\s*/u', $text);
     $_words = array();
     foreach ($words as &$_w) {
         $_words[] = !$search_prefix ? trim($_w) : preg_replace('/(\\b[^\\s,\\.]+\\b)/u', $search_prefix . '$0', trim($_w));
     }
     $newtext = '+' . implode(' +', $_words) . '*';
     //print_r($_words); exit;
     // Query CLAUSE for match the given text
     $db = JFactory::getDBO();
     $quoted_text = $db->escape($newtext, true);
     $quoted_text = $db->Quote($quoted_text, false);
     $_text_match = ' MATCH (si.search_index) AGAINST (' . $quoted_text . ' IN BOOLEAN MODE) ';
     // Query retieval limits
     $limitstart = $pageSize * ($pageNum - 1);
     $limit = $pageSize;
     $lang_where = '';
     if ($filtercat) {
         $lang_where .= '   AND ( i.language LIKE ' . $db->Quote($lang . '%') . (FLEXI_J16GE ? ' OR i.language="*" ' : '') . ' ) ';
     }
     $access_where = '';
     $joinaccess = '';
     /*if (!$show_noauth) {
     			$user = JFactory::getUser();
     			$aid_arr = JAccess::getAuthorisedViewLevels($user->id);
     			$aid_list = implode(",", $aid_arr);
     			$access_where .= ' AND ty.access IN (0,'.$aid_list.')';
     			$access_where .= ' AND mc.access IN (0,'.$aid_list.')';
     			$access_where .= ' AND  i.access IN (0,'.$aid_list.')';
     		}*/
     // Do query ...
     $tbl = $type == 'basic_index' ? 'flexicontent_items_ext' : 'flexicontent_advsearch_index';
     $query = 'SELECT si.item_id, si.search_index' . ' FROM #__' . $tbl . ' AS si' . ' JOIN ' . ($use_tmp ? '#__flexicontent_items_tmp' : '#__content') . ' AS i ON i.id = si.item_id' . ($access_where && !$use_tmp || $lang_where && !FLEXI_J16GE && !$use_tmp || $type != 'basic_index' ? ' JOIN #__flexicontent_items_ext AS ie ON i.id = ie.item_id ' : '') . ($access_where ? ' JOIN #__flexicontent_types AS ty ON ie.type_id = ty.id' : '') . ($access_where ? ' JOIN #__categories AS mc ON mc.id = i.catid' : '') . ($cid_list ? ' JOIN #__flexicontent_cats_item_relations AS rel ON i.id = rel.itemid AND rel.catid IN (' . $cid_list . ')' : '') . $joinaccess . ' WHERE ' . $_text_match . '   AND i.state IN (1,-5) ' . $lang_where . $access_where . ' LIMIT ' . $limitstart . ', ' . $limit;
     $db->setQuery($query);
     $data = $db->loadAssocList();
     //print_r($data); exit;
     //if ($db->getErrorNum())  echo __FUNCTION__.'(): SQL QUERY ERROR:<br/>'.nl2br($db->getErrorMsg());
     // Get last word (this is a word prefix) and remove it from words array
     $word_prefix = array_pop($words);
     // Reconstruct search text with complete words (not including last)
     $complete_words = implode(' ', $words);
     // Find out the words that matched
     $words_found = array();
     $regex = '/(\\b)(' . $search_prefix . $word_prefix . '\\w*)(\\b)/iu';
     foreach ($data as $_d) {
         //echo $_d['item_id'] . ' ';
         if (preg_match_all($regex, $_d['search_index'], $matches)) {
             //print_r($matches[2]); exit;
             foreach ($matches[2] as $_m) {
                 if ($search_prefix) {
                     $_m = preg_replace('/\\b' . $search_prefix . '/u', '', $_m);
                 }
                 $_m_low = mb_strtolower($_m, 'UTF-8');
                 $words_found[$_m_low] = 1;
             }
         }
     }
     //print_r($words_found); exit;
     // Pagination not appropriate when using autocomplete ...
     $options = array();
     $options['Total'] = count($words_found);
     // Create responce and JSON encode it
     $options['Matches'] = array();
     $n = 0;
     foreach ($words_found as $_w => $i) {
         if (!$search_prefix) {
             if (mb_strlen($_w) < $min_word_len) {
                 continue;
             }
             // word too short
             if ($this->isStopWord($_w, $tbl)) {
                 continue;
             }
             // stopword or too common
         }
         $options['Matches'][] = array('text' => $complete_words . ($complete_words ? ' ' : '') . $_w, 'id' => $complete_words . ($complete_words ? ' ' : '') . $_w);
         $n++;
         if ($n >= $pageSize) {
             break;
         }
     }
     echo json_encode($options);
     jexit();
 }
 /**
  * Method to fetch the subcategories
  *
  * @access private
  * @return object
  */
 function _getsubs($id)
 {
     $params = $this->_params;
     $use_tmp = true;
     $user = JFactory::getUser();
     $db = JFactory::getDBO();
     $cat_orderby = $this->_buildCatOrderBy('subcat_');
     // Date-Times are stored as UTC, we should use current UTC time to compare and not user time (requestTime),
     // thus the items are published globally at the time the author specified in his/her local clock
     //$now  = JFactory::getApplication()->requestTime;   // NOT correct behavior it should be UTC (below)
     //$now  = JFactory::getDate()->toSql();              // NOT good if string passed to function that will be cached, because string continuesly different
     $_nowDate = 'UTC_TIMESTAMP()';
     //$db->Quote($now);
     $nullDate = $db->getNullDate();
     // Get some parameters and other info
     $catlang = $params->get('language', '');
     // Category language (currently UNUSED)
     $lang = flexicontent_html::getUserCurrentLang();
     // Get user current language
     $filtercat = $params->get('filtercat', 0);
     // Filter items using currently selected language
     $show_noauth = $params->get('show_noauth', 0);
     // Show unauthorized items
     // Build where clause
     $sub_where = ' WHERE cc.published = 1';
     $sub_where .= ' AND c.id = cc.id';
     // Filter the category view with the current user language
     if ($filtercat) {
         $lta = $use_tmp ? 'i' : 'ie';
         $sub_where .= ' AND ( ' . $lta . '.language LIKE ' . $db->Quote($lang . '%') . ' OR ' . $lta . '.language="*" ) ';
     }
     // Get privilege to view non viewable items (upublished, archived, trashed, expired, scheduled).
     // NOTE:  ACL view level is checked at a different place
     $ignoreState = $user->authorise('flexicontent.ignoreviewstate', 'com_flexicontent');
     if (!$ignoreState) {
         // Limit by publication state. Exception: when displaying personal user items or items modified by the user
         $sub_where .= ' AND ( i.state IN (1, -5) OR ( i.created_by = ' . $user->id . ' AND i.created_by != 0 ) )';
         //.' OR ( i.modified_by = '.$user->id.' AND i.modified_by != 0 ) )';
         // Limit by publish up/down dates. Exception: when displaying personal user items or items modified by the user
         $sub_where .= ' AND ( ( i.publish_up = ' . $db->Quote($nullDate) . ' OR i.publish_up <= ' . $_nowDate . ' ) OR ( i.created_by = ' . $user->id . ' AND i.created_by != 0 ) )';
         //.' OR ( i.modified_by = '.$user->id.' AND i.modified_by != 0 ) )';
         $sub_where .= ' AND ( ( i.publish_down = ' . $db->Quote($nullDate) . ' OR i.publish_down >= ' . $_nowDate . ' ) OR ( i.created_by = ' . $user->id . ' AND i.created_by != 0 ) )';
         //.' OR ( i.modified_by = '.$user->id.' AND i.modified_by != 0 ) )';
     }
     // Select only items that user has view access, checking item, category, content type access level
     $and = $asscat_and = '';
     if (!$show_noauth) {
         $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
         $aid_list = implode(",", $aid_arr);
         $sub_where .= ' AND ty.access IN (0,' . $aid_list . ')';
         $sub_where .= ' AND cc.access IN (0,' . $aid_list . ')';
         $sub_where .= ' AND  i.access IN (0,' . $aid_list . ')';
         $and .= ' AND  c.access IN (0,' . $aid_list . ')';
         $asscat_and .= ' AND sc.access IN (0,' . $aid_list . ')';
     }
     $query = 'SELECT c.*,' . ' CASE WHEN CHAR_LENGTH( c.alias ) THEN CONCAT_WS( \':\', c.id, c.alias ) ELSE c.id END AS slug,' . ' (' . ' SELECT COUNT( DISTINCT rel.itemid )' . ' FROM #__flexicontent_cats_item_relations AS rel' . (!$use_tmp ? ' JOIN #__content AS i ON rel.itemid = i.id' : ' JOIN #__flexicontent_items_tmp AS i ON rel.itemid = i.id') . (!$use_tmp ? ' JOIN #__flexicontent_items_ext AS ie ON rel.itemid = ie.item_id' : '') . ' JOIN #__flexicontent_types AS ty ON ' . (!$use_tmp ? 'ie' : 'i') . '.type_id = ty.id' . ' JOIN #__categories AS cc ON cc.id = rel.catid' . $sub_where . ' ) AS assignedsubitems,' . ' (' . ' SELECT COUNT( sc.id )' . ' FROM #__categories AS sc' . ' WHERE c.id = sc.parent_id' . ' AND sc.published = 1' . $asscat_and . ' ) AS assignedcats' . ' FROM #__categories AS c' . ' WHERE c.published = 1' . (!FLEXI_J16GE ? ' AND c.section = ' . FLEXI_SECTION : ' AND c.extension="' . FLEXI_CAT_EXTENSION . '" ') . ' AND c.parent_id = ' . (int) $id . $and . $cat_orderby;
     $this->_db->setQuery($query);
     $this->_subs = $this->_db->loadObjectList();
     return $this->_subs;
 }
}
$app = JFactory::getApplication();
$caching = $app->getCfg('caching');
$show_alpha = $this->params->get('show_alpha', 1);
if ($show_alpha == 1) {
    // Language Default
    $alphacharacters = JTEXT::_("FLEXI_ALPHA_INDEX_CHARACTERS");
    $groups = explode("!!", $alphacharacters);
    $groupcssclasses = explode("!!", JTEXT::_("FLEXI_ALPHA_INDEX_CSSCLASSES"));
    $alphaaliases = explode("!!", JTEXT::_("FLEXI_ALPHA_INDEX_ALIASES"));
} else {
    // $show_alpha == 2
    // Custom setting
    $alphacharacters = $this->params->get('alphacharacters', "[default]=a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,y,z!!0,1,2,3,4,5,6,7,8,9");
    // Get a 2 character language tag
    $lang = flexicontent_html::getUserCurrentLang();
    // a. Try to get for current language
    $result = preg_match("/(\\[{$lang}\\])=([^[]+)/i", $alphacharacters, $matches);
    if ($result) {
        $custom_lang_alpha_index = $matches[2];
    } else {
        // b. Try to get default for all languages
        $result = preg_match("/(\\[default\\])=([^[]+)/i", $alphacharacters, $matches);
        if ($result) {
            $custom_lang_alpha_index = $matches[2];
        } else {
            // c. Use default language string from language file
            $custom_lang_alpha_index = JTEXT::_("FLEXI_ALPHA_INDEX_CHARACTERS");
        }
    }
    $groups = explode("!!", $custom_lang_alpha_index);
Example #11
0
 /**
  * Method to fetch the subcategories
  *
  * @access private
  * @return object
  */
 function _getsubs($id)
 {
     $params = $this->_params;
     $user = JFactory::getUser();
     $db = JFactory::getDBO();
     $orderby = $this->_buildCatOrderBy('subcat_');
     // Get a 2 character language tag
     $lang = flexicontent_html::getUserCurrentLang();
     // Do we filter the categories
     $filtercat = $params->get('filtercat', 0);
     // show unauthorized items
     $show_noauth = $params->get('show_noauth', 0);
     // Build where clause
     $where = ' WHERE cc.published = 1';
     $where .= ' AND c.id = cc.id';
     // Filter the category view with the active active language
     if ((FLEXI_FISH || FLEXI_J16GE) && $filtercat) {
         $lta = FLEXI_J16GE ? 'i' : 'ie';
         $where .= ' AND ( ' . $lta . '.language LIKE ' . $db->Quote($lang . '%') . (FLEXI_J16GE ? ' OR ' . $lta . '.language="*" ' : '') . ' ) ';
     }
     $states = (int) $user->get('gid') > 19 ? '1, -5, 0, -3, -4' : '1, -5';
     $where .= ' AND i.state IN (' . $states . ')';
     // Select only items that user has view access, if listing of unauthorized content is not enabled
     $subjoin = $suband = $join = $and = '';
     if (!$show_noauth) {
         if (FLEXI_J16GE) {
             $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
             $aid_list = implode(",", $aid_arr);
             $suband .= ' AND ty.access IN (0,' . $aid_list . ')';
             $suband .= ' AND cc.access IN (0,' . $aid_list . ')';
             $suband .= ' AND i.access IN (0,' . $aid_list . ')';
             $and .= ' AND c.access IN (0,' . $aid_list . ')';
         } else {
             $aid = (int) $user->get('aid');
             if (FLEXI_ACCESS) {
                 $subjoin .= ' LEFT JOIN #__flexiaccess_acl AS sgt ON ty.id = sgt.axo AND sgt.aco = "read" AND sgt.axosection = "type"';
                 $subjoin .= ' LEFT JOIN #__flexiaccess_acl AS sgc ON cc.id = sgc.axo AND sgc.aco = "read" AND sgc.axosection = "category"';
                 $subjoin .= ' LEFT JOIN #__flexiaccess_acl AS sgi ON i.id = sgi.axo AND sgi.aco = "read" AND sgi.axosection = "item"';
                 $suband .= ' AND (sgt.aro IN ( ' . $user->gmid . ' ) OR ty.access <= ' . $aid . ')';
                 $suband .= ' AND (sgc.aro IN ( ' . $user->gmid . ' ) OR cc.access <= ' . $aid . ')';
                 $suband .= ' AND (sgi.aro IN ( ' . $user->gmid . ' ) OR i.access <= ' . $aid . ')';
                 $join .= ' LEFT JOIN #__flexiaccess_acl AS gc ON c.id = gc.axo AND gc.aco = "read" AND gc.axosection = "category"';
                 $and .= ' AND (gc.aro IN ( ' . $user->gmid . ' ) OR c.access <= ' . $aid . ')';
             } else {
                 $suband .= ' AND ty.access <= ' . $aid;
                 $suband .= ' AND cc.access <= ' . $aid;
                 $suband .= ' AND i.access <= ' . $aid;
                 $and .= ' AND c.access <= ' . $aid;
             }
         }
     }
     $query = 'SELECT c.*,' . ' CASE WHEN CHAR_LENGTH( c.alias ) THEN CONCAT_WS( \':\', c.id, c.alias ) ELSE c.id END AS slug,' . ' (' . ' SELECT COUNT( DISTINCT i.id )' . ' FROM #__content AS i' . ' JOIN #__flexicontent_cats_item_relations AS rel ON rel.itemid = i.id' . ' JOIN #__flexicontent_items_ext AS ie ON ie.item_id = i.id' . ' JOIN #__flexicontent_types AS ty ON ie.type_id = ty.id' . ' JOIN #__categories AS cc ON cc.id = rel.catid' . $subjoin . $where . $suband . ' ) AS assignedsubitems,' . ' (' . ' SELECT COUNT( sc.id )' . ' FROM #__categories AS sc' . ' WHERE c.id = sc.parent_id' . ' AND sc.published = 1' . ' ) AS assignedcats' . ' FROM #__categories AS c' . $join . ' WHERE c.published = 1' . (!FLEXI_J16GE ? ' AND c.section = ' . FLEXI_SECTION : ' AND c.extension="' . FLEXI_CAT_EXTENSION . '" ') . ' AND c.parent_id = ' . (int) $id . $and . $orderby;
     $this->_db->setQuery($query);
     $this->_subs = $this->_db->loadObjectList();
     return $this->_subs;
 }