예제 #1
0
 /**
  * Check in a record
  *
  * @since	1.5
  */
 function checkin()
 {
     $tbl = 'flexicontent_categories';
     $redirect_url = 'index.php?option=com_flexicontent&view=categories';
     flexicontent_db::checkin($tbl, $redirect_url, $this);
     return;
     // true;
 }
	/**
	 * Build the order clause of item listings
	 * precedence: $request_var ==> $order ==> $config_param ==> $default_order_col (& $default_order_dir)
	 * @access private
	 * @return string
	 */
	static function buildItemOrderBy(&$params=null, &$order='', $request_var='orderby', $config_param='orderby', $i_as='i', $rel_as='rel', $default_order_col_1st='', $default_order_dir_1st='', $sfx='', $support_2nd_lvl=false)
	{
		// Use global params ordering if parameters were not given
		if (!$params) $params = JComponentHelper::getParams( 'com_flexicontent' );
		
		$order_fallback = 'rdate';  // Use as default or when an invalid ordering is requested
		$orderbycustomfield   = (int) $params->get('orderbycustomfield'.$sfx, 1);    // Backwards compatibility, defaults to enabled *
		$orderbycustomfieldid = (int) $params->get('orderbycustomfieldid'.$sfx, 0);  // * but this needs to be set in order for field ordering to be used
		
		// 1. If a FORCED -ORDER- is not given, then use ordering parameters from configuration. NOTE: custom field ordering takes priority
		if (!$order) {
			$order = ($orderbycustomfield && $orderbycustomfieldid)  ?  'field'  :  $params->get($config_param.$sfx, $order_fallback);
		}
		
		// 2. If allowing user ordering override, then get ordering from HTTP request variable
		$order = $params->get('orderby_override') && ($request_order = JRequest::getVar($request_var.$sfx)) ? $request_order : $order;
		
		// 3. Check various cases of invalid order, print warning, and reset ordering to default
		if ($order=='field' && !$orderbycustomfieldid ) {
			// This can occur only if field ordering was requested explicitly, otherwise an not set 'orderbycustomfieldid' will prevent 'field' ordering
			echo "Custom field ordering was selected, but no custom field is selected to be used for ordering<br/>";
			$order = $order_fallback;
		}
		if ($order=='commented') {
			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";
				$order = $order_fallback;
			} 
		}
		
		$order_col_1st = $default_order_col_1st;
		$order_dir_1st = $default_order_dir_1st;
		flexicontent_db::_getOrderByClause($params, $order, $i_as, $rel_as, $order_col_1st, $order_dir_1st, $sfx);
		$order_arr[1] = $order;
		$orderby = ' ORDER BY '.$order_col_1st.' '.$order_dir_1st;
		
		
		// ****************************************************************
		// 2nd level ordering, (currently only supported when no SFX given)
		// ****************************************************************
		
		if ($sfx!='' || !$support_2nd_lvl) {
			$orderby .= $order_col_1st != $i_as.'.title'  ?  ', '.$i_as.'.title'  :  '';
			$order_arr[2] = '';
			$order = $order_arr;
			return $orderby;
		}
		
		$order = '';  // Clear this, thus force retrieval from parameters (below)
		$sfx='_2nd';  // Set suffix of second level ordering
		$order_fallback = 'alpha';  // Use as default or when an invalid ordering is requested
		$orderbycustomfield   = (int) $params->get('orderbycustomfield'.$sfx, 1);    // Backwards compatibility, defaults to enabled *
		$orderbycustomfieldid = (int) $params->get('orderbycustomfieldid'.$sfx, 0);  // * but this needs to be set in order for field ordering to be used
		
		// 1. If a FORCED -ORDER- is not given, then use ordering parameters from configuration. NOTE: custom field ordering takes priority
		if (!$order) {
			$order = ($orderbycustomfield && $orderbycustomfieldid)  ?  'field'  :  $params->get($config_param.$sfx, $order_fallback);
		}
		
		// 2. If allowing user ordering override, then get ordering from HTTP request variable
		$order = $request_var && ($request_order = JRequest::getVar($request_var.$sfx)) ? $request_order : $order;
		
		// 3. Check various cases of invalid order, print warning, and reset ordering to default
		if ($order=='field' && !$orderbycustomfieldid ) {
			// This can occur only if field ordering was requested explicitly, otherwise an not set 'orderbycustomfieldid' will prevent 'field' ordering
			echo "Custom field ordering was selected, but no custom field is selected to be used for ordering<br/>";
			$order = $order_fallback;
		}
		if ($order=='commented') {
			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";
				$order = $order_fallback;
			} 
		}
		
		$order_col_2nd = '';
		$order_dir_2nd = '';
		if ($order!='default') {
			flexicontent_db::_getOrderByClause($params, $order, $i_as, $rel_as, $order_col_2nd, $order_dir_2nd, $sfx);
			$order_arr[2] = $order;
			$orderby .= ', '.$order_col_2nd.' '.$order_dir_2nd;
		}
		
		// Order by title after default ordering
		$orderby .= ($order_col_1st != $i_as.'.title' && $order_col_2nd != $i_as.'.title')  ?  ', '.$i_as.'.title'  :  '';
		$order = $order_arr;
		return $orderby;
	}
예제 #3
0
 /**
  * Method to add a favourite
  *
  * @access	public
  * @return	boolean	True on success
  * @since	1.0
  */
 function addfav()
 {
     return flexicontent_db::addfav($type = 1, $this->_id, JFactory::getUser()->id);
 }
예제 #4
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 FAVOURED items
     $where = ' WHERE fav.userid = ' . (int) $user->get('id');
     // Get privilege to view non viewable items (upublished, archived, trashed, expired, scheduled).
     // NOTE:  ACL view level is checked at a different place
     if (FLEXI_J16GE) {
         $ignoreState = $user->authorise('flexicontent.ignoreviewstate', 'com_flexicontent');
     } else {
         if (FLEXI_ACCESS) {
             $ignoreState = $user->gid < 25 ? FAccess::checkComponentAccess('com_flexicontent', 'ignoreviewstate', 'users', $user->gmid) : 1;
         } else {
             $ignoreState = $user->gid > 19;
         }
     }
     // author has 19 and editor has 20
     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 = FLEXI_J16GE ? $db->escape($text, true) : $db->getEscaped($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 = FLEXI_J16GE ? $db->escape($newtext, true) : $db->getEscaped($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 = FLEXI_J16GE ? $db->escape($newtext, true) : $db->getEscaped($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 = FLEXI_J16GE ? $db->escape($newtext, true) : $db->getEscaped($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;
 }
예제 #5
0
foreach ($this->tmpls as $tmpl) {
	$layouts[] = $tmpl->name;
}
$layouts = implode("','", $layouts);

$this->document->addScriptDeclaration("
	window.addEvent('domready', function() {
		activatePanel('blog');
	});
	");
dump($this->row);
*/
?>

<?php 
$useAssocs = flexicontent_db::useAssociations();
// Load JS tabber lib
$this->document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/tabber-minimized.js', FLEXI_VERSION);
$this->document->addStyleSheetVersion(JURI::root(true) . '/components/com_flexicontent/assets/css/tabber.css', FLEXI_VERSION);
$this->document->addScriptDeclaration(' document.write(\'<style type="text/css">.fctabber{display:none;}<\\/style>\'); ');
// temporarily hide the tabbers until javascript runs
$js = "\n\tjQuery(document).ready(function(){\n\t\tfc_bindFormDependencies('#flexicontent', 0, '');\n\t});\n";
?>

<style>
.current:after{
	clear: both;
	content: "";
	display: block;
}
</style>
예제 #6
0
    function display($tpl = null)
    {
        //initialise variables
        $app = JFactory::getApplication();
        $option = JRequest::getVar('option');
        $document = JFactory::getDocument();
        $cparams = JComponentHelper::getParams('com_flexicontent');
        $user = JFactory::getUser();
        //add css to document
        $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontentbackend.css', FLEXI_VHASH);
        $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/j3x.css', FLEXI_VHASH);
        // Add JS frameworks
        flexicontent_html::loadFramework('select2');
        // Add js function to overload the joomla submitform validation
        JHTML::_('behavior.formvalidation');
        // load default validation JS to make sure it is overriden
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/admin.js', FLEXI_VHASH);
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/validate.js', FLEXI_VHASH);
        //Load pane behavior
        jimport('joomla.html.pane');
        //Import File system
        jimport('joomla.filesystem.file');
        //Get data from the model
        $model = $this->getModel();
        $row = $this->get('Field');
        $form = $this->get('Form');
        $types = $this->get('Typeslist');
        $typesselected = $this->get('Typesselected');
        //create the toolbar
        if ($row->id) {
            JToolBarHelper::title(JText::_('FLEXI_EDIT_FIELD'), 'fieldedit');
        } else {
            JToolBarHelper::title(JText::_('FLEXI_ADD_FIELD'), 'fieldadd');
        }
        $ctrl = FLEXI_J16GE ? 'fields.' : '';
        JToolBarHelper::apply($ctrl . 'apply');
        JToolBarHelper::save($ctrl . 'save');
        JToolBarHelper::custom($ctrl . 'saveandnew', 'savenew.png', 'savenew.png', 'FLEXI_SAVE_AND_NEW', false);
        JToolBarHelper::cancel($ctrl . 'cancel');
        // Import Joomla plugin that implements the type of current flexi field
        $extfolder = 'flexicontent_fields';
        $extname = $row->iscore ? 'core' : $row->field_type;
        JPluginHelper::importPlugin('flexicontent_fields', $row->iscore ? 'core' : $row->field_type);
        // Create class name of the plugin and then create a plugin instance
        $classname = 'plg' . ucfirst($extfolder) . $extname;
        // Check max allowed version
        if (property_exists($classname, 'prior_to_version')) {
            // Set a system message with warning of failed PHP limits
            $prior_to_version = $app->getUserStateFromRequest($option . '.flexicontent.prior_to_version_' . $row->field_type, 'prior_to_version_' . $row->field_type, 0, 'int');
            $app->setUserState($option . '.flexicontent.prior_to_version_' . $row->field_type, $prior_to_version + 1);
            if ($prior_to_version < 2) {
                $close_btn = FLEXI_J30GE ? '<a class="close" data-dismiss="alert">&#215;</a>' : '<a class="fc-close" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">&#215;</a>';
                $manifest_path = JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_flexicontent' . DS . 'manifest.xml';
                $com_xml = JApplicationHelper::parseXMLInstallFile($manifest_path);
                $ver_exceeded = version_compare(str_replace(' ', '.', $com_xml['version']), str_replace(' ', '.', $classname::$prior_to_version), '>=');
                if ($ver_exceeded) {
                    echo '
					<span class="fc-note fc-mssg-inline">
						' . $close_btn . '
						Warning: installed version of Field: \'<b>' . $extname . '</b>\' was given to be free for FLEXIcontent versions prior to: v' . $classname::$prior_to_version . ' <br/> It may or may not work properly in later versions
					</span>';
                } else {
                    echo '
					<span class="fc-info fc-mssg-inline">
						' . $close_btn . '
						Note: installed version of Field: \'<b>' . $extname . '</b>\' is given free for FLEXIcontent versions prior to: v' . $classname::$prior_to_version . ', &nbsp; &nbsp; nevertheless it will continue to function after FLEXIcontent is upgraded.
					</span>';
                }
            }
        }
        // load plugin's english language file then override with current language file
        $extension_name = 'plg_flexicontent_fields_' . ($row->iscore ? 'core' : $row->field_type);
        JFactory::getLanguage()->load($extension_name, JPATH_ADMINISTRATOR, 'en-GB', true);
        JFactory::getLanguage()->load($extension_name, JPATH_ADMINISTRATOR, null, true);
        //check which properties are supported by current field
        $ft_support = FlexicontentFields::getPropertySupport($row->field_type, $row->iscore);
        $supportsearch = $ft_support->supportsearch;
        $supportadvsearch = $ft_support->supportadvsearch;
        $supportfilter = $ft_support->supportfilter;
        $supportadvfilter = $ft_support->supportadvfilter;
        $supportuntranslatable = $ft_support->supportuntranslatable;
        $supportvalueseditable = $ft_support->supportvalueseditable;
        $supportformhidden = $ft_support->supportformhidden;
        $supportedithelp = $ft_support->supportedithelp;
        //build selectlists, (for J1.6+ most of these are defined via XML file and custom form field classes)
        $lists = array();
        //build field_type list
        if (!$row->field_type) {
            $row->field_type = 'text';
        }
        $_attribs = ' class="use_select2_lib fc_skip_highlight" ';
        if ($row->iscore == 1) {
            $_attribs .= ' disabled="disabled" ';
        } else {
            $_field_id = 'jform_field_type';
            $_row_id = $form->getValue("id");
            $_ctrl_task = 'task=fields.getfieldspecificproperties';
            $document->addScriptDeclaration("\n\t\t\t\tjQuery(document).ready(function() {\n\t\t\t\t\tjQuery('#" . $_field_id . "').on('change', function() {\n\t\t\t\t\t\tjQuery('#fieldspecificproperties').html('<p class=\"centerimg\"><img src=\"components/com_flexicontent/assets/images/ajax-loader.gif\" align=\"center\"></p>');\n\t\t\t\t\t\tjQuery.ajax({\n\t\t\t\t\t\t\ttype: \"GET\",\n\t\t\t\t\t\t\turl: 'index.php?option=com_flexicontent&" . $_ctrl_task . "&cid=" . $_row_id . "&field_type='+this.value+'&format=raw',\n\t\t\t\t\t\t\tsuccess: function(str) {\n\t\t\t\t\t\t\t\tjQuery('#fieldspecificproperties').html(str);\n\t\t\t\t\t\t\t\t" . (FLEXI_J30GE ? "\n\t\t\t\t\t\t\t\t\tjQuery('.hasTooltip').tooltip({'html': true,'container': jQuery('#fieldspecificproperties')});\n\t\t\t\t\t\t\t\t" : "\n\t\t\t\t\t\t\t\tvar tipped_elements = jQuery('#fieldspecificproperties .hasTip');\n\t\t\t\t\t\t\t\ttipped_elements.each(function() {\n\t\t\t\t\t\t\t\t\tvar title = this.get('title');\n\t\t\t\t\t\t\t\t\tif (title) {\n\t\t\t\t\t\t\t\t\t\tvar parts = title.split('::', 2);\n\t\t\t\t\t\t\t\t\t\tthis.store('tip:title', parts[0]);\n\t\t\t\t\t\t\t\t\t\tthis.store('tip:text', parts[1]);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tvar ajax_JTooltips = new Tips(\$('fieldspecificproperties').getElements('.hasTip'), { maxTitleChars: 50, fixed: false});\n\t\t\t\t\t\t\t\t") . "\n\t\t\t\t\t\t\t\ttabberAutomatic(tabberOptions, 'fieldspecificproperties');\n\t\t\t\t\t\t\t\tfc_bindFormDependencies('#fieldspecificproperties', 0, '');\n\t\t\t\t\t\t\t\tjQuery('#field_typename').html(jQuery('#" . $_field_id . "').val());\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});\n\t\t\t");
        }
        //build field select list
        $fieldtypes = flexicontent_db::getFieldTypes($_grouped = true, $_usage = false, $_published = true);
        $fftypes = array();
        foreach ($fieldtypes as $field_group => $ft_types) {
            $fftypes[] = $field_group;
            foreach ($ft_types as $field_type => $ftdata) {
                $fftypes[] = array('value' => $ftdata->field_type, 'text' => $ftdata->friendly);
            }
            $fftypes[] = '';
        }
        $lists['field_type'] = flexicontent_html::buildfieldtypeslist($fftypes, 'jform[field_type]', $row->field_type, $_grouped ? 1 : 0, $_attribs);
        //build type select list
        $attribs = 'class="use_select2_lib" multiple="multiple" size="6"';
        $attribs .= $row->iscore ? ' disabled="disabled"' : '';
        $types_fieldname = FLEXI_J16GE ? 'jform[tid][]' : 'tid[]';
        $lists['tid'] = flexicontent_html::buildtypesselect($types, $types_fieldname, $typesselected, false, $attribs);
        // **************************************************************************
        // Create fields for J1.5 (J2.5+ uses JForm XML file for most of form fields)
        // **************************************************************************
        if (!FLEXI_J16GE) {
            //build formhidden selector
            $formhidden[] = JHTML::_('select.option', 0, JText::_('FLEXI_NO'));
            $formhidden[] = JHTML::_('select.option', 1, JText::_('FLEXI_FRONTEND'));
            $formhidden[] = JHTML::_('select.option', 2, JText::_('FLEXI_BACKEND'));
            $formhidden[] = JHTML::_('select.option', 3, JText::_('FLEXI_BOTH'));
            $formhidden_fieldname = FLEXI_J16GE ? 'jform[formhidden]' : 'formhidden';
            $lists['formhidden'] = JHTML::_('select.radiolist', $formhidden, $formhidden_fieldname, '', 'value', 'text', $row->formhidden);
            if (FLEXI_ACCESS) {
                $valueseditable[] = JHTML::_('select.option', 0, JText::_('FLEXI_ANY_EDITOR'));
                $valueseditable[] = JHTML::_('select.option', 1, JText::_('FLEXI_USE_ACL_PERMISSION'));
                $valueseditable_fieldname = FLEXI_J16GE ? 'jform[valueseditable]' : 'valueseditable';
                $lists['valueseditable'] = JHTML::_('select.radiolist', $valueseditable, $valueseditable_fieldname, '', 'value', 'text', $row->valueseditable);
            }
            $edithelp[] = JHTML::_('select.option', 0, JText::_('FLEXI_EDIT_HELP_NONE'));
            $edithelp[] = JHTML::_('select.option', 1, JText::_('FLEXI_EDIT_HELP_LABEL_TOOLTIP'));
            $edithelp[] = JHTML::_('select.option', 2, JText::_('FLEXI_EDIT_HELP_LABEL_TOOLTIP_WICON'));
            $edithelp[] = JHTML::_('select.option', 3, JText::_('FLEXI_EDIT_HELP_INLINE'));
            $edithelp_fieldname = FLEXI_J16GE ? 'jform[edithelp]' : 'edithelp';
            $lists['edithelp'] = JHTML::_('select.radiolist', $edithelp, $edithelp_fieldname, '', 'value', 'text', $row->edithelp);
            // build the html select list for ordering
            $query = 'SELECT ordering AS value, label AS text' . ' FROM #__flexicontent_fields' . ' WHERE published >= 0' . ' ORDER BY ordering';
            $row->ordering = @$row->ordering;
            $lists['ordering'] = $row->id ? JHTML::_('list.specificordering', $row, $row->id, $query) : JHTML::_('list.specificordering', $row, '', $query);
            //build access level list
            if (FLEXI_ACCESS) {
                $lang = JFactory::getLanguage();
                $lang->_strings['FLEXIACCESS_PADD'] = 'Edit-Value';
                $lists['access'] = FAccess::TabGmaccess($row, 'field', 1, 1, 0, 1, 0, 1, 0, 1, 1);
            } else {
                $lists['access'] = JHTML::_('list.accesslevel', $row);
            }
        }
        if (!FLEXI_J16GE) {
            // Create the parameter 's form object parsing the file XML
            $pluginpath = JPATH_PLUGINS . DS . 'flexicontent_fields' . DS . $row->field_type . '.xml';
            if (JFile::exists($pluginpath)) {
                $form = new JParameter('', $pluginpath);
            } else {
                $form = new JParameter('', JPATH_PLUGINS . DS . 'flexicontent_fields' . DS . 'core.xml');
            }
            // Special and Core Groups
            $form->loadINI($row->attribs);
        }
        // fail if checked out not by 'me'
        if ($row->id) {
            if ($model->isCheckedOut($user->get('id'))) {
                JError::raiseWarning('SOME_ERROR_CODE', $row->name . ' ' . JText::_('FLEXI_EDITED_BY_ANOTHER_ADMIN'));
                $app->redirect('index.php?option=com_flexicontent&view=fields');
            }
        }
        //clean data
        JFilterOutput::objectHTMLSafe($row, ENT_QUOTES);
        // assign permissions for J2.5
        $permission = FlexicontentHelperPerm::getPerm();
        $this->assignRef('permission', $permission);
        //assign data to template
        $this->assignRef('document', $document);
        $this->assignRef('row', $row);
        $this->assignRef('lists', $lists);
        $this->assignRef('form', $form);
        $this->assignRef('typesselected', $typesselected);
        $this->assignRef('supportsearch', $supportsearch);
        $this->assignRef('supportadvsearch', $supportadvsearch);
        $this->assignRef('supportfilter', $supportfilter);
        $this->assignRef('supportadvfilter', $supportadvfilter);
        $this->assignRef('supportuntranslatable', $supportuntranslatable);
        $this->assignRef('supportvalueseditable', $supportvalueseditable);
        $this->assignRef('supportformhidden', $supportformhidden);
        $this->assignRef('supportedithelp', $supportedithelp);
        parent::display($tpl);
    }
    $fcitems[$i] = JTable::getInstance('flexicontent_items', '');
    $fcitems[$i]->load($result->fc_item_id);
    $fcitems[$i]->category_access = $result->category_access;
    $fcitems[$i]->type_access = $result->type_access;
    $fcitems[$i]->has_access = $result->has_access;
    $fcitems[$i]->categories = $result->categories;
}
// ************************************************************************
// Calculate CSS classes needed to add special styling markups to the items
// ************************************************************************
flexicontent_html::calculateItemMarkups($fcitems, $this->params);
// *********************************************************
// Get Original content ids for creating some untranslatable
// fields that have share data (like shared folders)
// *********************************************************
flexicontent_db::getOriginalContentItemids($fcitems);
// *****************************************************
// Get image configuration for FLEXIcontent result items
// *****************************************************
$fcr_use_image = $this->params->get('fcr_use_image', 1);
$fcr_image = $this->params->get('fcr_image');
if ($fcr_use_image && $fcr_image) {
    $img_size_map = array('l' => 'large', 'm' => 'medium', 's' => 'small');
    $img_field_size = $img_size_map[$this->params->get('fcr_image_size', 'l')];
    $img_field_name = $this->params->get('fcr_image');
}
// *******************************************************************
// Get custom displayed fields to add to each FLEXIcontent result item
// *******************************************************************
$use_infoflds = (int) $this->params->get('use_infoflds', 1);
$infoflds = $this->params->get('infoflds');
예제 #8
0
 function display($tpl = null)
 {
     // ********************
     // Initialise variables
     // ********************
     $app = JFactory::getApplication();
     $jinput = $app->input;
     $option = $jinput->get('option', '', 'cmd');
     $view = $jinput->get('view', '', 'cmd');
     $cparams = JComponentHelper::getParams('com_flexicontent');
     $user = JFactory::getUser();
     $db = JFactory::getDBO();
     $document = JFactory::getDocument();
     // Get model
     $model = $this->getModel();
     $print_logging_info = $cparams->get('print_logging_info');
     if ($print_logging_info) {
         global $fc_run_times;
     }
     // ***********
     // Get filters
     // ***********
     $count_filters = 0;
     // various filters
     $filter_fieldtype = $model->getState('filter_fieldtype');
     $filter_assigned = $model->getState('filter_assigned');
     $filter_type = $model->getState('filter_type');
     $filter_state = $model->getState('filter_state');
     $filter_access = $model->getState('filter_access');
     if ($filter_assigned) {
         $count_filters++;
     }
     if ($filter_fieldtype) {
         $count_filters++;
     }
     if ($filter_state) {
         $count_filters++;
     }
     if ($filter_access) {
         $count_filters++;
     }
     if ($filter_type) {
         $count_filters++;
     }
     // ordering filters
     $filter_order = $model->getState('filter_order');
     $filter_order_Dir = $model->getState('filter_order_Dir');
     // text search
     $search = $model->getState('search');
     $search = $db->escape(trim(JString::strtolower($search)));
     // ****************************
     // Important usability messages
     // ****************************
     if ($cparams->get('show_usability_messages', 1)) {
         $notice_content_type_order = $app->getUserStateFromRequest($option . '.' . $view . '.notice_content_type_order', 'notice_content_type_order', 0, 'int');
         if (!$notice_content_type_order) {
             $app->setUserState($option . '.' . $view . '.notice_content_type_order', 1);
             $app->enqueueMessage(JText::_('FLEXI_DEFINE_FIELD_ORDER_FILTER_BY_TYPE'), 'message');
             $app->enqueueMessage(JText::_('FLEXI_DEFINE_FIELD_ORDER_FILTER_WITHOUT_TYPE'), 'message');
             $app->enqueueMessage(JText::_('FLEXI_USABILITY_MESSAGES_TURN_OFF'), 'message');
         }
     }
     // **************************
     // Add css and js to document
     // **************************
     flexicontent_html::loadFramework('select2');
     //JHTML::_('behavior.tooltip');
     $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontentbackend.css', FLEXI_VHASH);
     $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/j3x.css', FLEXI_VHASH);
     $js = "jQuery(document).ready(function(){";
     // *****************************
     // Get user's global permissions
     // *****************************
     $perms = FlexicontentHelperPerm::getPerm();
     // ************************
     // Create Submenu & Toolbar
     // ************************
     // Create Submenu (and also check access to current view)
     FLEXISubmenu('CanFields');
     // Create document/toolbar titles
     $doc_title = JText::_('FLEXI_FIELDS');
     $site_title = $document->getTitle();
     JToolBarHelper::title($doc_title, 'fields');
     $document->setTitle($doc_title . ' - ' . $site_title);
     if ($perms->CanEditField) {
         $ctrl_task = '&task=fields.selectsearchflag';
         $popup_load_url = JURI::base() . 'index.php?option=com_flexicontent' . $ctrl_task . '&tmpl=component';
         $btn_name = 'basicindex';
         $btn_task = '';
         $full_js = ';';
         $extra_js = '';
         flexicontent_html::addToolBarButton(JText::_('FLEXI_TOGGLE_SEARCH_FLAG'), $btn_name, $full_js, $msg_alert = JText::_('FLEXI_SELECT_FIELDS_TO_TOGGLE_PROPERTY'), $msg_confirm = '', $btn_task, $extra_js, $btn_list = true, $btn_menu = true, $btn_confirm = false, $btn_class = "");
         $js .= "\n\t\t\t\tjQuery('#toolbar-basicindex a.toolbar, #toolbar-basicindex button')\n\t\t\t\t\t.attr('onclick', 'javascript:;')\n\t\t\t\t\t.attr('href', '" . $popup_load_url . "')\n\t\t\t\t\t.attr('rel', '{handler: \\'iframe\\', size: {x: 800, y: 340}, onClose: function() {}}');\n\t\t\t";
     }
     $contrl = "fields.";
     if ($perms->CanCopyFields) {
         JToolBarHelper::custom($contrl . 'copy', 'copy.png', 'copy_f2.png', 'FLEXI_COPY');
         JToolBarHelper::custom($contrl . 'copy_wvalues', 'copy_wvalues.png', 'copy_f2.png', 'FLEXI_COPY_WITH_VALUES');
         JToolBarHelper::divider();
     }
     JToolBarHelper::publishList($contrl . 'publish');
     JToolBarHelper::unpublishList($contrl . 'unpublish');
     if ($perms->CanAddField) {
         JToolBarHelper::addNew($contrl . 'add');
     }
     if ($perms->CanEditField) {
         JToolBarHelper::editList($contrl . 'edit');
     }
     if ($perms->CanDeleteField) {
         //JToolBarHelper::deleteList(JText::_('FLEXI_ARE_YOU_SURE'), $contrl.'remove');
         // This will work in J2.5+ too and is offers more options (above a little bogus in J1.5, e.g. bad HTML id tag)
         $msg_alert = JText::sprintf('FLEXI_SELECT_LIST_ITEMS_TO', JText::_('FLEXI_DELETE'));
         $msg_confirm = JText::_('FLEXI_ITEMS_DELETE_CONFIRM');
         $btn_task = $contrl . 'remove';
         $extra_js = "";
         flexicontent_html::addToolBarButton('FLEXI_DELETE', 'delete', '', $msg_alert, $msg_confirm, $btn_task, $extra_js, $btn_list = true, $btn_menu = true, $btn_confirm = true);
     }
     JToolbarHelper::checkin($contrl . 'checkin');
     /*
     JToolBarHelper::divider(); JToolBarHelper::spacer();
     $btn_name = 'basicindex';
     $btn_task    = 'fields.toggleprop';
     $extra_js    = "document.getElementById('adminForm').elements['propname'].value='issearch';";
     flexicontent_html::addToolBarButton(
     	'FLEXI_TOGGLE_TEXT_SEARCHABLE', $btn_name, $full_js='', $msg_alert=JText::_('FLEXI_SELECT_FIELDS_TO_TOGGLE_PROPERTY'), $msg_confirm='',
     	$btn_task, $extra_js, $btn_list=true, $btn_menu=true, $btn_confirm=false, $btn_class="btn-info");
     
     $btn_name = 'basicfilter';
     $btn_task    = 'fields.toggleprop';
     $extra_js    = "document.getElementById('adminForm').elements['propname'].value='isfilter';";
     flexicontent_html::addToolBarButton(
     	'FLEXI_TOGGLE_FILTERABLE', $btn_name, $full_js='', $msg_alert=JText::_('FLEXI_SELECT_FIELDS_TO_TOGGLE_PROPERTY'), $msg_confirm='',
     	$btn_task, $extra_js, $btn_list=true, $btn_menu=true, $btn_confirm=false, $btn_class="btn-info");
     
     $btn_name = 'advindex';
     $btn_task    = 'fields.toggleprop';
     $extra_js    = "document.getElementById('adminForm').elements['propname'].value='isadvsearch';";
     flexicontent_html::addToolBarButton(
     	'FLEXI_TOGGLE_ADV_TEXT_SEARCHABLE', $btn_name, $full_js='', $msg_alert=JText::_('FLEXI_SELECT_FIELDS_TO_TOGGLE_PROPERTY'), $msg_confirm='',
     	$btn_task, $extra_js, $btn_list=true, $btn_menu=true, $btn_confirm=false, $btn_class="btn-info");
     
     $btn_name = 'advfilter';
     $btn_task    = 'fields.toggleprop';
     $extra_js    = "document.getElementById('adminForm').elements['propname'].value='isadvfilter';";
     flexicontent_html::addToolBarButton(
     	'FLEXI_TOGGLE_ADV_FILTERABLE', $btn_name, $full_js='', $msg_alert=JText::_('FLEXI_SELECT_FIELDS_TO_TOGGLE_PROPERTY'), $msg_confirm='',
     	$btn_task, $extra_js, $btn_list=true, $btn_menu=true, $btn_confirm=false, $btn_class="btn-info");
     */
     $appsman_path = JPATH_COMPONENT_ADMINISTRATOR . DS . 'views' . DS . 'appsman';
     if (file_exists($appsman_path)) {
         $btn_icon = 'icon-download';
         $btn_name = 'download';
         $btn_task = 'appsman.exportxml';
         $extra_js = " var f=document.getElementById('adminForm'); f.elements['view'].value='appsman'; jQuery('<input>').attr({type: 'hidden', name: 'table', value: 'flexicontent_fields'}).appendTo(jQuery(f));";
         flexicontent_html::addToolBarButton('Export now', $btn_name, $full_js = '', $msg_alert = '', $msg_confirm = 'Export now as XML', $btn_task, $extra_js, $btn_list = false, $btn_menu = true, $btn_confirm = true, $btn_class = "btn-warning", $btn_icon);
         $btn_icon = 'icon-box-add';
         $btn_name = 'box-add';
         $btn_task = 'appsman.addtoexport';
         $extra_js = " var f=document.getElementById('adminForm'); f.elements['view'].value='appsman'; jQuery('<input>').attr({type: 'hidden', name: 'table', value: 'flexicontent_fields'}).appendTo(jQuery(f));";
         flexicontent_html::addToolBarButton('Add to export', $btn_name, $full_js = '', $msg_alert = '', $msg_confirm = 'Add to export list', $btn_task, $extra_js, $btn_list = false, $btn_menu = true, $btn_confirm = true, $btn_class = "btn-warning", $btn_icon);
     }
     /*$btn_icon = 'icon-download';
     		$btn_name = 'download';
     		$btn_task    = 'fields.exportsql';
     		$extra_js    = "";
     		flexicontent_html::addToolBarButton(
     			'Export SQL', $btn_name, $full_js='', $msg_alert='', $msg_confirm='Field\'s configuration will be exported as SQL',
     			$btn_task, $extra_js, $btn_list=false, $btn_menu=true, $btn_confirm=true, $btn_class="btn-warning", $btn_icon);
     		
     		
     		$btn_icon = 'icon-download';
     		$btn_name = 'download';
     		$btn_task    = 'fields.exportcsv';
     		$extra_js    = "";
     		flexicontent_html::addToolBarButton(
     			'Export CSV', $btn_name, $full_js='', $msg_alert='', $msg_confirm='Field\'s configuration will be exported as CSV',
     			$btn_task, $extra_js, $btn_list=false, $btn_menu=true, $btn_confirm=true, $btn_class="btn-warning", $btn_icon);*/
     if ($perms->CanConfig) {
         JToolBarHelper::divider();
         JToolBarHelper::spacer();
         $session = JFactory::getSession();
         $fc_screen_width = (int) $session->get('fc_screen_width', 0, 'flexicontent');
         $_width = $fc_screen_width && $fc_screen_width - 84 > 940 ? $fc_screen_width - 84 > 1400 ? 1400 : $fc_screen_width - 84 : 940;
         $fc_screen_height = (int) $session->get('fc_screen_height', 0, 'flexicontent');
         $_height = $fc_screen_height && $fc_screen_height - 128 > 550 ? $fc_screen_height - 128 > 1000 ? 1000 : $fc_screen_height - 128 : 550;
         JToolBarHelper::preferences('com_flexicontent', $_height, $_width, 'Configuration');
     }
     $js .= "});";
     $document->addScriptDeclaration($js);
     // Get data from the model
     if ($print_logging_info) {
         $start_microtime = microtime(true);
     }
     $rows = $this->get('Items');
     $allrows = $this->get('AllItems');
     if ($print_logging_info) {
         @($fc_run_times['execute_main_query'] += round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
     }
     $pagination = $this->get('Pagination');
     // Pagination
     $types = $this->get('Typeslist');
     // Content types
     $fieldTypes = flexicontent_db::getFieldTypes($_grouped = true, $_usage = true, $_published = false);
     // Field types with content type ASSIGNMENT COUNTING
     $lists = array();
     // build item-type filter
     $lists['filter_type'] = ($filter_type || 1 ? '<label class="label">' . JText::_('FLEXI_TYPE') . '</label>' : '') . flexicontent_html::buildtypesselect($types, 'filter_type', $filter_type, '-', 'class="use_select2_lib" size="1" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', 'filter_type');
     // build orphaned/assigned filter
     $assigned = array();
     $assigned[] = JHTML::_('select.option', '', '-');
     $assigned[] = JHTML::_('select.option', 'O', JText::_('FLEXI_ORPHANED'));
     $assigned[] = JHTML::_('select.option', 'A', JText::_('FLEXI_ASSIGNED'));
     $lists['assigned'] = ($filter_assigned || 1 ? '<label class="label">' . JText::_('FLEXI_ASSIGNED') . '</label>' : '') . JHTML::_('select.genericlist', $assigned, 'filter_assigned', 'class="use_select2_lib" size="1" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', 'value', 'text', $filter_assigned);
     // build field-type filter
     $ALL = mb_strtoupper(JText::_('FLEXI_ALL'), 'UTF-8') . ' : ';
     $fftypes = array();
     $fftypes[] = array('value' => '', 'text' => '-');
     $fftypes[] = array('value' => 'BV', 'text' => $ALL . JText::_('FLEXI_BACKEND_FIELDS'));
     $fftypes[] = array('value' => 'C', 'text' => $ALL . JText::_('FLEXI_CORE_FIELDS'));
     $fftypes[] = array('value' => 'NC', 'text' => $ALL . JText::_('FLEXI_NON_CORE_FIELDS'));
     foreach ($fieldTypes as $field_group => $ft_types) {
         $fftypes[] = $field_group;
         foreach ($ft_types as $field_type => $ftdata) {
             $fftypes[] = array('value' => $ftdata->field_type, 'text' => '-' . $ftdata->assigned . '- ' . $ftdata->friendly);
         }
         $fftypes[] = '';
     }
     $lists['fftype'] = ($filter_fieldtype || 1 ? '<label class="label">' . JText::_('FLEXI_FIELD_TYPE') . '</label>' : '') . flexicontent_html::buildfieldtypeslist($fftypes, 'filter_fieldtype', $filter_fieldtype, $_grouped ? 1 : 0, 'class="use_select2_lib" size="1" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"');
     // build publication state filter
     $states = array();
     $states[] = JHTML::_('select.option', '', '-');
     $states[] = JHTML::_('select.option', 'P', JText::_('FLEXI_PUBLISHED'));
     $states[] = JHTML::_('select.option', 'U', JText::_('FLEXI_UNPUBLISHED'));
     //$states[] = JHTML::_('select.option',  '-2', JText::_( 'FLEXI_TRASHED' ) );
     $lists['state'] = ($filter_state || 1 ? '<label class="label">' . JText::_('FLEXI_STATE') . '</label>' : '') . JHTML::_('select.genericlist', $states, 'filter_state', 'class="use_select2_lib" size="1" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', 'value', 'text', $filter_state);
     //JHTML::_('grid.state', $filter_state );
     // build access level filter
     $options = JHtml::_('access.assetgroups');
     array_unshift($options, JHtml::_('select.option', '', '-'));
     $fieldname = $elementid = 'filter_access';
     $attribs = 'class="use_select2_lib" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"';
     $lists['access'] = ($filter_access || 1 ? '<label class="label">' . JText::_('FLEXI_ACCESS') . '</label>' : '') . JHTML::_('select.genericlist', $options, $fieldname, $attribs, 'value', 'text', $filter_access, $elementid, $translate = true);
     // text search filter
     $lists['search'] = $search;
     // table ordering
     $lists['order_Dir'] = $filter_order_Dir;
     $lists['order'] = $filter_order;
     if ($filter_type == '' || $filter_type == 0) {
         $ordering = $lists['order'] == 't.ordering';
     } else {
         $ordering = $lists['order'] == 'typeordering';
     }
     //assign data to template
     $this->assignRef('count_filters', $count_filters);
     $this->assignRef('permission', $perms);
     $this->assignRef('filter_type', $filter_type);
     $this->assignRef('lists', $lists);
     $this->assignRef('rows', $rows);
     $this->assignRef('allrows', $allrows);
     $this->assignRef('types', $types);
     $this->assignRef('ordering', $ordering);
     $this->assignRef('pagination', $pagination);
     $this->assignRef('option', $option);
     $this->assignRef('view', $view);
     $this->sidebar = FLEXI_J30GE ? JHtmlSidebar::render() : null;
     parent::display($tpl);
 }
예제 #9
0
 /**
  * Method to determine if J3.1+ associations should be used
  *
  * @return  boolean True if using J3 associations; false otherwise.
  */
 public function useAssociations()
 {
     return flexicontent_db::useAssociations();
 }
예제 #10
0
    function display($tpl = null)
    {
        // ***********
        // Batch tasks
        // ***********
        $app = JFactory::getApplication();
        $jinput = $app->input;
        $task = $jinput->get('task', '', 'cmd');
        $cid = $jinput->get('cid', array(), 'array');
        if ($task == 'copy') {
            $behaviour = $jinput->get('copy_behaviour', 'copy/move', 'string');
            $this->setLayout('copy');
            $this->_displayCopyMove($tpl, $cid, $behaviour);
            return;
        }
        // ********************
        // Initialise variables
        // ********************
        global $globalcats;
        $option = $jinput->get('option', '', 'cmd');
        $view = $jinput->get('view', '', 'cmd');
        $cparams = JComponentHelper::getParams('com_flexicontent');
        $user = JFactory::getUser();
        $db = JFactory::getDBO();
        $document = JFactory::getDocument();
        $session = JFactory::getSession();
        $bind_limit = $jinput->get('bind_limit', 1000, 'int');
        // Some flags
        $enable_translation_groups = flexicontent_db::useAssociations();
        //$cparams->get("enable_translation_groups");
        $print_logging_info = $cparams->get('print_logging_info');
        // Get model
        $model = $this->getModel();
        // ***********
        // Get filters
        // ***********
        $count_filters = 0;
        // File id filtering
        $fileid_to_itemids = $session->get('fileid_to_itemids', array(), 'flexicontent');
        $filter_fileid = $model->getState('filter_fileid');
        if ($filter_fileid) {
            $count_filters++;
        }
        // Order type, order, order direction
        $filter_order_type = $model->getState('filter_order_type');
        $filter_order = $model->getState('filter_order');
        $filter_order_Dir = $model->getState('filter_order_Dir');
        // Category filtering
        $filter_cats = $model->getState('filter_cats');
        $filter_subcats = $model->getState('filter_subcats');
        $filter_catsinstate = $model->getState('filter_catsinstate');
        if ($filter_cats) {
            $count_filters++;
        }
        if ($filter_subcats != 1) {
            $count_filters++;
        }
        if ($filter_catsinstate != 1) {
            $count_filters++;
        }
        // Other filters
        $filter_tag = $model->getState('filter_tag');
        $filter_lang = $model->getState('filter_lang');
        $filter_type = $model->getState('filter_type');
        $filter_author = $model->getState('filter_author');
        $filter_state = $model->getState('filter_state');
        $filter_access = $model->getState('filter_access');
        // Support for using 'ALL', 'ORPHAN' fake states, by clearing other values
        if (is_array($filter_state) && in_array('ALL', $filter_state)) {
            $filter_state = array('ALL');
        }
        if (is_array($filter_state) && in_array('ORPHAN', $filter_state)) {
            $filter_state = array('ORPHAN');
        }
        // Count active filters
        if ($filter_tag) {
            $count_filters++;
        }
        if ($filter_lang) {
            $count_filters++;
        }
        if ($filter_type) {
            $count_filters++;
        }
        if ($filter_author) {
            $count_filters++;
        }
        if ($filter_state) {
            $count_filters++;
        }
        if ($filter_access) {
            $count_filters++;
        }
        // Date filters
        $date = $model->getState('date');
        $startdate = $model->getState('startdate');
        $enddate = $model->getState('enddate');
        $startdate = $db->escape(trim(JString::strtolower($startdate)));
        $enddate = $db->escape(trim(JString::strtolower($enddate)));
        if ($startdate) {
            $count_filters++;
        }
        if ($enddate) {
            $count_filters++;
        }
        // Item ID filter
        $filter_id = $model->getState('filter_id');
        if ($filter_id) {
            $count_filters++;
        }
        // Text search
        $scope = $model->getState('scope');
        $search = $model->getState('search');
        $search = $db->escape(trim(JString::strtolower($search)));
        // **************************
        // Add css and js to document
        // **************************
        flexicontent_html::loadFramework('select2');
        JHTML::_('behavior.calendar');
        $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontentbackend.css', FLEXI_VERSION);
        $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/j3x.css', FLEXI_VERSION);
        $js = "jQuery(document).ready(function(){";
        if ($filter_cats) {
            $js .= "jQuery('.col_cats').each(function(){ jQuery(this).addClass('yellow'); });";
        }
        if ($filter_type) {
            $js .= "jQuery('.col_type').each(function(){ jQuery(this).addClass('yellow'); });";
        }
        if ($filter_author) {
            $js .= "jQuery('.col_authors').each(function(){ jQuery(this).addClass('yellow'); });";
        }
        if ($filter_state) {
            $js .= "jQuery('.col_state').each(function(){ jQuery(this).addClass('yellow'); });";
        }
        if ($filter_lang) {
            $js .= "jQuery('.col_lang').each(function(){ jQuery(this).addClass('yellow'); });";
        }
        if ($filter_access) {
            $js .= "jQuery('.col_access').each(function(){ jQuery(this).addClass('yellow'); });";
        }
        if ($filter_tag) {
            $js .= "jQuery('.col_tag').each(function(){ jQuery(this).addClass('yellow'); });";
        }
        if ($filter_id) {
            $js .= "jQuery('.col_id').each(function(){ jQuery(this).addClass('yellow'); });";
        }
        if ($startdate || $enddate) {
            if ($date == 1) {
                $js .= "jQuery('.col_created').each(function(){ jQuery(this).addClass('yellow'); });";
            } else {
                if ($date == 2) {
                    $js .= "jQuery('.col_revised').each(function(){ jQuery(this).addClass('yellow'); });";
                }
            }
        }
        if (strlen($search)) {
            $js .= "jQuery('.col_title').each(function(){ jQuery(this).addClass('yellow'); });";
        }
        // *****************************
        // Get user's global permissions
        // *****************************
        $perms = FlexicontentHelperPerm::getPerm();
        $CanEdit = $perms->CanEdit;
        $CanPublish = $perms->CanPublish;
        $CanDelete = $perms->CanDelete;
        $CanEditOwn = $perms->CanEditOwn;
        $CanPublishOwn = $perms->CanPublishOwn;
        $CanDeleteOwn = $perms->CanDeleteOwn;
        $hasEdit = $CanEdit || $CanEditOwn;
        $hasPublish = $CanPublish || $CanPublishOwn;
        $hasDelete = $CanDelete || $CanDeleteOwn;
        $CanCats = $perms->CanCats;
        $CanAccLvl = $perms->CanAccLvl;
        $CanOrder = $perms->CanOrder;
        $CanCopy = $perms->CanCopy;
        $CanArchives = $perms->CanArchives;
        // Check if user can create in at least one published category
        require_once "components/com_flexicontent/models/item.php";
        $itemmodel = new FlexicontentModelItem();
        $CanAdd = $itemmodel->getItemAccess()->get('access-create');
        // *****************************
        // Get user's global permissions
        // *****************************
        $perms = FlexicontentHelperPerm::getPerm();
        // ************************
        // Create Submenu & Toolbar
        // ************************
        // Create Submenu (and also check access to current view)
        FLEXISubmenu('notvariable');
        // Create document/toolbar titles
        $doc_title = JText::_('FLEXI_ITEMS');
        $site_title = $document->getTitle();
        JToolBarHelper::title($doc_title, 'items');
        $document->setTitle($doc_title . ' - ' . $site_title);
        $toolbar = JToolBar::getInstance('toolbar');
        // Implementation of multiple-item state selector
        $add_divider = false;
        if ($hasPublish) {
            $btn_task = '';
            $ctrl_task = '&task=items.selectstate';
            $popup_load_url = JURI::base() . 'index.php?option=com_flexicontent' . $ctrl_task . '&format=raw';
            if (FLEXI_J30GE || !FLEXI_J16GE) {
                // Layout of Popup button broken in J3.1, add in J1.5 it generates duplicate HTML tag id (... just for validation), so add manually
                $js .= "\n\t\t\t\t\tjQuery('#toolbar-publish a.toolbar, #toolbar-publish button')\n\t\t\t\t\t\t.attr('onclick', 'javascript:;')\n\t\t\t\t\t\t.attr('href', '" . $popup_load_url . "')\n\t\t\t\t\t\t.attr('rel', '{handler: \\'iframe\\', size: {x: 800, y: 240}, onClose: function() {}}');\n\t\t\t\t";
                //JToolBarHelper::publishList( $btn_task );
                JToolBarHelper::custom($btn_task, 'publish.png', 'publish_f2.png', 'FLEXI_CHANGE_STATE', false);
                JHtml::_('behavior.modal', '#toolbar-publish a.toolbar, #toolbar-publish button');
            } else {
                $toolbar->appendButton('Popup', 'publish', JText::_('FLEXI_CHANGE_STATE'), str_replace('&', '&amp;', $popup_load_url), 800, 240);
            }
            $add_divider = true;
        }
        if ($hasDelete) {
            if ($filter_state && in_array('T', $filter_state)) {
                //$btn_msg = JText::_('FLEXI_ARE_YOU_SURE');
                //$btn_task = 'items.remove';
                //JToolBarHelper::deleteList($btn_msg, $btn_task);
                $msg_alert = JText::sprintf('FLEXI_SELECT_LIST_ITEMS_TO', JText::_('FLEXI_DELETE'));
                $msg_confirm = JText::_('FLEXI_ARE_YOU_SURE');
                $btn_task = 'items.remove';
                $extra_js = "";
                flexicontent_html::addToolBarButton('FLEXI_DELETE', 'delete', '', $msg_alert, $msg_confirm, $btn_task, $extra_js, $btn_list = true, $btn_menu = true, $btn_confirm = true, $btn_class = "btn-warning");
            } else {
                $msg_alert = JText::sprintf('FLEXI_SELECT_LIST_ITEMS_TO', JText::_('FLEXI_TRASH'));
                $msg_confirm = JText::_('FLEXI_TRASH_CONFIRM') . ' ' . JText::_('FLEXI_NOTES') . ': ' . JText::_('FLEXI_DELETE_PERMANENTLY');
                $btn_task = 'items.changestate';
                $extra_js = "document.adminForm.newstate.value='T';";
                flexicontent_html::addToolBarButton('FLEXI_TRASH', 'trash', '', $msg_alert, $msg_confirm, $btn_task, $extra_js, $btn_list = true, $btn_menu = true, $btn_confirm = true, $btn_class = "");
            }
            $add_divider = true;
        }
        if ($CanArchives && (!$filter_state || !in_array('A', $filter_state))) {
            $msg_alert = JText::sprintf('FLEXI_SELECT_LIST_ITEMS_TO', JText::_('FLEXI_ARCHIVE'));
            $msg_confirm = JText::_('FLEXI_ARCHIVE_CONFIRM');
            $btn_task = 'items.changestate';
            $extra_js = "document.adminForm.newstate.value='A';";
            flexicontent_html::addToolBarButton('FLEXI_ARCHIVE', 'archive', $full_js = '', $msg_alert, $msg_confirm, $btn_task, $extra_js, $btn_list = true, $btn_menu = true, $btn_confirm = true);
            $add_divider = true;
        }
        if ($CanArchives && $filter_state && in_array('A', $filter_state) || $hasDelete && $filter_state && in_array('T', $filter_state)) {
            $msg_alert = JText::sprintf('FLEXI_SELECT_LIST_ITEMS_TO', JText::_('FLEXI_RESTORE'));
            $msg_confirm = JText::_('FLEXI_RESTORE_CONFIRM');
            $btn_task = 'items.changestate';
            $extra_js = "document.adminForm.newstate.value='P';";
            flexicontent_html::addToolBarButton('FLEXI_RESTORE', 'restore', $full_js = '', $msg_alert, $msg_confirm, $btn_task, $extra_js, $btn_list = true, $btn_menu = true, $btn_confirm = true);
        }
        if ($add_divider) {
            JToolBarHelper::divider();
        }
        $add_divider = false;
        if ($CanAdd) {
            $btn_task = '';
            $popup_load_url = JURI::base() . 'index.php?option=com_flexicontent&view=types&format=raw';
            if (FLEXI_J30GE || !FLEXI_J16GE) {
                // Layout of Popup button broken in J3.1, add in J1.5 it generates duplicate HTML tag id (... just for validation), so add manually
                $js .= "\n\t\t\t\t\tjQuery('#toolbar-new a.toolbar, #toolbar-new button')\n\t\t\t\t\t\t.attr('onclick', 'javascript:;')\n\t\t\t\t\t\t.attr('href', '" . $popup_load_url . "')\n\t\t\t\t\t\t.attr('rel', '{handler: \\'iframe\\', size: {x: 800, y: 240}, onClose: function() {}}');\n\t\t\t\t";
                //JToolBarHelper::addNew( $btn_task );
                JToolBarHelper::custom($btn_task, 'new.png', 'new_f2.png', 'FLEXI_NEW', false);
                JHtml::_('behavior.modal', '#toolbar-new a.toolbar, #toolbar-new button');
            } else {
                $toolbar->appendButton('Popup', 'new', JText::_('FLEXI_NEW'), str_replace('&', '&amp;', $popup_load_url), 800, 240);
            }
            $add_divider = true;
        }
        if ($hasEdit) {
            $btn_task = 'items.edit';
            JToolBarHelper::editList($btn_task);
            $add_divider = true;
        }
        if ($add_divider) {
            JToolBarHelper::divider();
        }
        $add_divider = false;
        if ($CanAdd && $CanCopy) {
            $btn_task = 'items.copy';
            JToolBarHelper::custom($btn_task, 'copy.png', 'copy_f2.png', 'FLEXI_BATCH');
            if ($enable_translation_groups) {
                JToolBarHelper::custom('translate', 'translate', 'translate', 'FLEXI_TRANSLATE');
            }
            $add_divider = true;
        }
        $btn_task = 'items.checkin';
        JToolbarHelper::checkin($btn_task);
        if ($add_divider) {
            JToolBarHelper::divider();
            JToolBarHelper::spacer();
        }
        if ($perms->CanConfig) {
            $session = JFactory::getSession();
            $fc_screen_width = (int) $session->get('fc_screen_width', 0, 'flexicontent');
            $_width = $fc_screen_width && $fc_screen_width - 84 > 940 ? $fc_screen_width - 84 > 1400 ? 1400 : $fc_screen_width - 84 : 940;
            $fc_screen_height = (int) $session->get('fc_screen_height', 0, 'flexicontent');
            $_height = $fc_screen_height && $fc_screen_height - 128 > 550 ? $fc_screen_height - 128 > 1000 ? 1000 : $fc_screen_height - 128 : 550;
            JToolBarHelper::preferences('com_flexicontent', $_height, $_width, 'Configuration');
        }
        $js .= "});";
        $document->addScriptDeclaration($js);
        // ***********************
        // Get data from the model
        // ***********************
        $badcatitems = (int) $model->getUnboundedItems($limit = 10000000, $count_only = true, $checkNoExtData = false, $checkInvalidCat = true);
        $unassociated = (int) $model->getUnboundedItems($limit = 10000000, $count_only = true, $checkNoExtData = true, $checkInvalidCat = false);
        $rows = $this->get('Data');
        $pagination = $this->get('Pagination');
        $types = $this->get('Typeslist');
        $authors = $this->get('Authorslist');
        // these depend on data rows and must be called after getting data
        $extraCols = $this->get('ExtraCols');
        $customFilts = $this->get('CustomFilts');
        foreach ($customFilts as $filter) {
            if (count($filter->value)) {
                $count_filters++;
            }
        }
        $itemCats = $this->get('ItemCats');
        $itemTags = $this->get('ItemTags');
        if ($enable_translation_groups) {
            $langAssocs = $this->get('LangAssocs');
        }
        $langs = FLEXIUtilities::getLanguages('code');
        $categories = $globalcats ? $globalcats : array();
        $limit = $pagination->limit;
        $inline_ss_max = 500;
        $drag_reorder_max = 150;
        if ($limit > $drag_reorder_max) {
            $cparams->set('draggable_reordering', 0);
        }
        // ******************************************
        // Add usability notices if these are enabled
        // ******************************************
        if ($cparams->get('show_usability_messages', 1) && !$unassociated && !$badcatitems) {
            $notice_iss_disabled = $app->getUserStateFromRequest($option . '.items.notice_iss_disabled', 'notice_iss_disabled', 0, 'int');
            if (!$notice_iss_disabled && $limit > $inline_ss_max) {
                $app->setUserState($option . '.items.notice_iss_disabled', 1);
                $app->enqueueMessage(JText::sprintf('FLEXI_INLINE_ITEM_STATE_SELECTOR_DISABLED', $inline_ss_max), 'notice');
                $show_turn_off_notice = 1;
            }
            $notice_drag_reorder_disabled = $app->getUserStateFromRequest($option . '.items.notice_drag_reorder_disabled', 'notice_drag_reorder_disabled', 0, 'int');
            if (!$notice_drag_reorder_disabled && $limit > $drag_reorder_max) {
                $app->setUserState($option . '.items.notice_drag_reorder_disabled', 1);
                $app->enqueueMessage(JText::sprintf('FLEXI_DRAG_REORDER_DISABLED', $drag_reorder_max), 'notice');
                $show_turn_off_notice = 1;
            }
            $notice_add_custom_columns = $app->getUserStateFromRequest($option . '.items.notice_add_custom_columns', 'notice_add_custom_columns', 0, 'int');
            if (!$notice_add_custom_columns) {
                $app->setUserState($option . '.items.notice_add_custom_columns', 1);
                $app->enqueueMessage(JText::_('FLEXI_YOU_MAY_CONFIGURE_CUSTOM_COLUMNS_GLOBAL_AND_PER_TYPE'), 'message');
                $show_turn_off_notice = 1;
            }
            if (!empty($show_turn_off_notice)) {
                $app->enqueueMessage(JText::_('FLEXI_USABILITY_MESSAGES_TURN_OFF'), 'message');
            }
        }
        // *******************
        // Create Filters HTML
        // *******************
        // filter publication state
        $states = array();
        //$states[] = JHTML::_('select.option',  '', '-'/*JText::_( 'FLEXI_SELECT_STATE' )*/ );
        $states[] = JHTML::_('select.optgroup', JText::_('FLEXI_SINGLE_STATUS'));
        $states[] = JHTML::_('select.option', 'P', JText::_('FLEXI_PUBLISHED'));
        $states[] = JHTML::_('select.option', 'U', JText::_('FLEXI_UNPUBLISHED'));
        $states[] = JHTML::_('select.option', 'PE', JText::_('FLEXI_PENDING'));
        $states[] = JHTML::_('select.option', 'OQ', JText::_('FLEXI_TO_WRITE'));
        $states[] = JHTML::_('select.option', 'IP', JText::_('FLEXI_IN_PROGRESS'));
        $states[] = JHTML::_('select.option', 'RV', JText::_('FLEXI_REVISED_VER'));
        $states[] = JHTML::_('select.option', 'A', JText::_('FLEXI_ARCHIVED'));
        $states[] = JHTML::_('select.option', 'T', JText::_('FLEXI_TRASHED'));
        $states[] = JHTML::_('select.optgroup', '');
        $states[] = JHTML::_('select.optgroup', JText::_('FLEXI_STATUS_GROUPS'));
        $states[] = JHTML::_('select.option', 'ALL', JText::_('FLEXI_GRP_ALL') . ' ' . JText::_('FLEXI_STATE_S'));
        $states[] = JHTML::_('select.option', 'ALL_P', JText::_('FLEXI_GRP_PUBLISHED') . ' ' . JText::_('FLEXI_STATE_S'));
        $states[] = JHTML::_('select.option', 'ALL_U', JText::_('FLEXI_GRP_UNPUBLISHED') . ' ' . JText::_('FLEXI_STATE_S'));
        $states[] = JHTML::_('select.option', 'ORPHAN', JText::_('FLEXI_GRP_ORPHAN'));
        $states[] = JHTML::_('select.optgroup', '');
        $lists['filter_state'] = ($filter_state || 1 ? '<label class="label">' . JText::_('FLEXI_STATE') . '</label>' : '') . JHTML::_('select.genericlist', $states, 'filter_state[]', 'class="use_select2_lib fcfilter_be" multiple="multiple" size="3" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', 'value', 'text', $filter_state);
        //JHTML::_('grid.state', $filter_state );
        // build filter state group
        if ($hasDelete || $CanArchives) {
            //$stategroups[''] = JText::_( 'FLEXI_GRP_NORMAL' ) .' '. JText::_( 'FLEXI_STATE_S' );
            //$stategroups['published'] = JText::_( 'FLEXI_GRP_PUBLISHED' ) .' '. JText::_( 'FLEXI_STATE_S' );
            //$stategroups['unpublished'] = JText::_( 'FLEXI_GRP_UNPUBLISHED' ) .' '. JText::_( 'FLEXI_STATE_S' );
            /*if ($hasDelete)
            		$stategroups['trashed']  = JText::_( 'FLEXI_GRP_TRASHED' );*/
            /*if ($CanArchives)
            		$stategroups['archived'] = JText::_( 'FLEXI_GRP_ARCHIVED' );*/
            //$stategroups['orphan']      = JText::_( 'FLEXI_GRP_ORPHAN' );
            //$stategroups['all']      = JText::_( 'FLEXI_GRP_ALL' );
            /*$_stategroups = array();
            		foreach ($stategroups as $i => $v) {
            			$_stategroups[] = JHTML::_('select.option', $i, $v);
            		}
            		$lists['filter_stategrp'] = JHTML::_('select.radiolist', $_stategroups, 'filter_stategrp', 'size="1" class="inputbox" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', 'value', 'text', $filter_stategrp );*/
            /*$lists['filter_stategrp'] = '';
            		foreach ($stategroups as $i => $v) {
            			$checked = $filter_stategrp == $i ? ' checked="checked" ' : '';
            			$lists['filter_stategrp'] .= '<input type="radio" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()" class="inputbox" '.$checked.' value="'.$i.'" id="filter_stategrp'.$i.'" name="filter_stategrp" />';
            			$lists['filter_stategrp'] .= '<label class="" id="filter_stategrp'.$i.'-lbl" for="filter_stategrp'.$i.'">'.$v.'</label>';
            		}*/
        }
        // build the include subcats boolean list
        // build the include non-published cats boolean list
        if ($filter_order_type && $filter_cats && ($filter_order == 'i.ordering' || $filter_order == 'catsordering')) {
            $ordering_tip = '<img src="components/com_flexicontent/assets/images/comment.png" class="hasTooltip" title="' . JText::_('FLEXI_SUBCATEGORIES_NOT_INCLUDED_DURING_CATORDER_DESC', true) . '" />';
            $lists['filter_subcats'] = '
			<span class="fc-mssg-inline fc-note">
				' . JText::_('FLEXI_SUBCATEGORIES_NOT_INCLUDED_DURING_CATORDER') . ' &nbsp;
				' . $ordering_tip . '
			</span>';
        } else {
            //$lists['filter_subcats'] = JHTML::_('select.booleanlist',  'filter_subcats', 'class="inputbox" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', $filter_subcats );
            $subcats = array();
            $subcats[] = JHTML::_('select.option', 0, JText::_('FLEXI_NO'));
            $subcats[] = JHTML::_('select.option', 1, JText::_('FLEXI_YES'));
            $lists['filter_subcats'] = JHTML::_('select.genericlist', $subcats, 'filter_subcats', 'size="1" class="use_select2_lib ' . ($filter_subcats != 1 ? '' : ' fc_skip_highlight') . '" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', 'value', 'text', $filter_subcats, 'filter_subcats');
        }
        $lists['filter_subcats'] = ($filter_subcats || 1 ? '<label class="label">' . JText::_('FLEXI_SUBCATEGORIES') . '</label>' : '') . $lists['filter_subcats'];
        // build the include non-published cats boolean list
        $catsinstate[1] = JText::_('FLEXI_PUBLISHED');
        $catsinstate[0] = JText::_('FLEXI_UNPUBLISHED');
        $catsinstate[99] = JText::_('FLEXI_ANY');
        $catsinstate[2] = JText::_('FLEXI_ARCHIVED_STATE');
        $catsinstate[-2] = JText::_('FLEXI_TRASHED_STATE');
        $_catsinstate = array();
        foreach ($catsinstate as $i => $v) {
            $_catsinstate[] = JHTML::_('select.option', $i, $v);
        }
        $lists['filter_catsinstate'] = ($filter_catsinstate || 1 ? '<label class="label">' . JText::_('FLEXI_LIST_ITEMS_IN_CATS') . '</label>' : '') . JHTML::_('select.genericlist', $_catsinstate, 'filter_catsinstate', 'size="1" class="use_select2_lib' . ($filter_catsinstate != 1 ? '' : ' fc_skip_highlight') . '" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', 'value', 'text', $filter_catsinstate, 'filter_catsinstate');
        //$lists['filter_catsinstate'] = JHTML::_('select.radiolist', $_catsinstate, 'filter_catsinstate', 'size="1" class="inputbox" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', 'value', 'text', $filter_catsinstate );
        /*$lists['filter_catsinstate']  = '';
        		foreach ($catsinstate as $i => $v) {
        			$checked = $filter_catsinstate == $i ? ' checked="checked" ' : '';
        			$lists['filter_catsinstate'] .= '<input type="radio" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()" class="inputbox" '.$checked.' value="'.$i.'" id="filter_catsinstate'.$i.'" name="filter_catsinstate" />';
        			$lists['filter_catsinstate'] .= '<label class="" id="filter_catsinstate'.$i.'-lbl" for="filter_catsinstate'.$i.'">'.$v.'</label>';
        		}*/
        // build the order type boolean list
        $order_types = array();
        $order_types[] = JHTML::_('select.option', '0', 'FLEXI_ORDER_JOOMLA');
        $order_types[] = JHTML::_('select.option', '1', 'FLEXI_ORDER_FLEXICONTENT');
        //$lists['filter_order_type'] = JHTML::_('select.radiolist', $order_types, 'filter_order_type', 'size="1" class="inputbox" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', 'value', 'text', $filter_order_type );
        $lists['filter_order_type'] = JHTML::_('select.genericlist', $order_types, 'filter_order_type', 'size="1" class="use_select2_lib fc_skip_highlight" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', 'value', 'text', $filter_order_type, 'filter_order_type', $translate = true);
        // build the categories select list for filter
        $lists['filter_cats'] = ($filter_cats || 1 ? '<label class="label">' . JText::_('FLEXI_CATEGORY') . '</label>' : '') . flexicontent_cats::buildcatselect($categories, 'filter_cats', $filter_cats, '-', 'class="use_select2_lib" size="1" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', $check_published = false, $check_perms = false);
        //build type select list
        $lists['filter_type'] = ($filter_type || 1 ? '<label class="label">' . JText::_('FLEXI_TYPE') . '</label>' : '') . flexicontent_html::buildtypesselect($types, 'filter_type[]', $filter_type, 0, 'class="use_select2_lib fcfilter_be" multiple="multiple" size="3" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', 'filter_type');
        //build authors select list
        $lists['filter_author'] = ($filter_author || 1 ? '<label class="label">' . JText::_('FLEXI_AUTHOR') . '</label>' : '') . flexicontent_html::buildauthorsselect($authors, 'filter_author[]', $filter_author, 0, 'class="use_select2_lib fcfilter_be" multiple="multiple" size="3" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"');
        if ($badcatitems) {
            $lists['default_cat'] = flexicontent_cats::buildcatselect($categories, 'default_cat', '', 2, 'class="use_select2_lib"', false, false);
        }
        //search filter
        $scopes = array();
        $scopes[1] = JText::_('FLEXI_TITLE');
        $scopes[2] = JText::_('FLEXI_INTROTEXT');
        $scopes[4] = JText::_('FLEXI_INDEXED_CONTENT');
        $_scopes = array();
        foreach ($scopes as $i => $v) {
            $_scopes[] = JHTML::_('select.option', $i, $v);
        }
        //$lists['scope'] = JHTML::_('select.radiolist', $_scopes, 'scope', 'size="1" class="inputbox"', 'value', 'text', $scope );
        $lists['scope'] = JHTML::_('select.genericlist', $_scopes, 'scope', 'size="1" class="use_select2_lib fc_skip_highlight" onchange="jQuery(\'#search\').attr(\'placeholder\', jQuery(this).find(\'option:selected\').text());" title="' . JText::_('FLEXI_SEARCH_TEXT_INSIDE') . '"', 'value', 'text', $scope, 'scope');
        /*$lists['scope']  = '';
        		foreach ($scopes as $i => $v) {
        			$checked = $scope == $i ? ' checked="checked" ' : '';
        			$lists['scope'] .= '<input type="radio" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()" class="inputbox" '.$checked.' value="'.$i.'" id="scope'.$i.'" name="scope" />';
        			$lists['scope'] .= '<label class="" id="scope'.$i.'-lbl" for="scope'.$i.'">'.$v.'</label>';
        		}*/
        // build item dates option list
        $dates[1] = JText::_('FLEXI_CREATED');
        $dates[2] = JText::_('FLEXI_REVISED');
        $_dates = array();
        foreach ($dates as $i => $v) {
            $_dates[] = JHTML::_('select.option', $i, $v);
        }
        //$lists['date'] = JHTML::_('select.radiolist', $_dates, 'date', 'size="1" class="inputbox"', 'value', 'text', $date );
        $lists['date'] = '<label class="label">' . JText::_('FLEXI_DATE') . '</label>' . JHTML::_('select.genericlist', $_dates, 'date', 'size="1" class="use_select2_lib fc_skip_highlight"', 'value', 'text', $date, 'date');
        /*$lists['date']  = '';
        		foreach ($dates as $i => $v) {
        			$checked = $date == $i ? ' checked="checked" ' : '';
        			$lists['date'] .= '<input type="radio" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()" class="inputbox" '.$checked.' value="'.$i.'" id="date'.$i.'" name="date" />';
        			$lists['date'] .= '<label class="" id="date'.$i.'-lbl" for="date'.$i.'">'.$v.'</label>';
        		}*/
        $lists['startdate'] = JHTML::_('calendar', $startdate, 'startdate', 'startdate', '%Y-%m-%d', array('class' => 'inputbox', 'size' => '8', 'maxlength' => '19', 'style' => 'width:auto', 'placeholder' => JText::_('FLEXI_FROM')));
        $lists['enddate'] = JHTML::_('calendar', $enddate, 'enddate', 'enddate', '%Y-%m-%d', array('class' => 'inputbox', 'size' => '8', 'maxlength' => '19', 'style' => 'width:auto', 'placeholder' => JText::_('FLEXI_TO')));
        // search filter
        $bind_limits = array();
        $bind_limits[] = JHTML::_('select.option', 250, '250 ' . JText::_('FLEXI_ITEMS'));
        $bind_limits[] = JHTML::_('select.option', 500, '500 ' . JText::_('FLEXI_ITEMS'));
        $bind_limits[] = JHTML::_('select.option', 750, '750 ' . JText::_('FLEXI_ITEMS'));
        $bind_limits[] = JHTML::_('select.option', 1000, '1000 ' . JText::_('FLEXI_ITEMS'));
        $bind_limits[] = JHTML::_('select.option', 1500, '1500 ' . JText::_('FLEXI_ITEMS'));
        $bind_limits[] = JHTML::_('select.option', 2000, '2000 ' . JText::_('FLEXI_ITEMS'));
        $lists['bind_limits'] = JHTML::_('select.genericlist', $bind_limits, 'bind_limit', 'size="1" class="use_select2_lib"', 'value', 'text', $bind_limit, 'bind_limit');
        // search filter
        $lists['search'] = $search;
        // search id
        $lists['filter_id'] = $filter_id;
        // table ordering
        $lists['order_Dir'] = $filter_order_Dir;
        $lists['order'] = $filter_order;
        // filter ordering
        if (!$filter_order_type) {
            $ordering = $lists['order'] == 'i.ordering';
        } else {
            $ordering = $lists['order'] == 'catsordering';
        }
        //build tags filter
        $lists['filter_tag'] = ($filter_tag || 1 ? '<label class="label">' . JText::_('FLEXI_TAG') . '</label>' : '') . flexicontent_html::buildtagsselect('filter_tag[]', 'class="use_select2_lib fcfilter_be" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()" multiple="multiple" size="3" ', $filter_tag, 0);
        //build languages filter
        $lists['filter_lang'] = ($filter_lang || 1 ? '<label class="label">' . JText::_('FLEXI_LANGUAGE') . '</label>' : '') . flexicontent_html::buildlanguageslist('filter_lang[]', 'class="use_select2_lib fcfilter_be" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()" multiple="multiple" size="3" ', $filter_lang, 1);
        // build access level filter
        $access_levels = JHtml::_('access.assetgroups');
        /*if ( $cparams->get('iman_viewable_items', 1) )  // only viewable items is enabled, skip the non available levels to avoid user confusion
        		{
        			$_aid_arr = array_flip(JAccess::getAuthorisedViewLevels($user->id));
        			$_levels = array();
        			foreach($access_levels as $i => $level)
        			{
        				if ( isset($_aid_arr[$level->value]) )
        					$_levels[] = $level;
        				//else $access_levels[$i]->disable = 1;
        			}
        			$access_levels = $_levels;
        		}*/
        // Above code is maybe problematic (e.g. in multi-sites), need to test more
        //array_unshift($access_levels, JHtml::_('select.option', '', '-'/*'JOPTION_SELECT_ACCESS'*/) );
        $fieldname = 'filter_access[]';
        // make multivalue
        $elementid = 'filter_access';
        $attribs = 'class="use_select2_lib fcfilter_be" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()" multiple="multiple"';
        $lists['filter_access'] = ($filter_access || 1 ? '<label class="label">' . JText::_('FLEXI_ACCESS') . '</label>' : '') . JHTML::_('select.genericlist', $access_levels, $fieldname, $attribs, 'value', 'text', $filter_access, $elementid, $translate = true);
        // filter by item usage a specific file
        if ($fileid_to_itemids && count($fileid_to_itemids)) {
            $files_data = $model->getFileData(array_keys($fileid_to_itemids));
            $file_options = array();
            $file_options[] = JHTML::_('select.option', '', '-');
            foreach ($files_data as $_file) {
                $file_options[] = JHTML::_('select.option', $_file->id, $_file->altname);
            }
            flexicontent_html::loadFramework('select2');
            $lists['filter_fileid'] = ($filter_fileid || 1 ? '<label class="label">' . JText::_('FLEXI_ITEMS_USING') . ' ' . JText::_('FLEXI_FILE') . '</label>' : '') . JHTML::_('select.genericlist', $file_options, 'filter_fileid', 'size="1" class="use_select2_lib' . ($filter_fileid ? '' : ' fc_skip_highlight') . '" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', 'value', 'text', $filter_fileid);
        }
        //assign data to template
        $this->assignRef('CanTemplates', $perms->CanTemplates);
        $this->assignRef('count_filters', $count_filters);
        //$this->assignRef('filter_stategrp', $filter_stategrp);
        $this->assignRef('filter_catsinstate', $filter_catsinstate);
        $this->assignRef('db', $db);
        $this->assignRef('lists', $lists);
        $this->assignRef('rows', $rows);
        $this->assignRef('itemCats', $itemCats);
        $this->assignRef('itemTags', $itemTags);
        $this->assignRef('extra_fields', $extraCols);
        $this->assignRef('custom_filts', $customFilts);
        if ($enable_translation_groups) {
            $this->assignRef('lang_assocs', $langAssocs);
        }
        $this->assignRef('langs', $langs);
        $this->assignRef('cid', $cid);
        $this->assignRef('pagination', $pagination);
        $this->assignRef('ordering', $ordering);
        $this->assignRef('CanOrder', $CanOrder);
        $this->assignRef('CanCats', $CanCats);
        $this->assignRef('CanAccLvl', $CanAccLvl);
        $this->assignRef('unassociated', $unassociated);
        $this->assignRef('badcatitems', $badcatitems);
        // filters
        $this->assignRef('filter_id', $filter_id);
        $this->assignRef('filter_state', $filter_state);
        $this->assignRef('filter_author', $filter_author);
        $this->assignRef('filter_type', $filter_type);
        $this->assignRef('filter_cats', $filter_cats);
        $this->assignRef('filter_subcats', $filter_subcats);
        $this->assignRef('filter_catsinstate', $filter_catsinstate);
        $this->assignRef('filter_order_type', $filter_order_type);
        $this->assignRef('filter_order', $filter_order);
        $this->assignRef('filter_lang', $filter_lang);
        $this->assignRef('filter_access', $filter_access);
        $this->assignRef('filter_tag', $filter_tag);
        $this->assignRef('filter_fileid', $filter_fileid);
        $this->assignRef('inline_ss_max', $inline_ss_max);
        $this->assignRef('scope', $scope);
        $this->assignRef('search', $search);
        $this->assignRef('date', $date);
        $this->assignRef('startdate', $startdate);
        $this->assignRef('enddate', $enddate);
        $this->assignRef('option', $option);
        $this->assignRef('view', $view);
        $print_logging_info = $cparams->get('print_logging_info');
        if ($print_logging_info) {
            global $fc_run_times;
            $start_microtime = microtime(true);
        }
        $this->sidebar = FLEXI_J30GE ? JHtmlSidebar::render() : null;
        parent::display($tpl);
        if ($print_logging_info) {
            @($fc_run_times['template_render'] += round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
        }
    }
예제 #11
0
 /**
  * Method to copy items
  *
  * @access	public
  * @return	boolean	True on success
  * @since	1.5
  */
 function copyitems($cid, $keeptags = 1, $prefix, $suffix, $copynr = 1, $lang = null, $state = null, $method = 1, $maincat = null, $seccats = null, $type_id = null, $access = null)
 {
     $app = JFactory::getApplication();
     $jinput = $app->input;
     $dbprefix = $app->getCfg('dbprefix');
     $use_versioning = $this->cparams->get('use_versioning', 1);
     require_once "components/com_flexicontent/models/item.php";
     // ************************************************************************
     // Try to find Falang/Joomfish, to import translation data, if so requested
     // ************************************************************************
     $_FALANG = false;
     $this->_db->setQuery('SHOW TABLES LIKE "' . $dbprefix . 'falang_content"');
     $_FALANG = (bool) count($this->_db->loadObjectList());
     // Try to find old joomfish tables (with current DB prefix)
     $this->_db->setQuery('SHOW TABLES LIKE "' . $dbprefix . 'jf_content"');
     $_FISH = (bool) count($this->_db->loadObjectList());
     // Try to find old joomfish tables (with J1.5 jos prefix)
     if (!$_FISH) {
         $this->_db->setQuery('SHOW TABLES LIKE "jos_jf_content"');
         if (count($this->_db->loadObjectList())) {
             $_FISH = true;
             $dbprefix = 'jos_';
         }
     }
     // Detect version of joomfish tables
     $_FISH22GE = false;
     if ($_FISH) {
         $this->_db->setQuery('SHOW TABLES LIKE "' . $dbprefix . 'jf_languages_ext"');
         $_FISH22GE = (bool) count($this->_db->loadObjectList());
     }
     $_NEW_LANG_TBL = FLEXI_J16GE || $_FISH22GE;
     // Get if translation is to be performed, 1: FLEXI_DUPLICATEORIGINAL,  2: FLEXI_USE_JF_DATA,  3: FLEXI_AUTO_TRANSLATION,  4: FLEXI_FIRST_JF_THEN_AUTO
     if ($method == 99) {
         $translate_method = $jinput->get('translate_method', 1, 'int');
     } else {
         $translate_method = 0;
     }
     // If translation method import the translator class
     if ($translate_method == 3 || $translate_method == 4) {
         require_once JPATH_COMPONENT_SITE . DS . 'helpers' . DS . 'translator.php';
     }
     // If translation method load description field to allow some parsing according to parameters
     if ($translate_method == 3 || $translate_method == 4) {
         $this->_db->setQuery('SELECT id FROM #__flexicontent_fields WHERE name = "text" ');
         $desc_field_id = $this->_db->loadResult();
         $desc_field = JTable::getInstance('flexicontent_fields', '');
         $desc_field->load($desc_field_id);
     }
     // ************************************************************
     // Loop through the items, copying, moving, or translating them
     // ************************************************************
     foreach ($cid as $itemid) {
         for ($nr = 0; $nr < $copynr; $nr++) {
             // (a) Get existing item
             $item = JTable::getInstance('flexicontent_items', '');
             $item->load($itemid);
             // Some shortcuts
             $sourceid = (int) $item->id;
             $curversion = (int) $item->version;
             // (b) We create copy so that the original data are always available
             $row = clone $item;
             // (c) Force creation & assigning of new records by cleaning the primary keys
             $row->id = null;
             // force creation of new record in _content DB table
             $row->item_id = null;
             // force creation of new record in _flexicontent_ext DB table
             $row->asset_id = null;
             // force creation of new record in _assets DB table
             // (d) Start altering the properties of the cloned item
             $row->title = ($prefix ? $prefix . ' ' : '') . $item->title . ($suffix ? ' ' . $suffix : '');
             $row->hits = 0;
             if (!$translate_method) {
                 // cleared featured flag if not translating
                 $row->featured = 0;
             }
             $row->version = 1;
             $datenow = JFactory::getDate();
             $row->created = $datenow->toSql();
             $row->publish_up = $datenow->toSql();
             $row->modified = $nullDate = $this->_db->getNullDate();
             $lang_from = substr($row->language, 0, 2);
             $row->language = $lang ? $lang : $row->language;
             $lang_to = substr($row->language, 0, 2);
             $row->state = strlen($state) ? $state : $row->state;
             // keep original if: null, ''
             $row->type_id = $type_id ? $type_id : $row->type_id;
             // keep original if: null, zero, ''
             $row->access = $access ? $access : $row->access;
             // keep original if: null, zero, ''
             $doauto['title'] = $doauto['introtext'] = $doauto['fulltext'] = $doauto['metakey'] = $doauto['metadesc'] = true;
             // In case JF data is missing
             if ($translate_method == 2 || $translate_method == 4) {
                 // a. Try to get joomfish/falang translation from the item
                 $jfitemfields = false;
                 if ($_FALANG) {
                     $query = "SELECT c.* FROM `#__falang_content` AS c " . " LEFT JOIN #__languages AS lg ON c.language_id=lg.lang_id" . " WHERE c.reference_table = 'content' AND lg.lang_code='" . $row->language . "' AND c.reference_id = " . $sourceid;
                     $this->_db->setQuery($query);
                     $jfitemfields = $this->_db->loadObjectList();
                 }
                 if (!$jfitemfields && $_FISH) {
                     $query = "SELECT c.* FROM `" . $dbprefix . "jf_content` AS c " . " LEFT JOIN #__languages AS lg ON c.language_id=" . ($_NEW_LANG_TBL ? "lg.lang_id" : "lg.id") . " WHERE c.reference_table = 'content' AND " . ($_NEW_LANG_TBL ? "lg.lang_code" : "lg.code") . "='" . $row->language . "' AND c.reference_id = " . $sourceid;
                     $this->_db->setQuery($query);
                     $jfitemfields = $this->_db->loadObjectList();
                 }
                 // b. if joomfish translation found set for the new item
                 if ($jfitemfields) {
                     $jfitemdata = new stdClass();
                     foreach ($jfitemfields as $jfitemfield) {
                         $jfitemdata->{$jfitemfield->reference_field} = $jfitemfield->value;
                     }
                     if (isset($jfitemdata->title) && mb_strlen($jfitemdata->title) > 0) {
                         $row->title = $jfitemdata->title;
                         $doauto['title'] = false;
                     }
                     if (isset($jfitemdata->alias) && mb_strlen($jfitemdata->alias) > 0) {
                         $row->alias = $jfitemdata->alias;
                     }
                     if (isset($jfitemdata->introtext) && mb_strlen(strip_tags($jfitemdata->introtext)) > 0) {
                         $row->introtext = $jfitemdata->introtext;
                         $doauto['introtext'] = false;
                     }
                     if (isset($jfitemdata->fulltext) && mb_strlen(strip_tags($jfitemdata->fulltext)) > 0) {
                         $row->fulltext = $jfitemdata->fulltext;
                         $doauto['fulltext'] = false;
                     }
                     if (isset($jfitemdata->metakey) && mb_strlen($jfitemdata->metakey) > 0) {
                         $row->metakey = $jfitemdata->metakey;
                         $doauto['metakey'] = false;
                     }
                     if (isset($jfitemdata->metadesc) && mb_strlen($jfitemdata->metadesc) > 0) {
                         $row->metadesc = $jfitemdata->metadesc;
                         $doauto['metadesc'] = false;
                     }
                 }
             }
             // Try to do automatic translation from the item, if autotranslate is SET and --NOT found-- or --NOT using-- JoomFish Data
             if ($translate_method == 3 || $translate_method == 4) {
                 // Translate fulltext item property, using the function for which handles custom fields TYPES: text, textarea, ETC
                 if ($doauto['fulltext']) {
                     $desc_field->value = $row->fulltext;
                     $fields = array(&$desc_field);
                     $this->translateFieldValues($fields, $row, $lang_from, $lang_to);
                     $row->fulltext = $desc_field->value;
                 }
                 // TRANSLATE basic item properties (if not already imported via Joomfish)
                 $translatables = array('title', 'introtext', 'metakey', 'metadesc');
                 $fieldnames_arr = array();
                 $fieldvalues_arr = array();
                 foreach ($translatables as $translatable) {
                     if (!$doauto[$translatable]) {
                         continue;
                     }
                     $fieldnames_arr[] = $translatable;
                     $translatable_obj = new stdClass();
                     $translatable_obj->originalValue = $row->{$translatable};
                     $translatable_obj->noTranslate = false;
                     $fieldvalues_arr[] = $translatable_obj;
                 }
                 if (count($fieldvalues_arr)) {
                     $result = autoTranslator::translateItem($fieldnames_arr, $fieldvalues_arr, $lang_from, $lang_to);
                     if (intval($result)) {
                         $n = 0;
                         foreach ($fieldnames_arr as $fieldname) {
                             $row->{$fieldname} = $fieldvalues_arr[$n]->translationValue;
                             $n++;
                         }
                     }
                 }
             }
             //print_r($row->fulltext); exit;
             // Create a new item in the content fc_items_ext table
             $row->store();
             // Not doing a translation, we start a new language group for the new item
             if ($translate_method == 0) {
                 $row->lang_parent_id = 0;
                 //$row->id;
                 $row->store();
             }
             // ***********************************************************
             // Copy custom fields, translating the fields if so configured
             // ***********************************************************
             $doTranslation = $translate_method == 3 || $translate_method == 4;
             $query = 'SELECT fir.*, f.* ' . ' FROM #__flexicontent_fields_item_relations as fir' . ' LEFT JOIN #__flexicontent_fields as f ON f.id=fir.field_id' . ' WHERE item_id = ' . $sourceid;
             $this->_db->setQuery($query);
             $fields = $this->_db->loadObjectList();
             //echo "<pre>"; print_r($fields); exit;
             if ($doTranslation) {
                 $this->translateFieldValues($fields, $row, $lang_from, $lang_to);
             }
             //foreach ($fields as $field)  if ($field->field_type!='text' && $field->field_type!='textarea') { print_r($field->value); echo "<br><br>"; }
             foreach ($fields as $field) {
                 if (strlen($field->value)) {
                     $query = 'INSERT INTO #__flexicontent_fields_item_relations (`field_id`, `item_id`, `valueorder`, `suborder`, `value`)' . ' VALUES(' . $field->field_id . ', ' . $row->id . ', ' . $field->valueorder . ', ' . $field->suborder . ', ' . $this->_db->Quote($field->value) . ')';
                     $this->_db->setQuery($query);
                     $this->_db->execute();
                 }
             }
             if ($use_versioning) {
                 $v = new stdClass();
                 $v->item_id = (int) $item->id;
                 $v->version_id = 1;
                 $v->created = $item->created;
                 $v->created_by = $item->created_by;
                 //$v->comment		= 'copy version.';
                 $this->_db->insertObject('#__flexicontent_versions', $v);
             }
             // get the items versions
             $query = 'SELECT *' . ' FROM #__flexicontent_items_versions' . ' WHERE item_id = ' . $sourceid . ' AND version = ' . $curversion;
             $this->_db->setQuery($query);
             $curversions = $this->_db->loadObjectList();
             foreach ($curversions as $cv) {
                 $query = 'INSERT INTO #__flexicontent_items_versions (`version`, `field_id`, `item_id`, `valueorder`, `suborder`, `value`)' . ' VALUES(1 ,' . $cv->field_id . ', ' . $row->id . ', ' . $cv->valueorder . ', ' . $cv->suborder . ', ' . $this->_db->Quote($cv->value) . ')';
                 $this->_db->setQuery($query);
                 $this->_db->execute();
             }
             // get the item categories
             $query = 'SELECT catid' . ' FROM #__flexicontent_cats_item_relations' . ' WHERE itemid = ' . $sourceid;
             $this->_db->setQuery($query);
             $cats = $this->_db->loadColumn();
             foreach ($cats as $cat) {
                 $query = 'INSERT INTO #__flexicontent_cats_item_relations (`catid`, `itemid`)' . ' VALUES(' . $cat . ',' . $row->id . ')';
                 $this->_db->setQuery($query);
                 $this->_db->execute();
             }
             if ($keeptags) {
                 // get the item tags
                 $query = 'SELECT tid' . ' FROM #__flexicontent_tags_item_relations' . ' WHERE itemid = ' . $sourceid;
                 $this->_db->setQuery($query);
                 $tags = $this->_db->loadColumn();
                 foreach ($tags as $tag) {
                     $query = 'INSERT INTO #__flexicontent_tags_item_relations (`tid`, `itemid`)' . ' VALUES(' . $tag . ',' . $row->id . ')';
                     $this->_db->setQuery($query);
                     $this->_db->execute();
                 }
             }
             if ($method == 3) {
                 $this->moveitem($row->id, $maincat, $seccats);
             } else {
                 if ($method == 99 && ($maincat || $seccats)) {
                     $row->catid = $maincat ? $maincat : $row->catid;
                     $this->moveitem($row->id, $row->catid, $seccats);
                 }
             }
             // Load item model and save it once, e.g. updating Joomla featured FLAG data
             //$itemmodel = new FlexicontentModelItem();
             //$itemmodel->getItem($row->id);
             //$itemmodel->store((array)$row);
             // If new item is a tranlation, load the language associations of item
             // that was copied, and save the associations, adding the new item to them
             if ($method == 99 && $item->language != '*' && $row->language != '*' && flexicontent_db::useAssociations()) {
                 $associations = JLanguageAssociations::getAssociations('com_content', '#__content', 'com_content.item', $item->id);
                 // associations of item that was copied
                 $_data = array();
                 foreach ($associations as $tag => $association) {
                     $_data['associations'][$tag] = (int) $association->id;
                 }
                 $_data['associations'][$row->language] = $row->id;
                 // Add new item itself
                 $_data['associations'][$item->language] = $item->id;
                 // unneeded, done by saving ...
                 $context = 'com_content';
                 flexicontent_db::saveAssociations($row, $_data, $context);
                 // Save associations, adding the new item
                 //$app->enqueueMessage( print_r($_data, true), 'message' );
             }
         }
     }
     return true;
 }
예제 #12
0
    function onDisplayField(&$field, &$item)
    {
        if (!in_array($field->field_type, self::$field_types)) {
            return;
        }
        $field->label = JText::_($field->label);
        // Get some api objects
        $db = JFactory::getDBO();
        $user = JFactory::getUser();
        $document = JFactory::getDocument();
        $field->html = '';
        $ri_field_name = str_replace('-', '_', $field->name);
        $fieldname = FLEXI_J16GE ? 'custom[' . $ri_field_name . '][]' : $ri_field_name . '[]';
        // Case of autorelated item
        $autorelation_itemid = JRequest::getInt('autorelation_' . $field->id);
        if ($autorelation_itemid) {
            // automatically related item
            $query = 'SELECT title, id, catid, state, alias ' . ' FROM #__content ' . ' WHERE id =' . $autorelation_itemid;
            $db->setQuery($query);
            $rel_item = $db->loadObject();
            if (!$rel_item) {
                $field->html = 'auto relating item id: ' . $autorelation_itemid . ' : item not found ';
                return;
            }
            $field->html = '<input id="' . $ri_field_name . '" name="' . $fieldname . '" type="hidden" value="' . $rel_item->id . ':' . $rel_item->catid . '" />';
            $field->html .= $rel_item->title;
            return;
        }
        // ************************************************************************
        // Initialise values and split them into: (a) item ids and (b) category ids
        // ************************************************************************
        $default_values = '';
        if ($item->version == 0 && $default_values) {
            $field->value = explode(",", $default_values);
        } else {
            if (!$field->value) {
                $field->value = array();
            } else {
                // Compatibility with old values, we no longer serialize all values to one, this way the field can be reversed more easily !!!
                $field->value = ($field_data = @unserialize($field->value[0])) ? $field_data : $field->value;
            }
        }
        $_itemids_catids = array();
        foreach ($field->value as $i => $val) {
            list($itemid, $catid) = explode(":", $val);
            $itemid = (int) $itemid;
            $catid = (int) $catid;
            $_itemids_catids[$itemid] = new stdClass();
            $_itemids_catids[$itemid]->itemid = $itemid;
            $_itemids_catids[$itemid]->catid = $catid;
            $_itemids_catids[$itemid]->value = $val;
        }
        $auto_relate_curritem = $field->parameters->get('auto_relate_curritem', 0);
        if ($auto_relate_curritem && !empty($_itemids_catids) && !FlexicontentHelperPerm::getPerm()->SuperAdmin) {
            $query = 'SELECT title, id, catid, state, alias ' . ' FROM #__content ' . ' WHERE id IN (' . implode(array_keys($_itemids_catids), ',') . ')';
            $db->setQuery($query);
            $rel_items = $db->loadObjectList();
            $i = 0;
            foreach ($rel_items as $rel_item) {
                $field->html .= '<input id="' . $ri_field_name . $i . '" name="' . $fieldname . '" type="hidden" value="' . $rel_item->id . ':' . $rel_item->catid . '" />';
                $field->html .= $rel_item->title . " <br/> \n";
                $i++;
            }
            return;
        }
        // ******************
        // SCOPE PARAMETERS
        // ******************
        // categories scope parameters
        $method_cat = $field->parameters->get('method_cat', 1);
        $usesubcats = $field->parameters->get('usesubcats', 0);
        $catids = $field->parameters->get('catids');
        if (empty($catids)) {
            $catids = array();
        } else {
            if (!is_array($catids)) {
                $catids = !FLEXI_J16GE ? array($catids) : explode("|", $catids);
            }
        }
        // types scope parameters
        $method_types = $field->parameters->get('method_types', 1);
        $types = $field->parameters->get('types');
        if (empty($types)) {
            $types = array();
        } else {
            if (!is_array($types)) {
                $types = !FLEXI_J16GE ? array($types) : explode("|", $types);
            }
        }
        // other limits of scope parameters
        $samelangonly = $field->parameters->get('samelangonly', 1);
        $onlypublished = $field->parameters->get('onlypublished', 1);
        $ownedbyuser = $field->parameters->get('ownedbyuser', 0);
        // ******************
        // EDITING PARAMETERS
        // ******************
        // some parameters shortcuts
        $size = $field->parameters->get('size', 12);
        $size = $size ? ' size="' . $size . '"' : '';
        $prepend_item_state = $field->parameters->get('prepend_item_state', 1);
        $maxtitlechars = $field->parameters->get('maxtitlechars', 40);
        $title_filter = $field->parameters->get('title_filter', 1);
        $required = $field->parameters->get('required', 0);
        $required = $required ? ' required' : '';
        $select_items_prompt = $field->parameters->get('select_items_prompt', 'FLEXI_RIFLD_SELECT_ITEMS_PROMPT');
        $selected_items_label = $field->parameters->get('selected_items_label', 'FLEXI_RIFLD_SELECTED_ITEMS_LABEL');
        $display_cat_filter_label = $field->parameters->get('display_cat_filter_label', 1);
        $display_title_filter_label = $field->parameters->get('display_title_filter_label', 1);
        $default_value_title_filter = $field->parameters->get('default_value_title_filter', '');
        // ***********************************************
        // Get & check Global category related permissions
        // ***********************************************
        require_once JPATH_ROOT . DS . 'components' . DS . 'com_flexicontent' . DS . 'helpers' . DS . 'permission.php';
        $viewallcats = FlexicontentHelperPerm::getPerm()->ViewAllCats;
        $viewtree = FlexicontentHelperPerm::getPerm()->ViewTree;
        if (!$viewtree) {
            $field->html = '<div class="alert alert-info fc-small fc-iblock">' . JText::_('FLEXI_NO_ACCESS_LEVEL_TO_VIEW_CATEGORY_TREE') . '</div><div class="clear"></div>';
            return;
        }
        // ****************************************************
        // Calculate categories to use for retrieving the items
        // ****************************************************
        $allowed_cats = $disallowed_cats = false;
        // Get user allowed categories
        $usercats = FLEXI_J16GE || FLEXI_ACCESS ? FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.create', 'core.edit', 'core.edit.own'), $require_all = false, $check_published = true) : FlexicontentHelperPerm::returnAllCats($check_published = true, $specific_catids = null);
        // Find (if configured) , descendants of the categories
        if ($usesubcats) {
            global $globalcats;
            $_catids = array();
            foreach ($catids as $catid) {
                $subcats = $globalcats[$catid]->descendantsarray;
                foreach ($subcats as $subcat) {
                    $_catids[(int) $subcat] = 1;
                }
            }
            $catids = array_keys($_catids);
        }
        // ... TODO: retrieve items via AJAX
        // *********************************************
        // Item retrieving query ... CREATE WHERE CLAUSE
        // *********************************************
        $where = array();
        // **************
        // CATEGORY SCOPE
        // **************
        // Include method
        if ($method_cat == 3) {
            $allowed_cats = $viewallcats ? $catids : array_intersect($usercats, $catids);
            if (!empty($allowed_cats)) {
                $where[] = " rel.catid IN (" . implode(',', $allowed_cats) . ") ";
            } else {
                $field->html = JText::_('FLEXI_CANNOT_EDIT_FIELD') . ': <br/> ' . JText::_('FLEXI_NO_ACCESS_TO_USE_CONFIGURED_CATEGORIES');
                return;
            }
        } else {
            if ($method_cat == 2) {
                $disallowed_cats = $viewallcats ? $catids : array_diff($usercats, $catids);
                if (!empty($disallowed_cats)) {
                    $where[] = " rel.catid NOT IN (" . implode(',', $disallowed_cats) . ") ";
                }
            } else {
                if (!$viewallcats) {
                    $allowed_cats = $usercats;
                    if (!empty($allowed_cats)) {
                        $where[] = " rel.catid IN (" . implode(',', $allowed_cats) . ") ";
                    } else {
                        $field->html = JText::_('FLEXI_CANNOT_EDIT_FIELD') . ': <br/> ' . JText::_('FLEXI_NO_ACCESS_TO_USE_ANY_CATEGORIES');
                        return;
                    }
                }
            }
        }
        // TYPE SCOPE
        if (($method_types == 2 || $method_types == 3) && (!count($types) || empty($types[0]))) {
            $field->html = 'Content Type scope is set to include/exclude but no Types are selected in field configuration, please set to "ALL" or select types to include/exclude';
            return;
        }
        if ($method_types == 2) {
            $where[] = ' ie.type_id NOT IN (' . implode(',', $types) . ')';
        } else {
            if ($method_types == 3) {
                $where[] = ' ie.type_id IN (' . implode(',', $types) . ')';
            }
        }
        // include method
        // OTHER SCOPE LIMITS
        if ($samelangonly) {
            $where[] = $item->language == '*' ? " ie.language='*' " : " (ie.language='{$item->language}' OR ie.language='*') ";
        }
        if ($onlypublished) {
            $where[] = " i.state IN (1, -5) ";
        }
        if ($ownedbyuser == 1) {
            $where[] = " i.created_by = " . $user->id;
        } else {
            if ($ownedbyuser == 2) {
                $where[] = " i.created_by = " . $item->created_by;
            }
        }
        $where = !count($where) ? "" : " WHERE " . implode(" AND ", $where);
        // ***********************************************
        // Item retrieving query ... CREATE ORDERBY CLAUSE
        // ***********************************************
        $order = $field->parameters->get('orderby_form', 'alpha');
        // TODO: add more orderings: commented, rated
        $orderby = flexicontent_db::buildItemOrderBy($field->parameters, $order, $request_var = '', $config_param = '', $item_tbl_alias = 'i', $relcat_tbl_alias = 'rel', $default_order = '', $default_order_dir = '', $sfx = '_form', $support_2nd_lvl = false);
        // Create JOIN for ordering items by a most rated
        if (in_array('author', $order) || in_array('rauthor', $order)) {
            $orderby_join = ' LEFT JOIN #__users AS u ON u.id = i.created_by';
        }
        // *****************************************************
        // Item retrieving query ... put together and execute it
        // *****************************************************
        $query = 'SELECT i.title, i.id, i.catid, i.state, i.alias' . ", GROUP_CONCAT(rel.catid SEPARATOR ',') as catlist" . ' FROM #__content AS i ' . ($samelangonly || $method_types > 1 ? " LEFT JOIN #__flexicontent_items_ext AS ie on i.id=ie.item_id " : "") . ' JOIN #__flexicontent_cats_item_relations AS rel on i.id=rel.itemid ' . @$orderby_join . $where . " GROUP BY rel.itemid " . $orderby;
        $db->setQuery($query);
        $items_arr = $db->loadObjectList();
        if ($db->getErrorNum()) {
            echo $db->getErrorMsg();
            $field->html = '';
            return false;
        }
        // *******************************************************
        // Create category tree to use for selecting related items
        // *******************************************************
        require_once JPATH_ROOT . DS . "components" . DS . "com_flexicontent" . DS . "classes" . DS . "flexicontent.categories.php";
        $tree = flexicontent_cats::getCategoriesTree();
        // Get categories without filtering
        if ($allowed_cats) {
            foreach ($allowed_cats as $catid) {
                $allowedtree[$catid] = $tree[$catid];
            }
        }
        if ($disallowed_cats) {
            foreach ($disallowed_cats as $catid) {
                unset($tree[$catid]);
            }
            $allowedtree =& $tree;
        }
        if (!$allowed_cats && !$disallowed_cats) {
            $allowedtree =& $tree;
        }
        // *****************************************
        // Create field's HTML display for item form
        // *****************************************
        static $common_css_js_added = false;
        if (!$common_css_js_added) {
            $common_css_js_added = true;
            flexicontent_html::loadFramework('select2');
            $css = '' . '.fcrelation_field_used_items, .fcrelation_field_unused_items, .fcrelation_field_controls { display:inline-block; float:left !important; margin: 0 0 8px 0; }' . '.fcrelation_field_used_items.fc_vertical,   .fcrelation_field_unused_items.fc_vertical   { min-width: 100%; }' . '.fcrelation_field_used_items.fc_horizontal, .fcrelation_field_unused_items.fc_horizontal { margin: 8px 0%; }' . '.fcrelation_field_controls.fc_vertical   { min-width: 100%; }' . '.fcrelation_field_controls.fc_horizontal { max-width:6%; margin: 48px 1% 0 1%; width: auto; }' . '.fcrelation_field_controls.fc_horizontal span.fcrelation_btn { float: left !important; clear: both !important; }' . '.fcfield-placement-h.fc_horizontal { display: none !important; }' . '.fcfield-placement-v.fc_vertical { display: none !important; }' . '.fcrelation_field_filters { display:inline-block; float:left !important; }' . '.fcrelation_field_filters span.label { min-width: 140px; }' . '.fcrelation_field_used_items select, .fcrelation_field_unused_items select { min-width: 100%; margin:0px; }';
            if ($css) {
                $document->addStyleDeclaration($css);
            }
        }
        // The split up the items
        $items_options = '';
        $items_options_select = '';
        $items_options_unused = '';
        $state_shortname = array(1 => 'P', 0 => 'U', -1 => 'A', -3 => 'PE', -4 => 'OQ', -5 => 'IP');
        foreach ($items_arr as $itemdata) {
            $itemtitle = mb_strlen($itemdata->title) > $maxtitlechars ? mb_substr($itemdata->title, 0, $maxtitlechars) . "..." : $itemdata->title;
            if ($prepend_item_state) {
                $statestr = "[" . @$state_shortname[$itemdata->state] . "] ";
                $itemtitle = $statestr . $itemtitle . " ";
                //.$itemdata->catlist;
            }
            $itemcat_arr = explode(",", $itemdata->catlist);
            $classes_str = "";
            $itemid = $itemdata->id;
            foreach ($itemcat_arr as $catid) {
                $classes_str .= " " . "cat_" . $catid;
            }
            if (isset($_itemids_catids[$itemid])) {
                $items_options .= '<option class="' . $classes_str . '" value="' . $_itemids_catids[$itemid]->value . '" >' . $itemtitle . '</option>' . "\n";
                $items_options_select .= '<option selected="selected" class="' . $classes_str . '" value="' . $_itemids_catids[$itemid]->value . '" >' . $itemtitle . '</option>' . "\n";
            } else {
                $items_options_unused .= '<option class="' . $classes_str . '" value="' . $itemid . '" >' . $itemtitle . '</option>' . "\n";
            }
        }
        $cat_selected = count($allowedtree) == 1 ? reset($allowedtree) : '';
        $cat_selecor_box_style = count($allowedtree) == 1 ? 'style="display:none;" ' : '';
        $_cat_selector = flexicontent_cats::buildcatselect($allowedtree, $ri_field_name . '_fccats', $catvals = $cat_selected ? $cat_selected->id : '', $top = 2, ' class="use_select2_lib ' . $ri_field_name . '_fccats" ', $check_published = true, $check_perms = true, $actions_allowed = array('core.create', 'core.edit', 'core.edit.own'), $require_all = false, $skip_subtrees = array(), $disable_subtrees = array(), $custom_options = array('__ALL__' => 'FLEXI_RIFLD_FILTER_LIST_ALL'));
        if ($title_filter) {
            $document->addScript(JURI::root(true) . '/components/com_flexicontent/assets/js/filterlist.js');
            $_title_filtering = '' . '<input class="fcfield_textval" id="' . $ri_field_name . '_regexp" name="' . $ri_field_name . '_regexp" onKeyUp="' . $ri_field_name . '_titlefilter.set(this.value)" size="30" onfocus="if (this.value==\'' . $default_value_title_filter . '\') this.value=\'\';" onblur="if (this.value==\'\') this.value=\'' . $default_value_title_filter . '\';" value="' . $default_value_title_filter . '" />' . '<input class="fcfield-button" type="button" onclick="' . $ri_field_name . '_titlefilter.reset();this.form.' . $ri_field_name . '_regexp.value=\'\'" value="' . JText::_('FLEXI_RIFLD_RESET') . '" />';
        }
        $field->html .= '
		<div class="fcfieldval_container valuebox fcfieldval_container_' . $field->id . '">
			<span class="fcrelation_field_filters">
				
				<span class="fcrelation_field_filter_by_cat nowrap_box" ' . $cat_selecor_box_style . '>
					' . ($display_cat_filter_label ? '<span class="label">' . JText::_('FLEXI_RIFLD_FILTER_BY_CAT') . '</span>' : '') . '
					' . $_cat_selector . '
				</span>
				
				' . ($title_filter ? '
				<span class="fcrelation_field_filter_by_title nowrap_box">
					' . ($display_title_filter_label ? '<span class="label">' . JText::_('FLEXI_RIFLD_FILTER_BY_TITLE') . '</span>' : '') . '
	    		' . $_title_filtering . '
				</span>
				' : '') . '
				
			</span>
			<div class="fcclear"></div>
		';
        $initial_placement = $field->parameters->get('initial_placement', 'h');
        $placement_class = $initial_placement == 'h' ? ' fc_horizontal' : ' fc_vertical';
        $field->html .= '
			<span class="fcrelation_field_unused_items' . $placement_class . '">
				<span class="label">' . JText::_($select_items_prompt) . '</span><br/>
				<select id="' . $ri_field_name . '_visitems" name="' . $ri_field_name . '_visitems[]" multiple="multiple" class="fcfield_selectmulval" ' . $size . ' >
				</select>
			</span>
		
			<span class="fcrelation_field_controls' . $placement_class . '">
				<span id="btn-add_' . $ri_field_name . '" class="fcrelation_btn fcfield-list-add ' . $placement_class . '" title="' . JText::_('FLEXI_ADD') . '"></span>
				<span id="btn-remove_' . $ri_field_name . '" class="fcrelation_btn fcfield-list-del ' . $placement_class . '" title="' . JText::_('FLEXI_REMOVE') . '"></span>
				<span id="btn-toggle_horizontal_' . $ri_field_name . '" class="fcrelation_btn fcfield-placement-h fc_toggle ' . $placement_class . '" onclick="jQuery(this).closest(\'.valuebox\').find(\'.fc_vertical\').removeClass(\'fc_vertical\').addClass(\'fc_horizontal\');" title="' . JText::_('FLEXI_HORIZONTAL') . '"></span>
				<span id="btn-toggle_vertical_' . $ri_field_name . '" class="fcrelation_btn fcfield-placement-v fc_toggle ' . $placement_class . '" onclick="jQuery(this).closest(\'.valuebox\').find(\'.fc_horizontal\').removeClass(\'fc_horizontal\').addClass(\'fc_vertical\');" title="' . JText::_('FLEXI_VERTICAL') . '"></span>
			</span>
    	
    	<span class="fcrelation_field_used_items' . $placement_class . '">
				<span class="label">' . JText::_($selected_items_label) . '</span><br/>
				<select id="' . $ri_field_name . '" name="' . $fieldname . '" multiple="multiple" class="' . $required . '" style="display:none;" ' . $size . ' >
					' . $items_options_select . '
				</select>
				
				<select id="' . $ri_field_name . '_selitems" name="' . $ri_field_name . '_selitems[]" multiple="multiple" class="fcfield_selectmulval" ' . $size . ' >
					' . $items_options . '
				</select>
				
				<select id="' . $ri_field_name . '_hiditems" name="' . $ri_field_name . '_hiditems" style="display:none;" >
					' . $items_options_unused . '
				</select>
			</span>
		</div>
		';
        $js = ($title_filter ? ' var filteredfield, ' . $ri_field_name . '_titlefilter;' : '') . "\n\njQuery(document).ready(function() {\n\n" . ($title_filter ? '
	filteredfield = document.getElementById("' . $ri_field_name . '_visitems");
	' . $ri_field_name . '_titlefilter = new filterlist( filteredfield );
	' : '') . "\n\n  jQuery('#btn-add_" . $ri_field_name . "').click(function(){\n      jQuery('#" . $ri_field_name . "_visitems option:selected').each( function() {\n          jQuery('#" . $ri_field_name . "_selitems').append(\"<option class='\"+jQuery(this).attr('class')+\"' value='\"+jQuery(this).val()+\"'>\"+jQuery(this).text()+\"</option>\");\n          jQuery('#" . $ri_field_name . "').append(\"<option selected='selected' class='\"+jQuery(this).attr('class')+\"' value='\"+jQuery(this).val()+\"'>\"+jQuery(this).text()+\"</option>\");\n          jQuery(this).remove();\n      });\n  });\n  jQuery('#btn-remove_" . $ri_field_name . "').click(function(){\n      jQuery('#" . $ri_field_name . "_selitems option:selected').each( function() {\n          jQuery('#" . $ri_field_name . "_visitems').append(\"<option class='\"+jQuery(this).attr('class')+\"' value='\"+jQuery(this).val()+\"'>\"+jQuery(this).text()+\"</option>\");\n          jQuery(\"#" . $ri_field_name . " option[value='\"+jQuery(this).val()+\"']\").remove();\n          jQuery(this).remove();\n      });\n  });\n\n});\n\njQuery(document).ready(function() {\n\t\n\tjQuery('#" . $ri_field_name . "_fccats').change(function() {\n\t\t\n\t\tvar " . $ri_field_name . "_fccats_val = jQuery('#" . $ri_field_name . "_fccats').val();\n\t\t\n\t\t" . ($title_filter ? $ri_field_name . "_titlefilter.reset(); this.form." . $ri_field_name . "_regexp.value='';" : "") . "\n\t\t\n\t  jQuery('#" . $ri_field_name . "_visitems option').each( function() {\n\t  \tvar data = jQuery(this).val().split(':'); \n\t  \tvar itemid = data[0];\n\t  \tjQuery('#" . $ri_field_name . "_hiditems').append(\"<option class='\"+jQuery(this).attr('class')+\"' value='\"+itemid+\"'>\"+jQuery(this).text()+\"</option>\");\n\t  \tjQuery(this).remove();\n\t\t});\n\t\t\n\t  jQuery('#" . $ri_field_name . "_hiditems option').each( function() {\n\t  \tif ( " . $ri_field_name . "_fccats_val == '__ALL__' || jQuery(this).hasClass('cat_' + " . $ri_field_name . "_fccats_val ) ) {\n\t\t\t  jQuery('#" . $ri_field_name . "_visitems').append(\"<option class='\"+jQuery(this).attr('class')+\"'value='\"+jQuery(this).val()+\":\"+ " . $ri_field_name . "_fccats_val+\"'>\"+jQuery(this).text()+\"</option>\");\n\t\t\t\tjQuery(this).remove();\n\t  \t}\n\t\t});\n\t\t\n\t\t" . ($title_filter ? $ri_field_name . "_titlefilter.init();" : "") . "\n\t});\n\t" . (count($allowedtree) == 1 ? "jQuery('#" . $ri_field_name . "_fccats').trigger('change');" : "") . "\n\t\n});";
        $document->addScriptDeclaration($js);
    }
예제 #13
0
 /**
  * Method to load item data
  *
  * @access	private
  * @return	boolean	True on success
  * @since	1.0
  */
 function _loadItem($no_cache = false, $force_version = false)
 {
     if (!$this->_id) {
         return false;
     }
     // Only try to load existing item
     // Cache items retrieved, we can retrieve multiple items, for this purpose
     // (a) temporarily set JRequest variable -version- to specify loaded version (set to zero to use latest )
     // (b1) use member function function setId($id, $currcatid=0) to change primary key and then call getItem()
     // (b2) or call getItem($pk, $check_view_access=true) passing the item id and maybe also disabling read access checkings, to avoid unwanted messages/errors
     static $items = array();
     if ($no_cache) {
         // Clear item to make sure it is reloaded
         $this->_item = null;
     } else {
         if (isset($items[$this->_id])) {
             $this->_item =& $items[$this->_id];
             return (bool) $this->_item;
         }
     }
     static $unapproved_version_notice;
     $db = $this->_db;
     $app = JFactory::getApplication();
     $user = JFactory::getUser();
     $cparams = $this->_cparams;
     $task = JRequest::getVar('task', false);
     $layout = JRequest::getVar('layout', false);
     $view = JRequest::getVar('view', false);
     $option = JRequest::getVar('option', false);
     $use_versioning = $cparams->get('use_versioning', 1);
     $allow_current_version = true;
     $editjf_translations = $cparams->get('editjf_translations', 0);
     // *********************************************************************************************************
     // Retrieve item if not already retrieved, null indicates cleared item data, e.g. because of changed item id
     // *********************************************************************************************************
     if ($this->_item === null) {
         //*****************************************************
         // DECIDE VERSION and GENERATE VERSION RELATED MESSAGES
         //*****************************************************
         // Variables controlling the version loading logic
         $loadcurrent = JRequest::getVar('loadcurrent', false, 'request', 'boolean');
         // loadcurrent request flag, ignored if version specified
         $preview = JRequest::getVar('preview', false, 'request', 'boolean');
         // preview request flag for viewing latest (and possibly unapproved) version in frontend
         $version = JRequest::getVar('version', 0, 'request', 'int');
         // the item version to load
         // -- Decide the version to load: (a) the one specified by request or (b) the current one or (c) the latest one
         $current_version = FLEXIUtilities::getCurrentVersions($this->_id, true, $force = true);
         // Get current item version
         $last_version = FLEXIUtilities::getLastVersions($this->_id, true, $force = true);
         // Get last version (=latest one saved, highest version id),
         // NOTE: Setting version to zero indicates to load the current version from the normal tables and not the versioning table
         if (!$use_versioning) {
             // Force version to zero (load current version), when not using versioning mode
             $version = 0;
         } else {
             if ($force_version !== false) {
                 $version = $force_version == -1 ? $last_version : $force_version;
             } else {
                 if ($version == 0) {
                     // version request variable was NOT SET ... We need to decide to load current (version zero) or latest
                     if ($app->isAdmin() || $task == 'edit' && $option == 'com_flexicontent') {
                         // Catch cases (a) when we enable versioning mode after an item has been saved in unversioning mode, (b) loadcurrent flag is set
                         // in these case we will load CURRENT version instead of the default for the item edit form which is the LATEST (for backend/fontend)
                         $version = $current_version >= $last_version || $loadcurrent ? 0 : $last_version;
                     } else {
                         // In frontend item display the current version must be shown unless preview flag is set
                         $version = !$preview ? 0 : $last_version;
                     }
                 } else {
                     if ($version == $current_version) {
                         // Current version number given, the data from the versioning table should be the same as the data from normal tables
                         // we do not force $version to ZERO to allow testing the field data of current version from the versioning table
                         if (!$allow_current_version) {
                             $version = 0;
                         }
                         // Force zero to retrieve unversioned data
                     }
                 }
             }
         }
         // Check if not loading the current version while we are in edit form, and raise a notice to inform the user
         if ($version && $version != $current_version && $task == 'edit' && $option == 'com_flexicontent' && !$unapproved_version_notice) {
             $unapproved_version_notice = 1;
             if (!$app->isAdmin()) {
                 JError::raiseNotice(10, JText::_('FLEXI_LOADING_UNAPPROVED_VERSION_NOTICE'));
             } else {
                 JError::raiseNotice(10, JText::_('FLEXI_LOADING_UNAPPROVED_VERSION_NOTICE') . ' :: ' . JText::sprintf('FLEXI_LOADED_VERSION_INFO_NOTICE', $version, $current_version));
             }
         }
         try {
             if ($app->isAdmin()) {
                 // **********************
                 // Item Retrieval BACKEND
                 // **********************
                 $item = $this->getTable('flexicontent_items', '');
                 $result = $item->load($this->_id);
                 // try loading existing item data
                 if ($result === false) {
                     return false;
                 }
             } else {
                 // ***********************
                 // Item Retrieval FRONTEND
                 // ***********************
                 // Tables needed to be joined for calculating access
                 $joinaccess = '';
                 // Extra access columns for main category and content type (item access will be added as 'access')
                 $select_access = 'mc.access as category_access, ty.access as type_access';
                 // Access Flags for: content type, main category, item
                 if (FLEXI_J16GE) {
                     $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
                     $aid_list = implode(",", $aid_arr);
                     $select_access .= ', CASE WHEN ty.access IN (0,' . $aid_list . ') THEN 1 ELSE 0 END AS has_type_access';
                     $select_access .= ', CASE WHEN mc.access IN (0,' . $aid_list . ') THEN 1 ELSE 0 END AS has_mcat_access';
                     $select_access .= ', CASE WHEN  i.access IN (0,' . $aid_list . ') THEN 1 ELSE 0 END AS has_item_access';
                 } else {
                     $aid = (int) $user->get('aid');
                     if (FLEXI_ACCESS) {
                         $joinaccess .= ' LEFT JOIN #__flexiaccess_acl AS gt ON ty.id = gt.axo AND gt.aco = "read" AND gt.axosection = "type"';
                         $joinaccess .= ' LEFT JOIN #__flexiaccess_acl AS gc ON mc.id = gc.axo AND gc.aco = "read" AND gc.axosection = "category"';
                         $joinaccess .= ' LEFT JOIN #__flexiaccess_acl AS gi ON  i.id = gi.axo AND gi.aco = "read" AND gi.axosection = "item"';
                         $select_access .= ', CASE WHEN (gt.aro IN ( ' . $user->gmid . ' ) OR ty.access <= ' . (int) $aid . ') THEN 1 ELSE 0 END AS has_type_access';
                         $select_access .= ', CASE WHEN (gc.aro IN ( ' . $user->gmid . ' ) OR mc.access <= ' . (int) $aid . ') THEN 1 ELSE 0 END AS has_mcat_access';
                         $select_access .= ', CASE WHEN (gi.aro IN ( ' . $user->gmid . ' ) OR  i.access <= ' . (int) $aid . ') THEN 1 ELSE 0 END AS has_item_access';
                     } else {
                         $select_access .= ', CASE WHEN (ty.access <= ' . (int) $aid . ') THEN 1 ELSE 0 END AS has_type_access';
                         $select_access .= ', CASE WHEN (mc.access <= ' . (int) $aid . ') THEN 1 ELSE 0 END AS has_mcat_access';
                         $select_access .= ', CASE WHEN ( i.access <= ' . (int) $aid . ') THEN 1 ELSE 0 END AS has_item_access';
                     }
                     $select_access .= ', ';
                 }
                 // SQL date strings, current date and null date
                 $nowDate = $db->Quote(FLEXI_J16GE ? JFactory::getDate()->toSql() : JFactory::getDate()->toMySQL());
                 $nullDate = $db->Quote($db->getNullDate());
                 // Decide to limit to CURRENT CATEGORY
                 $limit_to_cid = $this->_cid ? ' AND rel.catid = ' . (int) $this->_cid : ' AND rel.catid = i.catid';
                 if (FLEXI_J16GE) {
                     // Initialize query
                     $query = $db->getQuery(true);
                     $query->select('i.*, ie.*');
                     // Item basic and extended data
                     $query->select($select_access);
                     // Access Columns and Access Flags for: content type, main category, item
                     if ($version) {
                         $query->select('ver.version_id');
                     }
                     // Versioned item viewing
                     $query->select('c.id AS catid, i.catid as maincatid');
                     // Current category id and Main category id
                     $query->select('c.title AS category_title, c.alias AS category_alias, c.lft,c.rgt');
                     // Current category data
                     $query->select('ty.name AS typename, ty.alias as typealias');
                     // Content Type data, and author data
                     $query->select('u.name AS author');
                     // Author data
                     // Rating count, Rating & Score
                     $query->select('v.rating_count as rating_count, ROUND( v.rating_sum / v.rating_count ) AS rating, ((v.rating_sum / v.rating_count)*20) as score');
                     // Item and Current Category slugs (for URL)
                     $query->select('CASE WHEN CHAR_LENGTH(i.alias) THEN CONCAT_WS(\':\', i.id, i.alias) ELSE i.id END as slug');
                     $query->select('CASE WHEN CHAR_LENGTH(c.alias) THEN CONCAT_WS(\':\', c.id, c.alias) ELSE c.id END as categoryslug');
                     // Publication Scheduled / Expired Flags
                     $query->select('CASE WHEN i.publish_up = ' . $nullDate . ' OR i.publish_up <= ' . $nowDate . ' THEN 0 ELSE 1 END as publication_scheduled');
                     $query->select('CASE WHEN i.publish_down = ' . $nullDate . ' OR i.publish_down >= ' . $nowDate . ' THEN 0 ELSE 1 END as publication_expired');
                     // From content table, and extended item table, content type table, user table, rating table, categories relation table
                     $query->from('#__content AS i');
                     $query->join('LEFT', '#__flexicontent_items_ext AS ie ON ie.item_id = i.id');
                     $query->join('LEFT', '#__flexicontent_types AS ty ON ie.type_id = ty.id');
                     $query->join('LEFT', '#__users AS u on u.id = i.created_by');
                     $query->join('LEFT', '#__content_rating AS v ON i.id = v.content_id');
                     $query->join('LEFT', '#__flexicontent_cats_item_relations AS rel ON rel.itemid = i.id' . $limit_to_cid);
                     // Join twice on category table, once for current category and once for item's main category
                     $query->join('LEFT', '#__categories AS c on c.id = rel.catid');
                     // All item's categories
                     $query->join('LEFT', '#__categories AS mc on mc.id = i.catid');
                     // Item's main category
                     // HANDLE J1.6+ ancestor category being unpublished, when badcats.id is not null,
                     // then the item is inside in an unpublished ancestor category, thus inaccessible
                     /*$query->select('CASE WHEN badcats.id is null THEN 1 ELSE 0 END AS ancestor_cats_published');
                     		$subquery = ' (SELECT cat.id as id FROM #__categories AS cat JOIN #__categories AS parent ';
                     		$subquery .= 'ON cat.lft BETWEEN parent.lft AND parent.rgt ';
                     		$subquery .= 'WHERE parent.extension = ' . $db->Quote('com_content');
                     		$subquery .= ' AND parent.published <= 0 GROUP BY cat.id)';
                     		$query->join('LEFT', $subquery . ' AS badcats ON badcats.id = c.id');*/
                     if ($version) {
                         // NOTE: version_id is used by field helper file to load the specified version, the reason for left join here is to verify that the version exists
                         $query->join('LEFT', '#__flexicontent_versions AS ver ON ver.item_id = i.id AND ver.version_id = ' . $db->Quote($version));
                     }
                     // Join on contact table, to get contact data of author
                     //$query = 'SHOW TABLES LIKE "' . JFactory::getApplication()->getCfg('dbprefix') . 'contact_details"';
                     //$db->setQuery($query);
                     //$contact_details_tbl_exists = (boolean) count($db->loadObjectList());
                     //if ( $contact_details_tbl_exists) {
                     //	$query->select('contact.id as contactid' ) ;
                     //	$query->join('LEFT','#__contact_details AS contact on contact.user_id = i.created_by');
                     //}
                     // Join over the categories to get parent category titles
                     //$query->select('parent.title as parent_title, parent.id as parent_id, parent.path as parent_route, parent.alias as parent_alias');
                     //$query->join('LEFT', '#__categories as parent ON parent.id = c.parent_id');
                     $query->where('i.id = ' . (int) $this->_id);
                     //echo $db->replacePrefix($query);
                 } else {
                     // NOTE: version_id is used by field helper file to load the specified version, the reason for left join here is to verify that the version exists
                     $version_join = $version ? ' LEFT JOIN #__flexicontent_versions AS ver ON ver.item_id = i.id AND ver.version_id = ' . $db->Quote($version) : '';
                     $where = $this->_buildItemWhere();
                     $query = 'SELECT i.*, ie.*, ' . $select_access . ($version ? 'ver.version_id,' : '') . ' c.id AS catid, i.catid as maincatid,' . ' c.published AS catpublished,' . ' c.title AS category_title, c.alias AS category_alias,' . ' ty.name as typename, ty.alias as typealias,' . ' u.name AS author, u.usertype,' . ' v.rating_count as rating_count, ROUND( v.rating_sum / v.rating_count ) AS rating, ((v.rating_sum / v.rating_count)*20) as score,' . ' 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,' . ' CASE WHEN i.publish_up = ' . $nullDate . ' OR i.publish_up <= ' . $nowDate . ' THEN 0 ELSE 1 END as publication_scheduled,' . ' CASE WHEN i.publish_down = ' . $nullDate . ' OR i.publish_down >= ' . $nowDate . ' THEN 0 ELSE 1 END as publication_expired' . ' FROM #__content AS i' . ' LEFT JOIN #__flexicontent_items_ext AS ie ON ie.item_id = i.id' . ' LEFT JOIN #__flexicontent_types AS ty ON ie.type_id = ty.id' . ' LEFT JOIN #__flexicontent_cats_item_relations AS rel ON rel.itemid = i.id' . $limit_to_cid . ' LEFT JOIN #__categories AS c ON c.id = rel.catid' . ' LEFT JOIN #__categories AS mc ON mc.id = i.catid' . ' LEFT JOIN #__users AS u ON u.id = i.created_by' . ' LEFT JOIN #__content_rating AS v ON i.id = v.content_id' . $joinaccess . $version_join . $where;
                 }
                 $db->setQuery($query);
                 // Try to execute query directly and load the data as an object
                 if (FLEXI_FISH && $task == 'edit' && $option == 'com_flexicontent' && in_array($app->getCfg('dbtype'), array('mysqli', 'mysql'))) {
                     $data = flexicontent_db::directQuery($query);
                     $data = @$data[0];
                     //$data = $db->loadObject(null, false);   // do not, translate, this is the JoomFish overridden method of Database extended Class
                 } else {
                     $data = $db->loadObject();
                 }
                 // Check for SQL error
                 if ($db->getErrorNum()) {
                     if (FLEXI_J16GE) {
                         throw new Exception($db->getErrorMsg(), 500);
                     } else {
                         JError::raiseError(500, $db->getErrorMsg());
                     }
                 }
                 //print_r($data); exit;
                 if (!$data) {
                     return false;
                 }
                 // item not found, return
                 if ($version && !$data->version_id) {
                     JError::raiseNotice(10, JText::sprintf('NOTICE: Requested item version %d was not found', $version));
                 }
                 $item =& $data;
             }
             // -- Create the description field called 'text' by appending introtext + readmore + fulltext
             $item->text = $item->introtext;
             $item->text .= JString::strlen(trim($item->fulltext)) ? '<hr id="system-readmore" />' . $item->fulltext : "";
             //echo "<br/>Current version (Frontend Active): " . $item->version;
             //echo "<br/>Version to load: ".$version;
             //echo "<br/><b> *** db title:</b> ".$item->title;
             //echo "<br/><b> *** db text:</b> ".$item->text;
             //echo "<pre>*** item data: "; print_r($item); echo "</pre>"; exit;
             // Set number of loaded version, IMPORTANT: zero means load unversioned data
             JRequest::setVar('version', $version);
             // *************************************************************************************************
             // -- Retrieve all active site languages, and create empty item translation objects for each of them
             // *************************************************************************************************
             $nn_content_tbl = FLEXI_J16GE ? 'falang_content' : 'jf_content';
             if (FLEXI_FISH) {
                 $site_languages = FLEXIUtilities::getlanguageslist();
                 $item_translations = new stdClass();
                 foreach ($site_languages as $lang_id => $lang_data) {
                     if (!$lang_id && $item->language != '*') {
                         continue;
                     }
                     $lang_data->fields = new stdClass();
                     $item_translations->{$lang_id} = $lang_data;
                 }
             }
             // **********************************
             // Retrieve and prepare JoomFish data
             // **********************************
             if (FLEXI_FISH && $task == 'edit' && $option == 'com_flexicontent') {
                 // -- Try to retrieve all joomfish data for the current item
                 $query = "SELECT jfc.language_id, jfc.reference_field, jfc.value, jfc.published " . " FROM #__" . $nn_content_tbl . " as jfc " . " WHERE jfc.reference_table='content' AND jfc.reference_id = {$this->_id} ";
                 $db->setQuery($query);
                 $translated_fields = $db->loadObjectList();
                 if ($editjf_translations == 0 && $translated_fields) {
                     // 1:disable without warning about found translations
                     $app->enqueueMessage("3rd party Joom!Fish/Falang translations detected for current item." . " You can either enable editing them or disable this message in FLEXIcontent component configuration", 'message');
                 } else {
                     if ($editjf_translations == 2) {
                         if ($db->getErrorNum()) {
                             JFactory::getApplication()->enqueueMessage(__FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($db->getErrorMsg()), 'error');
                         }
                         // -- Parse translation data according to their language
                         if ($translated_fields) {
                             // Add retrieved translated item properties
                             foreach ($translated_fields as $field_data) {
                                 $item_translations->{$field_data->language_id}->fields->{$field_data->reference_field} = new stdClass();
                                 $item_translations->{$field_data->language_id}->fields->{$field_data->reference_field}->value = $field_data->value;
                                 $found_languages[$field_data->language_id] = $item_translations->{$field_data->language_id}->name;
                             }
                             //echo "<br/>Joom!Fish translations found for: " . implode(",", $found_languages);
                         }
                         foreach ($item_translations as $lang_id => $translation_data) {
                             // Default title can be somewhat long, trim it to first word, so that it is more suitable for tabs
                             list($translation_data->name) = explode(' ', trim($translation_data->name));
                             // Create text field value for all languages
                             $translation_data->fields->text = new stdClass();
                             $translation_data->fields->text->value = @$translation_data->fields->introtext->value;
                             if (JString::strlen(trim(@$translation_data->fields->fulltext->value))) {
                                 $translation_data->fields->text->value .= '<hr id="system-readmore" />' . @$translation_data->fields->fulltext->value;
                             }
                         }
                         $item->item_translations =& $item_translations;
                     }
                 }
             }
             //echo "<pre>"; print_r($item->item_translations); exit;
             // *****************************************************
             // Overwrite item fields with the requested VERSION data
             // *****************************************************
             $item->current_version = $current_version;
             $item->last_version = $last_version;
             if ($use_versioning && $version) {
                 // Overcome possible group concat limitation
                 $query = "SET SESSION group_concat_max_len = 9999999";
                 $db->setQuery($query);
                 $db->query();
                 $query = "SELECT f.id, f.name, f.field_type, GROUP_CONCAT(iv.value SEPARATOR ',') as value, count(f.id) as valuecount, iv.field_id" . " FROM #__flexicontent_items_versions as iv " . " LEFT JOIN #__flexicontent_fields as f on f.id=iv.field_id" . " WHERE iv.version='" . $version . "' AND (f.iscore=1 OR iv.field_id=-1 OR iv.field_id=-2) AND iv.item_id='" . $this->_id . "'" . " GROUP BY f.id";
                 $db->setQuery($query);
                 $fields = $db->loadObjectList();
                 $fields = $fields ? $fields : array();
                 //echo "<br/>Overwritting fields with version: $version";
                 foreach ($fields as $f) {
                     //echo "<br/><b>{$f->field_id} : ". $f->name."</b> : "; print_r($f->value);
                     // Use versioned data, by overwriting the item data
                     $fieldname = $f->name;
                     if ($f->field_type == 'hits' || $f->field_type == 'state' || $f->field_type == 'voting') {
                         // skip fields that should not have been versioned: hits, state, voting
                         continue;
                     } else {
                         if ($f->field_type == 'version') {
                             // set version variable to indicate the loaded version
                             $item->version = $version;
                         } else {
                             if ($fieldname == 'categories' || $fieldname == 'tags') {
                                 // categories and tags must have been serialized but some earlier versions did not do it,
                                 // we will check before unserializing them, otherwise they were concatenated to a single string and use explode ...
                                 $item->{$fieldname} = ($array = @unserialize($f->value)) ? $array : explode(",", $f->value);
                             } else {
                                 if ($f->field_id == -1) {
                                     if (FLEXI_FISH) {
                                         $jfdata = unserialize($f->value);
                                         $item_lang = substr($item->language, 0, 2);
                                         foreach ($item_translations as $lang_id => $translation_data) {
                                             //echo "<br/>Adding values for: ".$translation_data->shortcode;
                                             if (empty($jfdata[$translation_data->shortcode])) {
                                                 continue;
                                             }
                                             foreach ($jfdata[$translation_data->shortcode] as $fieldname => $fieldvalue) {
                                                 //echo "<br/>".$translation_data->shortcode.": $fieldname => $fieldvalue";
                                                 if ($translation_data->shortcode != $item_lang) {
                                                     $translation_data->fields->{$fieldname} = new stdClass();
                                                     $translation_data->fields->{$fieldname}->value = $fieldvalue;
                                                 } else {
                                                     $item->{$fieldname} = $fieldvalue;
                                                 }
                                             }
                                         }
                                     }
                                 } else {
                                     if ($f->field_id == -2) {
                                         // Other item properties that were versioned, such as alias, catid, meta params, attribs
                                         $item_data = unserialize($f->value);
                                         //$item->bind($item_data);
                                         foreach ($item_data as $k => $v) {
                                             $item->{$k} = $v;
                                         }
                                     } else {
                                         if ($fieldname) {
                                             // Other fields (maybe serialized or not but we do not unserialized them, this is responsibility of the field itself)
                                             $item->{$fieldname} = $f->value;
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
                 // The text field is stored in the db as to seperate fields: introtext & fulltext
                 // So we search for the {readmore} tag and split up the text field accordingly.
                 $pattern = '#<hr\\s+id=("|\')system-readmore("|\')\\s*\\/*>#i';
                 $tagPos = preg_match($pattern, $item->text);
                 if ($tagPos == 0) {
                     $item->introtext = $item->text;
                     $item->fulltext = '';
                 } else {
                     list($item->introtext, $item->fulltext) = preg_split($pattern, $item->text, 2);
                     $item->fulltext = JString::strlen(trim($item->fulltext)) ? $item->fulltext : '';
                 }
             }
             // -- Retrieve tags field value (if not using versioning)
             if ($use_versioning && $version) {
                 // Check version value was found
                 if (!isset($item->tags) || !is_array($item->tags)) {
                     $item->tags = array();
                 }
             } else {
                 // Retrieve unversioned value
                 $query = 'SELECT DISTINCT tid FROM #__flexicontent_tags_item_relations WHERE itemid = ' . (int) $this->_id;
                 $db->setQuery($query);
                 $item->tags = FLEXI_J16GE ? $db->loadColumn() : $db->loadResultArray();
             }
             // -- Retrieve categories field value (if not using versioning)
             if ($use_versioning && $version) {
                 // Check version value was found, and is valid (above code should have produced an array)
                 if (!isset($item->categories) || !is_array($item->categories)) {
                     $item->categories = array();
                 }
             } else {
                 $query = 'SELECT DISTINCT catid FROM #__flexicontent_cats_item_relations WHERE itemid = ' . (int) $this->_id;
                 $db->setQuery($query);
                 $item->categories = FLEXI_J16GE ? $db->loadColumn() : $db->loadResultArray();
             }
             // Make sure catid is in categories array
             if (!in_array($item->catid, $item->categories)) {
                 $item->categories[] = $item->catid;
             }
             // 'cats' is an alias of categories
             $item->cats =& $item->categories;
             // *********************************************************
             // Retrieve item properties not defined in the model's CLASS
             // *********************************************************
             if (FLEXI_J16GE) {
                 $query = 'SELECT title FROM #__viewlevels WHERE id = ' . (int) $item->access;
             } else {
                 $query = 'SELECT name FROM #__groups WHERE id = ' . (int) $item->access;
             }
             $db->setQuery($query);
             $item->access_level = $db->loadResult();
             // Category access is retrieved here for J1.6+, for J1.5 we use FLEXIaccess
             if (FLEXI_J16GE) {
                 // Get category access for the item's main category, used later to determine viewing of the item
                 $query = 'SELECT access FROM #__categories WHERE id = ' . (int) $item->catid;
                 $db->setQuery($query);
                 $item->category_access = $db->loadResult();
             }
             // Typecast some properties in case LEFT JOIN returned nulls
             if (!isset($item->type_access)) {
                 $public_acclevel = !FLEXI_J16GE ? 0 : 1;
                 $item->type_access = $public_acclevel;
             }
             if (!isset($item->rating_count)) {
                 // Get category access for the item's main category, used later to determine viewing of the item
                 $query = 'SELECT ' . ' v.rating_count as rating_count, ROUND( v.rating_sum / v.rating_count ) AS rating, ((v.rating_sum / v.rating_count)*20) as score' . ' FROM #__content_rating AS v WHERE v.content_id = ' . (int) $item->id;
                 $db->setQuery($query);
                 $rating_data = $db->loadObject();
                 $item->rating_count = !$rating_data ? 0 : $rating_data->rating_count;
                 $item->rating = !$rating_data ? 0 : $rating_data->rating_count;
                 $item->score = !$rating_data ? 0 : $rating_data->score;
             }
             $item->typename = (string) @$item->typename;
             $item->typealias = (string) @$item->typealias;
             // Retrieve Creator NAME and email (used to display the gravatar)
             $query = 'SELECT name, email FROM #__users WHERE id = ' . (int) $item->created_by;
             $db->setQuery($query);
             $creator_data = $db->loadObject();
             $item->creator = $creator_data ? $creator_data->name : '';
             $item->creatoremail = $creator_data ? $creator_data->email : '';
             // Retrieve Modifier NAME
             if ($item->created_by == $item->modified_by) {
                 $item->modifier = $item->creator;
             } else {
                 $query = 'SELECT name, email FROM #__users WHERE id = ' . (int) $item->modified_by;
                 $db->setQuery($query);
                 $modifier_data = $db->loadObject();
                 $item->modifier = $modifier_data ? $modifier_data->name : '';
                 $item->modifieremail = $modifier_data ? $modifier_data->email : '';
             }
             // Clear modified Date, if it is an invalid "null" date
             if ($item->modified == $db->getNulldate()) {
                 $item->modified = null;
             }
             // ********************************************************
             // Assign to the item data member variable and cache it too
             // ********************************************************
             $this->_item =& $item;
             $items[$this->_id] =& $this->_item;
             // ******************************************************************************************************
             // Detect if current version doesnot exist in version table and add it !!! e.g. after enabling versioning
             // ******************************************************************************************************
             if ($use_versioning && $current_version > $last_version) {
                 require_once JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_flexicontent' . DS . 'models' . DS . 'flexicontent.php';
                 $fleximodel = new FlexicontentModelFlexicontent();
                 $fleximodel->addCurrentVersionData($item->id);
             }
             // return true if item was loaded successfully
             return (bool) $this->_item;
         } catch (JException $e) {
             if ($e->getCode() == 404) {
                 // Need to go thru the error handler to allow Redirect to work.
                 $msg = $e->getMessage();
                 if (FLEXI_J16GE) {
                     throw new Exception($msg, 404);
                 } else {
                     JError::raiseError(404, $msg);
                 }
             } else {
                 $this->setError($e);
                 $this->_item = false;
             }
         }
     } else {
         $items[$this->_id] =& $this->_item;
     }
     /*$session = JFactory::getSession();
     		$postdata = $session->get('item_edit_postdata', array(), 'flexicontent');
     		if (count($postdata)) {
     			$session->set('item_edit_postdata', null, 'flexicontent');
     			// ...
     		}*/
     return true;
 }
예제 #14
0
 /**
  * Creates the page's display
  *
  * @since 1.0
  */
 function display($tpl = null)
 {
     // Get Non-routing Categories, and Category Tree
     global $globalnoroute, $globalcats;
     if (!is_array($globalnoroute)) {
         $globalnoroute = array();
     }
     //initialize variables
     $dispatcher = JDispatcher::getInstance();
     $app = JFactory::getApplication();
     $session = JFactory::getSession();
     $option = JRequest::getVar('option');
     $format = JRequest::getCmd('format', 'html');
     $document = JFactory::getDocument();
     // Check for Joomla issue with system plugins creating JDocument in early events forcing it to be wrong type, when format as url suffix is enabled
     if ($format && $document->getType() != strtolower($format)) {
         echo '<div class="alert">WARNING: &nbsp; Document format should be: <b>' . $format . '</b> but current document is: <b>' . $document->getType() . '</b> <br/>Some system plugin may have forced current document type</div>';
     }
     $menus = $app->getMenu();
     $menu = $menus->getActive();
     $uri = JFactory::getURI();
     $user = JFactory::getUser();
     $aid = JAccess::getAuthorisedViewLevels($user->id);
     // Get model
     $model = $this->getModel();
     // Get category and set category parameters as VIEW's parameters (category parameters are merged with component/page/author parameters already)
     $category = $this->get('Category');
     $params = $category->parameters;
     if ($category->id) {
         $meta_params = new JRegistry($category->metadata);
     }
     // Get various data from the model
     $categories = $this->get('Childs');
     // this will also count sub-category items is if  'show_itemcount'  is enabled
     $peercats = $this->get('Peers');
     // this will also count sub-category items is if  'show_subcatcount_peercat'  is enabled
     $items = $this->get('Data');
     $total = $this->get('Total');
     $filters = $this->get('Filters');
     if ($params->get('show_comments_count', 0)) {
         $comments = $this->get('CommentsInfo');
     } else {
         $comments = null;
     }
     $alpha = $params->get('show_alpha', 1) ? $this->get('Alphaindex') : array();
     // This is somwhat expensive so calculate it only if required
     // Request variables, WARNING, must be loaded after retrieving items, because limitstart may have been modified
     $limitstart = JRequest::getInt('limitstart');
     // ********************************
     // Load needed JS libs & CSS styles
     // ********************************
     FLEXI_J30GE ? JHtml::_('behavior.framework', true) : JHTML::_('behavior.mootools');
     flexicontent_html::loadFramework('jQuery');
     flexicontent_html::loadFramework('flexi_tmpl_common');
     // Add css files to the document <head> section (also load CSS joomla template override)
     if (!$params->get('disablecss', '')) {
         $document->addStyleSheetVersion($this->baseurl . '/components/com_flexicontent/assets/css/flexicontent.css', FLEXI_VHASH);
         //$document->addCustomTag('<!--[if IE]><style type="text/css">.floattext {zoom:1;}</style><![endif]-->');
     }
     if (file_exists(JPATH_SITE . DS . 'templates' . DS . $app->getTemplate() . DS . 'css' . DS . 'flexicontent.css')) {
         $document->addStyleSheetVersion($this->baseurl . '/templates/' . $app->getTemplate() . '/css/flexicontent.css', FLEXI_VHASH);
     }
     // ************************
     // CATEGORY LAYOUT handling
     // ************************
     // (a) Decide to use mobile or normal category template layout
     $useMobile = $params->get('use_mobile_layouts', 0);
     if ($useMobile) {
         $force_desktop_layout = $params->get('force_desktop_layout', 0);
         $mobileDetector = flexicontent_html::getMobileDetector();
         $isMobile = $mobileDetector->isMobile();
         $isTablet = $mobileDetector->isTablet();
         $useMobile = $force_desktop_layout ? $isMobile && !$isTablet : $isMobile;
     }
     $_clayout = $useMobile ? 'clayout_mobile' : 'clayout';
     // (b) Get from category parameters, allowing URL override
     $clayout = JRequest::getCmd($_clayout, false);
     if (!$clayout) {
         $desktop_clayout = $params->get('clayout', 'blog');
         $clayout = !$useMobile ? $desktop_clayout : $params->get('clayout_mobile', $desktop_clayout);
     }
     // (c) Get cached template data
     $themes = flexicontent_tmpl::getTemplates($lang_files = array($clayout));
     // (d) Verify the category layout exists
     if (!isset($themes->category->{$clayout})) {
         $fixed_clayout = 'blog';
         $app->enqueueMessage("<small>Current Category Layout Template is '{$clayout}' does not exist<br>- Please correct this in the URL or in Content Type configuration.<br>- Using Template Layout: '{$fixed_clayout}'</small>", 'notice');
         $clayout = $fixed_clayout;
         FLEXIUtilities::loadTemplateLanguageFile($clayout);
         // Manually load Template-Specific language file of back fall clayout
     }
     // (e) finally set the template name back into the category's parameters
     $params->set('clayout', $clayout);
     // Get URL variables
     $layout_vars = flexicontent_html::getCatViewLayoutVars($model);
     $layout = $layout_vars['layout'];
     $authorid = $layout_vars['authorid'];
     $tagid = $layout_vars['tagid'];
     $cids = $layout_vars['cids'];
     $cid = $layout_vars['cid'];
     // Get Tag data if current layout is 'tags'
     if ($tagid) {
         $tag = $this->get('Tag');
     }
     $authordescr_item = false;
     if ($authorid && $params->get('authordescr_itemid') && $format != 'feed') {
         $authordescr_itemid = $params->get('authordescr_itemid');
     }
     // Bind Fields to items and render their display HTML, but check for document type, due to Joomla issue
     // with system plugins creating JDocument in early events forcing it to be wrong type, when format as url suffix is enabled
     if ($format != 'feed') {
         $items = FlexicontentFields::getFields($items, 'category', $params, $aid);
     }
     //Set layout
     $this->setLayout('category');
     $limit = $app->getUserStateFromRequest('com_flexicontent' . $category->id . '.category.limit', 'limit', $params->def('limit', 0), 'int');
     // Get category titles needed by pathway, this will allow Falang to translate them
     $catshelper = new flexicontent_cats($cid);
     $parents = $catshelper->getParentlist($all_cols = false);
     //echo "<pre>".print_r($parents,true)."</pre>";
     /*$parents = array();
     		if ( $cid && isset($globalcats[$cid]->ancestorsarray) ) {
     			$parent_ids = $globalcats[$cid]->ancestorsarray;
     			foreach ($parent_ids as $parent_id) $parents[] = $globalcats[$parent_id];
     		}*/
     $rootcat = (int) $params->get('rootcat');
     if ($rootcat) {
         $root_parents = $globalcats[$rootcat]->ancestorsarray;
     }
     // **********************************************************
     // Calculate a (browser window) page title and a page heading
     // **********************************************************
     // Verify menu item points to current FLEXIcontent object
     if ($menu) {
         $view_ok = 'category' == @$menu->query['view'];
         $cid_ok = $cid == (int) @$menu->query['cid'];
         $layout_ok = $layout == @$menu->query['layout'];
         // null is equal to empty string
         $authorid_ok = $authorid == (int) @$menu->query['authorid'];
         // null is equal to zero
         $tagid_ok = $tagid == (int) @$menu->query['tagid'];
         // null is equal to zero
         $menu_matches = $view_ok && $cid_ok && $layout_ok && $authorid_ok && $tagid_ok;
         //$menu_params = FLEXI_J16GE ? $menu->params : new JParameter($menu->params);  // Get active menu item parameters
     } else {
         $menu_matches = false;
     }
     // MENU ITEM matched, use its page heading (but use menu title if the former is not set)
     if ($menu_matches) {
         $default_heading = FLEXI_J16GE ? $menu->title : $menu->name;
         // Cross set (show_) page_heading / page_title for compatibility of J2.5+ with J1.5 template (and for J1.5 with J2.5 template)
         $params->def('page_heading', $params->get('page_title', $default_heading));
         $params->def('page_title', $params->get('page_heading', $default_heading));
         $params->def('show_page_heading', $params->get('show_page_title', 0));
         $params->def('show_page_title', $params->get('show_page_heading', 0));
     } else {
         // Clear some menu parameters
         //$params->set('pageclass_sfx',	'');  // CSS class SUFFIX is behavior, so do not clear it ?
         // Calculate default page heading (=called page title in J1.5), which in turn will be document title below !! ...
         switch ($layout) {
             case '':
                 $default_heading = $category->title;
                 break;
             case 'myitems':
                 $default_heading = JText::_('FLEXI_MY_CONTENT');
                 break;
             case 'author':
                 $default_heading = JText::_('FLEXI_CONTENT_BY_AUTHOR') . ': ' . JFactory::getUser($authorid)->get('name');
                 break;
             case 'tags':
                 $default_heading = JText::_('FLEXI_ITEMS_WITH_TAG') . ': ' . $tag->name;
                 break;
             case 'favs':
                 $default_heading = JText::_('FLEXI_YOUR_FAVOURED_ITEMS');
                 break;
             default:
                 $default_heading = JText::_('FLEXI_CONTENT_IN_CATEGORY');
         }
         if ($layout && $cid) {
             // Non-single category listings, limited to a specific category
             $default_heading .= ', ' . JText::_('FLEXI_IN_CATEGORY') . ': ' . $category->title;
         }
         // Decide to show page heading (=J1.5 page title) only if a custom layout is used (=not a single category layout)
         $show_default_heading = $layout ? 1 : 0;
         // Set both (show_) page_heading / page_title for compatibility of J2.5+ with J1.5 template (and for J1.5 with J2.5 template)
         $params->set('page_title', $default_heading);
         $params->set('page_heading', $default_heading);
         $params->set('show_page_heading', $show_default_heading);
         $params->set('show_page_title', $show_default_heading);
     }
     // Prevent showing the page heading if (a) IT IS same as category title and (b) category title is already configured to be shown
     if ($params->get('show_cat_title', 1)) {
         if ($params->get('page_heading') == $category->title) {
             $params->set('show_page_heading', 0);
         }
         if ($params->get('page_title') == $category->title) {
             $params->set('show_page_title', 0);
         }
     }
     // ************************************************************
     // Create the document title, by from page title and other data
     // ************************************************************
     // Use the page heading as document title, (already calculated above via 'appropriate' logic ...)
     // or the overriden custom <title> ... set via parameter
     $doc_title = empty($meta_params) ? $params->get('page_title') : $meta_params->get('page_title', $params->get('page_title'));
     // Check and prepend or append site name to page title
     if ($doc_title != $app->getCfg('sitename')) {
         if ($app->getCfg('sitename_pagetitles', 0) == 1) {
             $doc_title = JText::sprintf('JPAGETITLE', $app->getCfg('sitename'), $doc_title);
         } elseif ($app->getCfg('sitename_pagetitles', 0) == 2) {
             $doc_title = JText::sprintf('JPAGETITLE', $doc_title, $app->getCfg('sitename'));
         }
     }
     // Finally, set document title
     $document->setTitle($doc_title);
     // ************************
     // Set document's META tags
     // ************************
     // Workaround for Joomla not setting the default value for 'robots', so component must do it
     $app_params = $app->getParams();
     if ($_mp = $app_params->get('robots')) {
         $document->setMetadata('robots', $_mp);
     }
     if ($category->id) {
         // possibly not set for author items OR my items
         if ($category->metadesc) {
             $document->setDescription($category->metadesc);
         }
         if ($category->metakey) {
             $document->setMetadata('keywords', $category->metakey);
         }
         // meta_params are always set if J1.6+ and category id is set
         if ($meta_params->get('robots')) {
             $document->setMetadata('robots', $meta_params->get('robots'));
         }
         // ?? Deprecated <title> tag is used instead by search engines
         if ($app->getCfg('MetaTitle') == '1') {
             $meta_title = $meta_params->get('page_title') ? $meta_params->get('page_title') : $category->title;
             $document->setMetaData('title', $meta_title);
         }
         if ($app->getCfg('MetaAuthor') == '1') {
             if ($meta_params->get('author')) {
                 $meta_author = $meta_params->get('author');
             } else {
                 $table = JUser::getTable();
                 $meta_author = $table->load($category->created_user_id) ? $table->name : '';
             }
             $document->setMetaData('author', $meta_author);
         }
     }
     // Overwrite with menu META data if menu matched
     if ($menu_matches) {
         if ($_mp = $menu->params->get('menu-meta_description')) {
             $document->setDescription($_mp);
         }
         if ($_mp = $menu->params->get('menu-meta_keywords')) {
             $document->setMetadata('keywords', $_mp);
         }
         if ($_mp = $menu->params->get('robots')) {
             $document->setMetadata('robots', $_mp);
         }
         if ($_mp = $menu->params->get('secure')) {
             $document->setMetadata('secure', $_mp);
         }
     }
     // *********************************************************************
     // Create category link, but also consider current 'layout', and use the
     // layout specific variables so that filtering form will work properly
     // *********************************************************************
     $non_sef_link = null;
     $category_link = flexicontent_html::createCatLink($category->slug, $non_sef_link, $model);
     // ****************************************************************
     // Make sure Joomla SEF plugin has inserted a correct REL canonical
     // or that it has not insert any REL if current URL is sufficient
     // ****************************************************************
     if ($params->get('add_canonical')) {
         // Get canonical URL that SEF plugin adds, also $domain passed by reference, to get the domain configured in SEF plugin (multi-domain website)
         $domain = null;
         $defaultCanonical = flexicontent_html::getDefaultCanonical($domain);
         $domain = $domain ? $domain : $uri->toString(array('scheme', 'host', 'port'));
         // Create desired REL canonical URL
         $start = JRequest::getInt('start', '');
         $ucanonical = $domain . JRoute::_(FlexicontentHelperRoute::getCategoryRoute($category->slug) . ($start ? "&start=" . $start : ''));
         // Check if SEF plugin inserted a different REL canonical
         if ($defaultCanonical != $ucanonical) {
             // Add REL canonical only if different than current URL
             $head_obj = $document->addHeadLink(htmlspecialchars($ucanonical), 'canonical', 'rel', '');
             if ($uri->toString() == $ucanonical) {
                 unset($head_obj->_links[htmlspecialchars($ucanonical)]);
             }
             // Remove canonical inserted by SEF plugin
             unset($head_obj->_links[htmlspecialchars($defaultCanonical)]);
         }
     }
     if ($params->get('show_feed_link', 1) == 1) {
         //add alternate feed link
         $link = $non_sef_link . '&format=feed';
         $attribs = array('type' => 'application/rss+xml', 'title' => 'RSS 2.0');
         $document->addHeadLink(JRoute::_($link . '&type=rss'), 'alternate', 'rel', $attribs);
         $attribs = array('type' => 'application/atom+xml', 'title' => 'Atom 1.0');
         $document->addHeadLink(JRoute::_($link . '&type=atom'), 'alternate', 'rel', $attribs);
     }
     // ********************************************************************************************
     // Create pathway, if automatic pathways is enabled, then path will be cleared before populated
     // ********************************************************************************************
     $pathway = $app->getPathWay();
     // Clear pathway, if automatic pathways are enabled
     if ($params->get('automatic_pathways', 0)) {
         $pathway_arr = $pathway->getPathway();
         $pathway->setPathway(array());
         //$pathway->set('_count', 0);  // not needed ??
         $item_depth = 0;
         // menu item depth is now irrelevant ???, ignore it
     } else {
         $item_depth = $params->get('item_depth', 0);
     }
     // Respect menu item depth, defined in menu item
     $p = $item_depth;
     while ($p < count($parents)) {
         // Do not add the directory root category or its parents (this when coming from a directory view)
         if (!empty($root_parents) && in_array($parents[$p]->id, $root_parents)) {
             $p++;
             continue;
         }
         // Do not add to pathway unroutable categories
         if (in_array($parents[$p]->id, $globalnoroute)) {
             $p++;
             continue;
         }
         // Add current parent category
         $pathway->addItem($this->escape($parents[$p]->title), JRoute::_(FlexicontentHelperRoute::getCategoryRoute($parents[$p]->slug)));
         $p++;
     }
     //echo "<pre>"; print_r($pathway); echo "</pre>";
     $authordescr_item_html = false;
     if ($authordescr_item) {
         $flexi_html_helper = new flexicontent_html();
         $authordescr_item_html = $flexi_html_helper->renderItem($authordescr_itemid);
     }
     //echo $authordescr_item_html; exit();
     if ($clayout) {
         // Add the templates css files if availables
         if (isset($themes->category->{$clayout}->css)) {
             foreach ($themes->category->{$clayout}->css as $css) {
                 $document->addStyleSheet($this->baseurl . '/' . $css);
             }
         }
         // Add the templates js files if availables
         if (isset($themes->category->{$clayout}->js)) {
             foreach ($themes->category->{$clayout}->js as $js) {
                 $document->addScript($this->baseurl . '/' . $js);
             }
         }
         // Set the template var
         $tmpl = $themes->category->{$clayout}->tmplvar;
     } else {
         $tmpl = '.category.default';
     }
     // @TODO trigger the plugin selectively
     // and delete the plugins tags if not active
     if ($params->get('trigger_onprepare_content_cat')) {
         JPluginHelper::importPlugin('content');
         // Allow to trigger content plugins on category description
         // NOTE: for J2.5, we will trigger the plugins as if description text was an article text, using ... 'com_content.article'
         $category->text = $category->description;
         $results = $dispatcher->trigger('onContentPrepare', array('com_content.article', &$category, &$params, 0));
         JRequest::setVar('layout', $layout);
         // Restore LAYOUT variable should some plugin have modified it
         $category->description = $category->text;
     }
     // Maybe here not to import all plugins but just those for description field or add a parameter for this
     // Anyway these events are usually not very time consuming as is the the event onPrepareContent(J1.5)/onContentPrepare(J1.6+)
     JPluginHelper::importPlugin('content');
     $noroute_cats = array_flip($globalnoroute);
     $type_attribs = flexicontent_db::getTypeAttribs($force = true, $typeid = 0);
     $type_params = array();
     foreach ($items as $item) {
         $item->event = new stdClass();
         if (!isset($type_params[$item->type_id])) {
             $type_params[$item->type_id] = new JRegistry($type_attribs[$item->type_id]);
         }
         $item->params = clone $type_params[$item->type_id];
         $item->params->merge(new JRegistry($item->attribs));
         //$item->cats = isset($item->cats) ? $item->cats : array();
         // !!! The triggering of the event onPrepareContent(J1.5)/onContentPrepare(J1.6+) of content plugins
         // !!! for description field (maintext) along with all other flexicontent
         // !!! fields is handled by flexicontent.fields.php
         // !!! Had serious performance impact
         // CODE REMOVED
         // We must check if the current category is in the categories of the item ..
         $item_in_category = false;
         if ($item->catid == $category->id) {
             $item_in_category = true;
         } else {
             foreach ($item->cats as $cat) {
                 if ($cat->id == $category->id) {
                     $item_in_category = true;
                     break;
                 }
             }
         }
         // ADVANCED CATEGORY ROUTING (=set the most appropriate category for the item ...)
         // CHOOSE APPROPRIATE category-slug FOR THE ITEM !!! ( )
         if ($item_in_category && !isset($noroute_cats[$category->id])) {
             // 1. CATEGORY SLUG: CURRENT category
             // Current category IS a category of the item and ALSO routing (creating links) to this category is allowed
             $item->categoryslug = $category->slug;
         } else {
             if (!isset($noroute_cats[$item->catid])) {
                 // 2. CATEGORY SLUG: ITEM's MAIN category   (already SET, ... no assignment needed)
                 // Since we cannot use current category (above), we will use item's MAIN category
                 // ALSO routing (creating links) to this category is allowed
             } else {
                 // 3. CATEGORY SLUG: ANY ITEM's category
                 // We will use the first for which routing (creating links) to the category is allowed
                 $allcats = array();
                 foreach ($item->cats as $cat) {
                     if (!isset($noroute_cats[$cat->id])) {
                         $item->categoryslug = $globalcats[$cat->id]->slug;
                         break;
                     }
                 }
             }
         }
         // Just put item's text (description field) inside property 'text' in case the events modify the given text,
         $item->text = isset($item->fields['text']->display) ? $item->fields['text']->display : '';
         // Set the view and option to 'category' and 'com_content'  (actually view is already called category)
         JRequest::setVar('option', 'com_content');
         JRequest::setVar("isflexicontent", "yes");
         // These events return text that could be displayed at appropriate positions by our templates
         $item->event = new stdClass();
         $results = $dispatcher->trigger('onContentAfterTitle', array('com_content.category', &$item, &$params, 0));
         $item->event->afterDisplayTitle = trim(implode("\n", $results));
         $results = $dispatcher->trigger('onContentBeforeDisplay', array('com_content.category', &$item, &$params, 0));
         $item->event->beforeDisplayContent = trim(implode("\n", $results));
         $results = $dispatcher->trigger('onContentAfterDisplay', array('com_content.category', &$item, &$params, 0));
         $item->event->afterDisplayContent = trim(implode("\n", $results));
         // Set the option back to 'com_flexicontent'
         JRequest::setVar('option', 'com_flexicontent');
         // Put text back into the description field, THESE events SHOULD NOT modify the item text, but some plugins may do it anyway... , so we assign text back for compatibility
         $item->fields['text']->display =& $item->text;
     }
     // Calculate CSS classes needed to add special styling markups to the items
     flexicontent_html::calculateItemMarkups($items, $params);
     // *****************************************************
     // Remove unroutable categories from sub/peer categories
     // *****************************************************
     // sub-cats
     $_categories = array();
     foreach ($categories as $i => $cat) {
         if (in_array($cat->id, $globalnoroute)) {
             continue;
         }
         $_categories[] = $categories[$i];
     }
     $categories = $_categories;
     // peer-cats
     $_categories = array();
     foreach ($peercats as $i => $cat) {
         if (in_array($cat->id, $globalnoroute)) {
             continue;
         }
         $_categories[] = $peercats[$i];
     }
     $peercats = $_categories;
     // ************************************
     // Get some variables needed for images
     // ************************************
     $joomla_image_path = $app->getCfg('image_path', '');
     $joomla_image_url = str_replace(DS, '/', $joomla_image_path);
     $joomla_image_path = $joomla_image_path ? $joomla_image_path . DS : '';
     $joomla_image_url = $joomla_image_url ? $joomla_image_url . '/' : '';
     $phpThumbURL = $this->baseurl . '/components/com_flexicontent/librairies/phpthumb/phpThumb.php?src=';
     // **************
     // CATEGORY IMAGE
     // **************
     // category image params
     $show_cat_image = $params->get('show_description_image', 0);
     // we use different name for variable
     $cat_image_source = $params->get('cat_image_source', 2);
     // 0: extract, 1: use param, 2: use both
     $cat_link_image = $params->get('cat_link_image', 1);
     $cat_image_method = $params->get('cat_image_method', 1);
     $cat_image_width = $params->get('cat_image_width', 80);
     $cat_image_height = $params->get('cat_image_height', 80);
     $cat_default_image = $params->get('cat_default_image', '');
     if ($show_cat_image) {
         $h = '&amp;h=' . $cat_image_height;
         $w = '&amp;w=' . $cat_image_width;
         $aoe = '&amp;aoe=1';
         $q = '&amp;q=95';
         $zc = $cat_image_method ? '&amp;zc=' . $cat_image_method : '';
     }
     if ($cat_default_image) {
         $src = $this->baseurl . "/" . $joomla_image_url . $cat_default_image;
         $ext = strtolower(pathinfo($src, PATHINFO_EXTENSION));
         $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
         $conf = $w . $h . $aoe . $q . $zc . $f;
         $default_image = $phpThumbURL . $src . $conf;
         $default_image = '<img class="fccat_image" style="float:' . $cat_image_float . '" src="' . $default_image . '" alt="%s" title="%s"/>';
     } else {
         $default_image = '';
     }
     // Create category image/description/etc data
     $cat = $category;
     $image = "";
     if ($cat) {
         if ($cat->id && $show_cat_image) {
             $cat->image = $params->get('image');
             $cat->introtext =& $cat->description;
             $cat->fulltext = "";
             if ($cat_image_source && $cat->image && JFile::exists(JPATH_SITE . DS . $joomla_image_path . $cat->image)) {
                 $src = $this->baseurl . "/" . $joomla_image_url . $cat->image;
                 $ext = strtolower(pathinfo($src, PATHINFO_EXTENSION));
                 $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
                 $conf = $w . $h . $aoe . $q . $zc . $f;
                 $image = $phpThumbURL . $src . $conf;
             } else {
                 if ($cat_image_source != 1 && ($src = flexicontent_html::extractimagesrc($cat))) {
                     $ext = strtolower(pathinfo($src, PATHINFO_EXTENSION));
                     $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
                     $conf = $w . $h . $aoe . $q . $zc . $f;
                     $base_url = !preg_match("#^http|^https|^ftp|^/#i", $src) ? $this->baseurl . '/' : '';
                     $src = $base_url . $src;
                     $image = $phpThumbURL . $src . $conf;
                 }
             }
             $cat->image_src = @$src;
             // Also add image category URL for developers
             if ($image) {
                 $image = '<img class="fccat_image" src="' . $image . '" alt="' . $this->escape($cat->title) . '" title="' . $this->escape($cat->title) . '"/>';
             } else {
                 if ($default_image) {
                     $image = sprintf($default_image, $cat->title, $cat->title);
                 }
             }
             if ($cat_link_image && $image) {
                 $image = '<a href="' . JRoute::_(FlexicontentHelperRoute::getCategoryRoute($cat->slug)) . '">' . $image . '</a>';
             }
         }
         $cat->image = $image;
     }
     // ******************************
     // SUBCATEGORIES (some templates)
     // ******************************
     // sub-category image params
     $show_cat_image = $params->get('show_description_image_subcat', 1);
     // we use different name for variable
     $cat_image_source = $params->get('subcat_image_source', 2);
     // 0: extract, 1: use param, 2: use both
     $cat_link_image = $params->get('subcat_link_image', 1);
     $cat_image_method = $params->get('subcat_image_method', 1);
     $cat_image_width = $params->get('subcat_image_width', 24);
     $cat_image_height = $params->get('subcat_image_height', 24);
     $cat_default_image = $params->get('subcat_default_image', '');
     if ($show_cat_image) {
         $h = '&amp;h=' . $cat_image_height;
         $w = '&amp;w=' . $cat_image_width;
         $aoe = '&amp;aoe=1';
         $q = '&amp;q=95';
         $zc = $cat_image_method ? '&amp;zc=' . $cat_image_method : '';
     }
     if ($cat_default_image) {
         $src = $this->baseurl . "/" . $joomla_image_url . $cat_default_image;
         $ext = strtolower(pathinfo($src, PATHINFO_EXTENSION));
         $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
         $conf = $w . $h . $aoe . $q . $zc . $f;
         $default_image = $phpThumbURL . $src . $conf;
         $default_image = '<img class="fccat_image" style="float:' . $cat_image_float . '" src="' . $default_image . '" alt="%s" title="%s"/>';
     } else {
         $default_image = '';
     }
     // Create sub-category image/description/etc data
     foreach ($categories as $cat) {
         $image = "";
         if ($show_cat_image) {
             if (!is_object($cat->params)) {
                 $cat->params = new JRegistry($cat->params);
             }
             $cat->image = $cat->params->get('image');
             $cat->introtext =& $cat->description;
             $cat->fulltext = "";
             if ($cat_image_source && $cat->image && JFile::exists(JPATH_SITE . DS . $joomla_image_path . $cat->image)) {
                 $src = $this->baseurl . "/" . $joomla_image_url . $cat->image;
                 $ext = strtolower(pathinfo($src, PATHINFO_EXTENSION));
                 $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
                 $conf = $w . $h . $aoe . $q . $zc . $f;
                 $image = $phpThumbURL . $src . $conf;
             } else {
                 if ($cat_image_source != 1 && ($src = flexicontent_html::extractimagesrc($cat))) {
                     $ext = strtolower(pathinfo($src, PATHINFO_EXTENSION));
                     $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
                     $conf = $w . $h . $aoe . $q . $zc . $f;
                     $base_url = !preg_match("#^http|^https|^ftp|^/#i", $src) ? $this->baseurl . '/' : '';
                     $src = $base_url . $src;
                     $image = $phpThumbURL . $src . $conf;
                 }
             }
             $cat->image_src = @$src;
             // Also add image category URL for developers
             if ($image) {
                 $image = '<img class="fccat_image" src="' . $image . '" alt="' . $this->escape($cat->title) . '" title="' . $this->escape($cat->title) . '"/>';
             } else {
                 if ($default_image) {
                     $image = sprintf($default_image, $cat->title, $cat->title);
                 }
             }
             if ($cat_link_image && $image) {
                 $image = '<a href="' . JRoute::_(FlexicontentHelperRoute::getCategoryRoute($cat->slug)) . '">' . $image . '</a>';
             }
         }
         $cat->image = $image;
     }
     // *******************************
     // PEERCATEGORIES (some templates)
     // *******************************
     // peer-category image params
     $show_cat_image = $params->get('show_description_image_peercat', 1);
     // we use different name for variable
     $cat_image_source = $params->get('peercat_image_source', 2);
     // 0: extract, 1: use param, 2: use both
     $cat_link_image = $params->get('peercat_link_image', 1);
     $cat_image_method = $params->get('peercat_image_method', 1);
     $cat_image_width = $params->get('peercat_image_width', 24);
     $cat_image_height = $params->get('peercat_image_height', 24);
     $cat_default_image = $params->get('peercat_default_image', '');
     if ($show_cat_image) {
         $h = '&amp;h=' . $cat_image_height;
         $w = '&amp;w=' . $cat_image_width;
         $aoe = '&amp;aoe=1';
         $q = '&amp;q=95';
         $zc = $cat_image_method ? '&amp;zc=' . $cat_image_method : '';
     }
     if ($cat_default_image) {
         $src = $this->baseurl . "/" . $joomla_image_url . $cat_default_image;
         $ext = strtolower(pathinfo($src, PATHINFO_EXTENSION));
         $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
         $conf = $w . $h . $aoe . $q . $zc . $f;
         $default_image = $phpThumbURL . $src . $conf;
         $default_image = '<img class="fccat_image" style="float:' . $cat_image_float . '" src="' . $default_image . '" alt="%s" title="%s"/>';
     } else {
         $default_image = '';
     }
     // Create peer-category image/description/etc data
     foreach ($peercats as $cat) {
         $image = "";
         if ($show_cat_image) {
             if (!is_object($cat->params)) {
                 $cat->params = new JRegistry($cat->params);
             }
             $cat->image = $cat->params->get('image');
             $cat->introtext =& $cat->description;
             $cat->fulltext = "";
             if ($cat_image_source && $cat->image && JFile::exists(JPATH_SITE . DS . $joomla_image_path . $cat->image)) {
                 $src = $this->baseurl . "/" . $joomla_image_url . $cat->image;
                 $ext = strtolower(pathinfo($src, PATHINFO_EXTENSION));
                 $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
                 $conf = $w . $h . $aoe . $q . $zc . $f;
                 $image = $phpThumbURL . $src . $conf;
             } else {
                 if ($cat_image_source != 1 && ($src = flexicontent_html::extractimagesrc($cat))) {
                     $ext = strtolower(pathinfo($src, PATHINFO_EXTENSION));
                     $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
                     $conf = $w . $h . $aoe . $q . $zc . $f;
                     $base_url = !preg_match("#^http|^https|^ftp|^/#i", $src) ? $this->baseurl . '/' : '';
                     $src = $base_url . $src;
                     $image = $phpThumbURL . $src . $conf;
                 }
             }
             $cat->image_src = @$src;
             // Also add image category URL for developers
             if ($image) {
                 $image = '<img class="fccat_image" src="' . $image . '" alt="' . $this->escape($cat->title) . '" title="' . $this->escape($cat->title) . '"/>';
             } else {
                 if ($default_image) {
                     $image = sprintf($default_image, $cat->title, $cat->title);
                 }
             }
             if ($cat_link_image && $image) {
                 $image = '<a href="' . JRoute::_(FlexicontentHelperRoute::getCategoryRoute($cat->slug)) . '">' . $image . '</a>';
             }
         }
         $cat->image = $image;
     }
     // remove previous alpha index filter
     //$uri->delVar('letter');
     // remove filter variables (includes search box and sort order)
     preg_match_all('/filter[^=]*/', $uri->toString(), $matches);
     foreach ($matches[0] as $match) {
         //$uri->delVar($match);
     }
     // Build Lists
     $lists = array();
     //ordering
     $lists['filter_order'] = JRequest::getCmd('filter_order', 'i.title', 'default');
     $lists['filter_order_Dir'] = JRequest::getCmd('filter_order_Dir', 'ASC', 'default');
     $lists['filter'] = JRequest::getString('filter', '', 'default');
     // Add html to filter objects
     $form_name = 'adminForm';
     if ($filters) {
         FlexicontentFields::renderFilters($params, $filters, $form_name);
     }
     // ****************************
     // Create the pagination object
     // ****************************
     $pageNav = $this->get('pagination');
     $_revert = array('%21' => '!', '%2A' => '*', '%27' => "'", '%28' => '(', '%29' => ')');
     // URL-encode filter values
     foreach ($_GET as $i => $v) {
         if (substr($i, 0, 6) === "filter") {
             if (is_array($v)) {
                 foreach ($v as $ii => &$vv) {
                     $vv = str_replace('&', '__amp__', $vv);
                     $vv = strtr(rawurlencode($vv), $_revert);
                     $pageNav->setAdditionalUrlParam($i . '[' . $ii . ']', $vv);
                 }
                 unset($vv);
             } else {
                 $v = str_replace('&', '__amp__', $v);
                 $v = strtr(rawurlencode($v), $_revert);
                 $pageNav->setAdditionalUrlParam($i, $v);
             }
         }
     }
     $resultsCounter = $pageNav->getResultsCounter();
     // for overriding model's result counter
     // **********************************************************************
     // Print link ... must include layout and current filtering url vars, etc
     // **********************************************************************
     $curr_url = str_replace('&', '&amp;', $_SERVER['REQUEST_URI']);
     $print_link = $curr_url . (strstr($curr_url, '?') ? '&amp;' : '?') . 'pop=1&amp;tmpl=component&amp;print=1';
     $pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx'));
     $this->assignRef('layout_vars', $layout_vars);
     $this->assignRef('action', $category_link);
     $this->assignRef('print_link', $print_link);
     $this->assignRef('category', $category);
     $this->assignRef('categories', $categories);
     $this->assignRef('peercats', $peercats);
     $this->assignRef('items', $items);
     $this->assignRef('authordescr_item_html', $authordescr_item_html);
     $this->assignRef('lists', $lists);
     $this->assignRef('params', $params);
     $this->assignRef('pageNav', $pageNav);
     $this->assignRef('pageclass_sfx', $pageclass_sfx);
     $this->assignRef('pagination', $pageNav);
     // compatibility Alias for old templates
     $this->assignRef('resultsCounter', $resultsCounter);
     // for overriding model's result counter
     $this->assignRef('limitstart', $limitstart);
     // compatibility shortcut
     $this->assignRef('filters', $filters);
     $this->assignRef('comments', $comments);
     $this->assignRef('alpha', $alpha);
     $this->assignRef('tmpl', $tmpl);
     // NOTE: Moved decision of layout into the model, function decideLayout() layout variable should never be empty
     // It will consider things like: template exists, is allowed, client is mobile, current frontend user override, etc
     // !!! The following method of loading layouts, is Joomla legacy view loading of layouts
     // TODO: EXAMINE IF NEEDED to re-use these layouts, and use JLayout ??
     // Despite layout variable not being empty, there may be missing some sub-layout files,
     // e.g. category_somefilename.php for this reason we will use a fallback layout that surely has these files
     $fallback_layout = $params->get('category_fallback_layout', 'blog');
     // parameter does not exist yet
     if ($clayout != $fallback_layout) {
         $this->addTemplatePath(JPATH_COMPONENT . DS . 'templates' . DS . $fallback_layout);
         $this->addTemplatePath(JPATH_SITE . DS . 'templates' . DS . $app->getTemplate() . DS . 'html' . DS . 'com_flexicontent' . DS . 'templates' . DS . $fallback_layout);
     }
     $this->addTemplatePath(JPATH_COMPONENT . DS . 'templates' . DS . $clayout);
     $this->addTemplatePath(JPATH_SITE . DS . 'templates' . DS . $app->getTemplate() . DS . 'html' . DS . 'com_flexicontent' . DS . 'templates' . DS . $clayout);
     // **************************************************
     // increment the hit counter ONLY once per user visit
     // **************************************************
     // MOVED to flexisystem plugin due to ...
     $print_logging_info = $params->get('print_logging_info');
     if ($print_logging_info) {
         global $fc_run_times;
         $start_microtime = microtime(true);
     }
     parent::display($tpl);
     if ($print_logging_info) {
         @($fc_run_times['template_render'] += round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
     }
 }
예제 #15
0
    function display($tpl = null)
    {
        // ***********
        // Batch tasks
        // ***********
        $app = JFactory::getApplication();
        $jinput = $app->input;
        $layout = $jinput->get('layout', '', 'cmd');
        if ($layout == 'indexer') {
            $this->indexer($tpl);
            return;
        }
        // ********************
        // Initialise variables
        // ********************
        $option = $jinput->get('option', '', 'cmd');
        $view = $jinput->get('view', '', 'cmd');
        $cparams = JComponentHelper::getParams('com_flexicontent');
        $user = JFactory::getUser();
        $db = JFactory::getDBO();
        $document = JFactory::getDocument();
        // Get model
        $model = $this->getModel();
        $print_logging_info = $cparams->get('print_logging_info');
        if ($print_logging_info) {
            global $fc_run_times;
        }
        // ***********
        // Get filters
        // ***********
        $count_filters = 0;
        // Get filter vars
        $filter_order = $model->getState('filter_order');
        $filter_order_Dir = $model->getState('filter_order_Dir');
        $filter_indextype = $model->getState('filter_indextype');
        $isADV = $filter_indextype == 'advanced';
        $filter_fieldtype = $model->getState('filter_fieldtype');
        $filter_itemtype = $model->getState('filter_itemtype');
        $filter_itemstate = $model->getState('filter_itemstate');
        if ($filter_fieldtype) {
            $count_filters++;
        }
        if ($filter_itemtype) {
            $count_filters++;
        }
        if ($filter_itemstate) {
            $count_filters++;
        }
        $search = $model->getState('search');
        $search = $db->escape(trim(JString::strtolower($search)));
        $search_itemtitle = $model->getState('search_itemtitle');
        $search_itemid = $model->getState('search_itemid');
        $search_itemid = !empty($search_itemid) ? (int) $search_itemid : '';
        if ($search_itemtitle) {
            $count_filters++;
        }
        if ($search_itemid) {
            $count_filters++;
        }
        $filter_indextype = $model->getState('filter_indextype');
        $f_active['filter_fieldtype'] = (bool) $filter_fieldtype;
        $f_active['filter_itemtype'] = (bool) $filter_itemtype;
        $f_active['filter_itemstate'] = (bool) $filter_itemstate;
        $f_active['search'] = strlen($search);
        $f_active['search_itemtitle'] = strlen($search_itemtitle);
        $f_active['search_itemid'] = (bool) $search_itemid;
        // **************************
        // Add css and js to document
        // **************************
        flexicontent_html::loadFramework('select2');
        JHTML::_('behavior.tooltip');
        $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontentbackend.css');
        if (FLEXI_J30GE) {
            $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/j3x.css');
        } else {
            if (FLEXI_J16GE) {
                $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/j25.css');
            }
        }
        // *****************************
        // Get user's global permissions
        // *****************************
        $perms = FlexicontentHelperPerm::getPerm();
        // ************************
        // Create Submenu & Toolbar
        // ************************
        // Create Submenu (and also check access to current view)
        FLEXISubmenu('CanIndex');
        // Create document/toolbar titles
        $doc_title = JText::_('FLEXI_SEARCH_INDEX');
        $site_title = $document->getTitle();
        JToolBarHelper::title($doc_title, FLEXI_J16GE ? 'searchtext.png' : 'searchindex');
        $document->setTitle($doc_title . ' - ' . $site_title);
        // Create the toolbar
        $this->setToolbar();
        $types = $this->get('Typeslist');
        $fieldtypes = flexicontent_db::getFieldTypes($_grouped = false, $_usage = true, $_published = false);
        // Build select lists
        $lists = array();
        //build backend visible filter
        if ($isADV) {
            $fftypes = array();
            $fftypes[] = JHTML::_('select.option', '', '-');
            $fftypes[] = JHTML::_('select.option', 'C', JText::_('FLEXI_CORE_FIELDS'));
            $fftypes[] = JHTML::_('select.option', 'NC', JText::_('FLEXI_NON_CORE_FIELDS'));
            foreach ($fieldtypes as $field_type => $ftdata) {
                $fftypes[] = JHTML::_('select.option', $field_type, '-' . $ftdata->assigned . '- ' . $field_type);
            }
            $lists['filter_fieldtype'] = ($filter_fieldtype || 1 ? '<label class="label">' . JText::_('FLEXI_FIELD_TYPE') . '</label>' : '') . JHTML::_('select.genericlist', $fftypes, 'filter_fieldtype', 'class="use_select2_lib" size="1" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', 'value', 'text', $filter_fieldtype);
        }
        //build type select list
        $lists['filter_itemtype'] = ($filter_itemtype || 1 ? '<label class="label">' . JText::_('FLEXI_TYPE') . '</label>' : '') . flexicontent_html::buildtypesselect($types, 'filter_itemtype', $filter_itemtype, '-', 'class="use_select2_lib" size="1" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', 'filter_itemtype');
        //publish unpublished filter
        $ffstates = array();
        $ffstates[] = JHTML::_('select.option', '', '-');
        $ffstates[] = JHTML::_('select.option', 'P', JText::_('FLEXI_PUBLISHED'));
        $ffstates[] = JHTML::_('select.option', 'U', JText::_('FLEXI_UNPUBLISHED'));
        $lists['filter_itemstate'] = ($filter_itemstate || 1 ? '<label class="label">' . JText::_('FLEXI_STATE') . '</label>' : '') . JHTML::_('select.genericlist', $ffstates, 'filter_itemstate', 'class="use_select2_lib" size="1" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', 'value', 'text', $filter_itemstate);
        // build filter index type record listing
        $itn['basic'] = JText::_('FLEXI_INDEX_BASIC');
        $itn['advanced'] = JText::_('FLEXI_INDEX_ADVANCED');
        $indextypes = array();
        //foreach ($itn as $i => $v) $indextypes[] = JHTML::_('select.option', $i, $v);
        //$lists['filter_indextype'] = JHTML::_('select.radiolist', $indextypes, 'filter_indextype', 'size="1" class="inputbox" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', 'value', 'text', $filter_indextype );
        $lists['filter_indextype'] = '';
        foreach ($itn as $i => $v) {
            $checked = $filter_indextype == $i ? ' checked="checked" ' : '';
            $lists['filter_indextype'] .= '<input type="radio" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()" class="inputbox" size="1" ' . $checked . ' value="' . $i . '" id="filter_indextype' . $i . '" name="filter_indextype" />';
            $lists['filter_indextype'] .= '<label class="" id="filter_indextype' . $i . '-lbl" for="filter_indextype' . $i . '">' . $v . '</label>';
        }
        // table ordering
        $lists['order_Dir'] = $filter_order_Dir;
        $lists['order'] = $filter_order;
        // search index & item title  filter
        $lists['search'] = $search;
        $lists['search_itemtitle'] = $search_itemtitle;
        $lists['search_itemid'] = $search_itemid;
        $rows = $this->get('Data');
        // MUST BE BEFORE getCount and getPagination because it also calculates total rows
        $total = $this->get('Count');
        $pagination = $this->get('Pagination');
        $limitstart = $this->get('LimitStart');
        $js = "jQuery(document).ready(function(){";
        if ($filter_fieldtype) {
            $js .= "jQuery('.col_fieldtype').each(function(){ jQuery(this).addClass('yellow'); });";
        }
        if ($search) {
            $js .= "jQuery('.col_search').each(function(){ jQuery(this).addClass('yellow'); });";
        }
        $js .= "});";
        $document->addScriptDeclaration($js);
        $query = "SHOW VARIABLES LIKE '%ft_min_word_len%'";
        $db->setQuery($query);
        $_dbvariable = $db->loadObject();
        $ft_min_word_len = (int) @$_dbvariable->Value;
        $notice_ft_min_word_len = $app->getUserStateFromRequest($option . '.fields.notice_ft_min_word_len', 'notice_ft_min_word_len', 0, 'int');
        //if ( $cparams->get('show_usability_messages', 1) )     // Important usability messages
        //{
        $old_add_search_prefix = $app->getUserState('add_search_prefix', null);
        $add_search_prefix = $cparams->get('add_search_prefix', 0);
        $app->setUserState('add_search_prefix', $add_search_prefix);
        if ($old_add_search_prefix !== null && $old_add_search_prefix != $add_search_prefix) {
            $app->enqueueMessage('Parameter: "Searching small/common words" has changed, please recreate (just once) the search indexes, otherwise text search will not work', 'warning');
        }
        if (!$cparams->get('add_search_prefix', 0)) {
            if ($ft_min_word_len > 1 && $notice_ft_min_word_len < 10) {
                $app->setUserState($option . '.fields.notice_ft_min_word_len', $notice_ft_min_word_len + 1);
                $app->enqueueMessage("NOTE : Database limits minimum search word length (ft_min_word_len) to " . $ft_min_word_len, 'message');
                $app->enqueueMessage('Please enable: "Searching small/common words":
					<a class="btn" href="index.php?option=com_config&view=component&component=com_flexicontent&path=&"><span class="icon-options"></span>Configuration</a>
					and then click to re-INDEX both search indexes', 'notice');
                //$app->enqueueMessage(JText::_('FLEXI_USABILITY_MESSAGES_TURN_OFF'), 'message');
            }
        }
        //}
        $this->assignRef('count_filters', $count_filters);
        $this->assignRef('lists', $lists);
        $this->assignRef('pagination', $pagination);
        $this->assignRef('rows', $rows);
        $this->assignRef('total', $total);
        $this->assignRef('limitstart', $limitstart);
        $this->assignRef('f_active', $f_active);
        $this->assignRef('option', $option);
        $this->assignRef('view', $view);
        $this->assignRef('isADV', $isADV);
        $this->sidebar = FLEXI_J30GE ? JHtmlSidebar::render() : null;
        parent::display($tpl);
    }
예제 #16
0
 public static function getCategoryData(&$params)
 {
     if (!$params->get('apply_config_per_category', 0)) {
         return false;
     }
     $app = JFactory::getApplication();
     $db = JFactory::getDBO();
     $view = JRequest::getVar('view');
     $option = JRequest::getVar('option');
     $currcat_custom_display = $params->get('currcat_custom_display', 0);
     $currcat_source = $params->get('currcat_source', 0);
     // 0 item view, 1 category view, 2 both
     $isflexi_itemview = $option == 'com_flexicontent' && $view == FLEXI_ITEMVIEW;
     $isflexi_catview = $option == 'com_flexicontent' && $view == 'category';
     $currcat_valid_case = $currcat_source == 2 && ($isflexi_itemview || $isflexi_catview) || $currcat_source == 0 && $isflexi_itemview || $currcat_source == 1 && $isflexi_catview;
     if ($currcat_custom_display && $currcat_valid_case) {
         $id = JRequest::getInt('id', 0);
         // id of current item
         $cid = JRequest::getInt('cid', 0);
         // current category id of current item
         $catconf = new stdClass();
         $catconf->orderby = '';
         $catconf->fallback_maincat = $params->get('currcat_fallback_maincat', 0);
         $catconf->showtitle = $params->get('currcat_showtitle', 0);
         $catconf->showdescr = $params->get('currcat_showdescr', 0);
         $catconf->cuttitle = (int) $params->get('currcat_cuttitle', 40);
         $catconf->cutdescr = (int) $params->get('currcat_cutdescr', 200);
         $catconf->link_title = $params->get('currcat_link_title');
         $catconf->show_image = $params->get('currcat_show_image');
         $catconf->image_source = $params->get('currcat_image_source');
         $catconf->link_image = $params->get('currcat_link_image');
         $catconf->image_width = (int) $params->get('currcat_image_width', 80);
         $catconf->image_height = (int) $params->get('currcat_image_height', 80);
         $catconf->image_method = (int) $params->get('currcat_image_method', 1);
         $catconf->show_default_image = (int) $params->get('currcat_show_default_image', 0);
         // parameter not added yet
         $catconf->readmore = (int) $params->get('currcat_currcat_readmore', 1);
         if ($catconf->fallback_maincat && !$cid && $id) {
             $query = 'SELECT catid FROM #__content WHERE id = ' . $id;
             $db->setQuery($query);
             $cid = $db->loadResult();
         }
         if ($cid) {
             $cids = array($cid);
         }
     }
     if (empty($cids)) {
         $catconf = new stdClass();
         // Check if using a dynamic set of categories, that was decided by getItems()
         $dynamic_cids = $params->get('dynamic_catids', false);
         $static_cids = $params->get('catids', array());
         $cids = $dynamic_cids ? unserialize($dynamic_cids) : $static_cids;
         $cids = !is_array($cids) ? array($cids) : $cids;
         $catconf->orderby = $params->get('cats_orderby', 'alpha');
         $catconf->showtitle = $params->get('cats_showtitle', 0);
         $catconf->showdescr = $params->get('cats_showdescr', 0);
         $catconf->cuttitle = (int) $params->get('cats_cuttitle', 40);
         $catconf->cutdescr = (int) $params->get('cats_cutdescr', 200);
         $catconf->link_title = $params->get('cats_link_title');
         $catconf->show_image = $params->get('cats_show_image');
         $catconf->image_source = $params->get('cats_image_source');
         $catconf->link_image = $params->get('cats_link_image');
         $catconf->image_width = (int) $params->get('cats_image_width', 80);
         $catconf->image_height = (int) $params->get('cats_image_height', 80);
         $catconf->image_method = (int) $params->get('cats_image_method', 1);
         $catconf->show_default_image = (int) $params->get('cats_show_default_image', 0);
         // parameter not added yet
         $catconf->readmore = (int) $params->get('cats_readmore', 1);
     }
     if (empty($cids) || !count($cids)) {
         return false;
     }
     // initialize variables
     $orderby = '';
     if ($catconf->orderby) {
         $orderby = flexicontent_db::buildCatOrderBy($params, $catconf->orderby, $request_var = '', $config_param = '', $cat_tbl_alias = 'c', $user_tbl_alias = 'u', $default_order = '', $default_order_dir = '');
     }
     $query = 'SELECT c.id, c.title, c.description, c.params ' . (FLEXI_J16GE ? '' : ', c.image ') . ', CASE WHEN CHAR_LENGTH(c.alias) THEN CONCAT_WS(\':\', c.id, c.alias) ELSE c.id END as categoryslug' . ' FROM #__categories AS c' . (FLEXI_J16GE ? ' LEFT JOIN #__users AS u ON u.id = c.created_user_id' : '') . ' WHERE c.id IN (' . implode(',', $cids) . ')' . $orderby;
     $db->setQuery($query);
     $catdata_arr = $db->loadObjectList('id');
     if ($db->getErrorNum()) {
         JFactory::getApplication()->enqueueMessage(__FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($db->getErrorMsg()), 'error');
     }
     if (!$catdata_arr) {
         return false;
     }
     $joomla_image_path = $app->getCfg('image_path', FLEXI_J16GE ? '' : 'images' . DS . 'stories');
     foreach ($catdata_arr as $i => $catdata) {
         $catdata->params = new JRegistry($catdata->params);
         // Category Title
         $catdata->title = flexicontent_html::striptagsandcut($catdata->title, $catconf->cuttitle);
         $catdata->showtitle = $catconf->showtitle;
         // Category image
         $catdata->image = FLEXI_J16GE ? $catdata->params->get('image') : $catdata->image;
         $catimage = "";
         if ($catconf->show_image) {
             $catdata->introtext =& $catdata->description;
             $catdata->fulltext = "";
             if ($catconf->image_source && $catdata->image && JFile::exists(JPATH_SITE . DS . $joomla_image_path . DS . $catdata->image)) {
                 $src = JURI::base(true) . "/" . $joomla_image_path . "/" . $catdata->image;
                 $h = '&amp;h=' . $catconf->image_height;
                 $w = '&amp;w=' . $catconf->image_width;
                 $aoe = '&amp;aoe=1';
                 $q = '&amp;q=95';
                 $zc = $catconf->image_method ? '&amp;zc=' . $catconf->image_method : '';
                 $ext = strtolower(pathinfo($src, PATHINFO_EXTENSION));
                 $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
                 $conf = $w . $h . $aoe . $q . $zc . $f;
                 $catimage = JURI::base() . 'components/com_flexicontent/librairies/phpthumb/phpThumb.php?src=' . $src . $conf;
             } else {
                 if ($catconf->image_source != 1 && ($src = flexicontent_html::extractimagesrc($catdata))) {
                     $h = '&amp;h=' . $catconf->image_height;
                     $w = '&amp;w=' . $catconf->image_width;
                     $aoe = '&amp;aoe=1';
                     $q = '&amp;q=95';
                     $zc = $catconf->image_method ? '&amp;zc=' . $catconf->image_method : '';
                     $ext = strtolower(pathinfo($src, PATHINFO_EXTENSION));
                     $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
                     $conf = $w . $h . $aoe . $q . $zc . $f;
                     $base_url = !preg_match("#^http|^https|^ftp|^/#i", $src) ? JURI::base(true) . '/' : '';
                     $catimage = JURI::base() . 'components/com_flexicontent/librairies/phpthumb/phpThumb.php?src=' . $base_url . $src . $conf;
                 }
             }
             $catdata->image = $catimage;
         }
         // Category Description
         if (!$catconf->showdescr) {
             unset($catdata->description);
         } else {
             $catdata->description = flexicontent_html::striptagsandcut($catdata->description, $catconf->cutdescr);
         }
         // Category Links (title and image links)
         if ($catconf->link_title || $catconf->link_image || $catconf->readmore) {
             $catlink = JRoute::_(FlexicontentHelperRoute::getCategoryRoute($catdata->categoryslug));
             $catdata->titlelink = $catlink;
             $catdata->imagelink = $catlink;
         }
         $catdata->conf = $catconf;
     }
     return $catdata_arr;
 }
예제 #17
0
 /**
  * Method to build the part of WHERE clause related to Alpha Index
  *
  * @access private
  * @return array
  */
 function _buildFiltersWhere()
 {
     global $fc_catview;
     $app = JFactory::getApplication();
     $option = JRequest::getVar('option');
     $cparams = $this->_params;
     $db = $this->_db;
     $filters_where = array();
     // Get value of search text ('filter') from URL or SESSION (which is set new value if not already set)
     // *** Commented out to get variable only by HTTP GET or POST
     // thus supporting FULL PAGE CACHING (e.g. Joomla's system plugin 'Cache')
     /*if (!$this->_layout) {
     			$text  = $app->getUserStateFromRequest( $option.'.category'.$this->_id.'.filter', 'filter', '', 'string' );
     		} else if ($this->_layout=='author') {
     			$text  = $app->getUserStateFromRequest( $option.'.author'.$this->_authorid.'.filter', 'filter', '', 'string' );
     		} else if ($this->_layout=='mcats') {
     			$text  = $app->getUserStateFromRequest( $option.'.mcats'.$this->_menu_itemid.'.filter', 'filter', '', 'string' );
     		} else if ($this->_layout=='myitems') {
     			$text  = $app->getUserStateFromRequest( $option.'.myitems'.$this->_menu_itemid.'.filter', 'filter', '', 'string' );
     		} else if ($this->_layout=='favs') {
     			$text  = $app->getUserStateFromRequest( $option.'favs'.$this->_menu_itemid.'.filter', 'filter', '', 'string' );
     		} else if ($this->_layout=='tags') {
     			$text  = $app->getUserStateFromRequest( $option.'tags'.$this->_menu_itemid.'.filter', 'filter', '', 'string' );
     		} else {
     			$text  = JRequest::getString('filter', '', 'default');
     		}*/
     // ****************************************
     // Create WHERE clause part for Text Search
     // ****************************************
     $text = JRequest::getString('filter', '', 'default');
     //$text = $this->_params->get('use_search') ? $text : '';
     // Check for LIKE %word% search, for languages without spaces
     $filter_word_like_any = $cparams->get('filter_word_like_any', 0);
     if ($filter_word_like_any) {
         $phrase = JRequest::getVar('searchphrase', 'any', 'default');
     } else {
         $phrase = JRequest::getVar('searchphrase', 'exact', 'default');
     }
     $si_tbl = 'flexicontent_items_ext';
     $text = trim($text);
     if (strlen($text)) {
         $ts = 'ie';
         $escaped_text = FLEXI_J16GE ? $db->escape($text, true) : $db->getEscaped($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':
                 $words = preg_split('/\\s\\s*/u', $text);
                 $stopwords = array();
                 $shortwords = array();
                 $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 = FLEXI_J16GE ? $db->escape($newtext, true) : $db->getEscaped($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();
                 $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 = FLEXI_J16GE ? $db->escape($newtext, true) : $db->getEscaped($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:
                 // Check for LIKE %word% search, for languages without spaces
                 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();
                     $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 = FLEXI_J16GE ? $db->escape($newtext, true) : $db->getEscaped($newtext, true);
                     $quoted_text = $db->Quote($quoted_text, false);
                     $_text_match = ' MATCH (' . $ts . '.search_index) AGAINST (' . $quoted_text . ' IN BOOLEAN MODE) ';
                 }
                 break;
         }
         $filters_where['search'] = ' AND ' . $_text_match;
     }
     // Get filters these are EITHER (a) all filters (to do active only) OR (b) Locked filters
     // USING all filters here to allow filtering via module, thus category view can be filtered even if 'use_filters' is OFF
     $shown_filters = FlexicontentFields::getFilters('filters', '__ALL_FILTERS__', $cparams, $check_access = true);
     $locked_filters = FlexicontentFields::getFilters('persistent_filters', 'use_persistent_filters', $cparams, $check_access = false);
     $filters = array();
     if ($shown_filters) {
         foreach ($shown_filters as $_filter) {
             $filters[] = $_filter;
         }
     }
     if ($locked_filters) {
         foreach ($locked_filters as $_filter) {
             $filters[] = $_filter;
         }
     }
     // Get SQL clause for filtering via each field
     if ($filters) {
         foreach ($filters as $filter) {
             // Get filter values, setting into appropriate session variables
             // *** Commented out to get variable only by HTTP GET or POST thus supporting FULL PAGE CACHING (e.g. Joomla's system plugin 'Cache')
             /*if (!$this->_layout) {
             			$filt_vals 	= $app->getUserStateFromRequest( $option.'.category'.$this->_id.'.filter_'.$filter->id, 'filter_'.$filter->id, '', '' );
             		} else if ($this->_layout=='author') {
             			$filt_vals  = $app->getUserStateFromRequest( $option.'.author'.$this->_authorid.'.filter_'.$filter->id, 'filter_'.$filter->id, '', '' );
             		} else if ($this->_layout=='mcats') {
             			$filt_vals  = $app->getUserStateFromRequest( $option.'.mcats'.$this->_menu_itemid.'.filter_'.$filter->id, 'filter_'.$filter->id, '', '' );
             		} else if ($this->_layout=='myitems') {
             			$filt_vals  = $app->getUserStateFromRequest( $option.'.myitems'.$this->_menu_itemid.'.filter_'.$filter->id, 'filter_'.$filter->id, '', '' );
             		} else if ($this->_layout=='favs') {
             			$filt_vals  = $app->getUserStateFromRequest( $option.'.favs'.$this->_menu_itemid.'.filter_'.$filter->id, 'filter_'.$filter->id, '', '' );
             		} else if ($this->_layout=='tags') {
             			$filt_vals  = $app->getUserStateFromRequest( $option.'.tags'.$this->_menu_itemid.'.filter_'.$filter->id, 'filter_'.$filter->id, '', '' );
             		} else {
             			$filt_vals  = JRequest::getVar('filter_'.$filter->id, '', '');
             		}*/
             $filt_vals = JRequest::getVar('filter_' . $filter->id, '', '');
             // Skip filters without value
             $empty_filt_vals_array = is_array($filt_vals) && !strlen(trim(implode('', $filt_vals)));
             $empty_filt_vals_string = !is_array($filt_vals) && !strlen(trim($filt_vals));
             $allow_filtering_empty = $filter->parameters->get('allow_filtering_empty', 0);
             if (!$allow_filtering_empty && ($empty_filt_vals_array || $empty_filt_vals_string)) {
                 continue;
             }
             //echo "category model found filters: "; print_r($filt_vals);
             $filters_where[$filter->id] = $this->_getFiltered($filter, $filt_vals);
         }
     }
     return $filters_where;
 }
예제 #18
0
 /**
  * Check in a record
  *
  * @since	1.5
  */
 function checkin()
 {
     $tbl = 'flexicontent_files';
     $redirect_url = $_SERVER['HTTP_REFERER'] ? $_SERVER['HTTP_REFERER'] : 'index.php?option=com_flexicontent&view=filemanager';
     flexicontent_db::checkin($tbl, $redirect_url, $this);
     return;
     // true;
 }
예제 #19
0
    function display($tpl = null)
    {
        // ********************
        // Initialise variables
        // ********************
        $app = JFactory::getApplication();
        $jinput = $app->input;
        $option = $jinput->get('option', '', 'cmd');
        $view = $jinput->get('view', '', 'cmd');
        $task = $jinput->get('task', '', 'cmd');
        $cparams = JComponentHelper::getParams('com_flexicontent');
        $user = JFactory::getUser();
        $db = JFactory::getDBO();
        $document = JFactory::getDocument();
        $session = JFactory::getSession();
        // Get model
        $model = $this->getModel();
        // Some flags
        $has_zlib = function_exists("zlib_encode");
        //version_compare(PHP_VERSION, '5.4.0', '>=');
        // Get session information
        $conf = $session->get('csvimport_config', "", 'flexicontent');
        $conf = unserialize($conf ? $has_zlib ? zlib_decode(base64_decode($conf)) : base64_decode($conf) : "");
        $lineno = $session->get('csvimport_lineno', 999999, 'flexicontent');
        $session->set('csvimport_parse_log', null, 'flexicontent');
        // This is the flag if CSV file has been parsed (import form already submitted), thus to display the imported data
        // **************************
        // Add css and js to document
        // **************************
        $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontentbackend.css', FLEXI_VHASH);
        $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/j3x.css', FLEXI_VHASH);
        // Add JS frameworks
        flexicontent_html::loadFramework('select2');
        $prettycheckable_added = flexicontent_html::loadFramework('prettyCheckable');
        flexicontent_html::loadFramework('flexi-lib');
        // Add js function to overload the joomla submitform validation
        JHTML::_('behavior.formvalidation');
        // load default validation JS to make sure it is overriden
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/admin.js', FLEXI_VHASH);
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/validate.js', FLEXI_VHASH);
        // *****************************
        // Get user's global permissions
        // *****************************
        $perms = FlexicontentHelperPerm::getPerm();
        // ************************
        // Create Submenu & Toolbar
        // ************************
        // Create Submenu (and also check access to current view)
        FLEXISubmenu('CanImport');
        // Create document/toolbar titles
        $doc_title = JText::_('FLEXI_IMPORT');
        $site_title = $document->getTitle();
        JToolBarHelper::title($doc_title, 'import');
        $document->setTitle($doc_title . ' - ' . $site_title);
        // Create the toolbar
        $toolbar = JToolBar::getInstance('toolbar');
        if (!empty($conf)) {
            if ($task != 'processcsv') {
                $ctrl_task = 'import.processcsv';
                $import_btn_title = empty($lineno) ? 'FLEXI_IMPORT_START_TASK' : 'FLEXI_IMPORT_CONTINUE_TASK';
                JToolBarHelper::custom($ctrl_task, 'save.png', 'save.png', $import_btn_title, $list_check = false);
            }
            $ctrl_task = 'import.clearcsv';
            JToolBarHelper::custom($ctrl_task, 'cancel.png', 'cancel.png', 'FLEXI_IMPORT_CLEAR_TASK', $list_check = false);
        } else {
            $ctrl_task = 'import.initcsv';
            JToolBarHelper::custom($ctrl_task, 'import.png', 'import.png', 'FLEXI_IMPORT_PREPARE_TASK', $list_check = false);
            $ctrl_task = 'import.testcsv';
            JToolBarHelper::custom($ctrl_task, 'test.png', 'test.png', 'FLEXI_IMPORT_TEST_FILE_FORMAT', $list_check = false);
        }
        //JToolBarHelper::Back();
        if ($perms->CanConfig) {
            JToolBarHelper::divider();
            JToolBarHelper::spacer();
            $session = JFactory::getSession();
            $fc_screen_width = (int) $session->get('fc_screen_width', 0, 'flexicontent');
            $_width = $fc_screen_width && $fc_screen_width - 84 > 940 ? $fc_screen_width - 84 > 1400 ? 1400 : $fc_screen_width - 84 : 940;
            $fc_screen_height = (int) $session->get('fc_screen_height', 0, 'flexicontent');
            $_height = $fc_screen_height && $fc_screen_height - 128 > 550 ? $fc_screen_height - 128 > 1000 ? 1000 : $fc_screen_height - 128 : 550;
            JToolBarHelper::preferences('com_flexicontent', $_height, $_width, 'Configuration');
        }
        // Get types
        $types = flexicontent_html::getTypesList($_type_ids = false, $_check_perms = false, $_published = true);
        // Get Languages
        $languages = FLEXIUtilities::getLanguages('code');
        // Get categories
        global $globalcats;
        $categories = $globalcats;
        // ************************************
        // Decide layout to load: 'import*.php'
        // ************************************
        $this->setLayout('import');
        $this->sidebar = FLEXI_J30GE ? JHtmlSidebar::render() : null;
        // Execute the import task, load the log-like AJAX-based layout (import_process.php), to display results including any warnings
        if (!empty($conf) && $task == 'processcsv') {
            $this->assignRef('conf', $conf);
            parent::display('process');
            return;
        } else {
            if (!empty($conf)) {
                $this->assignRef('conf', $conf);
                $this->assignRef('cparams', $cparams);
                $this->assignRef('types', $types);
                $this->assignRef('languages', $languages);
                $this->assignRef('categories', $globalcats);
                parent::display('list');
                return;
            }
        }
        // Session config is empty, means import form has not been submited, display the form
        // We will display import form which is not 'default.php', it is 'import.php'
        // else ...
        // Check is session table DATA column is not mediumtext (16MBs, it can be 64 KBs ('text') in some sites that were not properly upgraded)
        $tblname = 'session';
        $dbprefix = $app->getCfg('dbprefix');
        $dbname = $app->getCfg('db');
        $db->setQuery("SELECT COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '" . $dbname . "' AND TABLE_NAME = '" . $dbprefix . $tblname . "'");
        $jession_coltypes = $db->loadAssocList('COLUMN_NAME');
        $_dataColType = strtolower($jession_coltypes['data']['DATA_TYPE']);
        $_dataCol_wrongSize = $_dataColType != 'mediumtext' && $_dataColType != 'longtext';
        // If data type is "text" it is safe to assume that it can be converted to "mediumtext",
        // since "text" means that session table is not memory storage,
        // plus it is already stored externally aka operation will be quick ?
        /*if ($_dataCol_wrongSize && $_dataColType == 'text')
        		{
        			$db->setQuery("ALTER TABLE `#__session` MODIFY `data` MEDIUMTEXT");
        			$db->execute();
        			$_dataCol_wrongSize = false;
        		}*/
        if ($_dataCol_wrongSize) {
            $app->enqueueMessage("Joomla DB table: <b>'session'</b> has a <b>'data'</b> column with type: <b>'" . $_dataColType . "'</b>, instead of expected type <b>'mediumtext'</b>. Trying to import large data files may fail", "notice");
        }
        $formvals = array();
        // Retrieve Basic configuration
        $formvals['type_id'] = $model->getState('type_id');
        $formvals['language'] = $model->getState('language');
        $formvals['state'] = $model->getState('state');
        $formvals['access'] = $model->getState('access');
        // Main and secondary categories, tags
        $formvals['maincat'] = $model->getState('maincat');
        $formvals['maincat_col'] = $model->getState('maincat_col');
        $formvals['seccats'] = $model->getState('seccats');
        $formvals['seccats_col'] = $model->getState('seccats_col');
        $formvals['tags_col'] = $model->getState('tags_col');
        // Publication: Author/modifier
        $formvals['created_by_col'] = $model->getState('created_by_col');
        $formvals['modified_by_col'] = $model->getState('modified_by_col');
        // Publication: META data
        $formvals['metadesc_col'] = $model->getState('metadesc_col');
        $formvals['metakey_col'] = $model->getState('metakey_col');
        // Publication: dates
        $formvals['modified_col'] = $model->getState('modified_col');
        $formvals['created_col'] = $model->getState('modified_col');
        $formvals['publish_up_col'] = $model->getState('publish_up_col');
        $formvals['publish_down_col'] = $model->getState('publish_down_col');
        // Advanced configuration
        $formvals['ignore_unused_cols'] = $model->getState('ignore_unused_cols');
        $formvals['id_col'] = $model->getState('id_col');
        $formvals['items_per_step'] = $model->getState('items_per_step');
        // CSV file format
        $formvals['mval_separator'] = $model->getState('mval_separator');
        $formvals['mprop_separator'] = $model->getState('mprop_separator');
        $formvals['field_separator'] = $model->getState('field_separator');
        $formvals['enclosure_char'] = $model->getState('enclosure_char');
        $formvals['record_separator'] = $model->getState('record_separator');
        $formvals['debug_records'] = $model->getState('debug_records');
        // ******************
        // Create form fields
        // ******************
        $lists['type_id'] = flexicontent_html::buildtypesselect($types, 'type_id', $formvals['type_id'], true, 'class="required use_select2_lib"', 'type_id');
        $actions_allowed = array('core.create');
        // Creating categorories tree for item assignment, we use the 'create' privelege
        // build the main category select list
        $attribs = 'class="use_select2_lib required"';
        $fieldname = 'maincat';
        $lists['maincat'] = flexicontent_cats::buildcatselect($categories, $fieldname, $formvals['maincat'], 2, $attribs, false, true, $actions_allowed);
        // build the secondary categories select list
        $class = "use_select2_lib";
        $attribs = 'multiple="multiple" size="10" class="' . $class . '"';
        $fieldname = 'seccats[]';
        $lists['seccats'] = flexicontent_cats::buildcatselect($categories, $fieldname, $formvals['seccats'], false, $attribs, false, true, $actions_allowed, $require_all = true);
        // build languages list
        // Retrieve author configuration
        $authorparams = flexicontent_db::getUserConfig($user->id);
        $allowed_langs = $authorparams->get('langs_allowed', null);
        $allowed_langs = !$allowed_langs ? null : FLEXIUtilities::paramToArray($allowed_langs);
        // We will not use the default getInput() function of J1.6+ since we want to create a radio selection field with flags
        // we could also create a new class and override getInput() method but maybe this is an overkill, we may do it in the future
        $lists['languages'] = flexicontent_html::buildlanguageslist('language', ' style="vertical-align:top;" onchange="var m=jQuery(\'#fc_import_about_langcol\'); this.value ? m.hide(600) : m.show(600);"', $formvals['language'], 6, $allowed_langs, $published_only = true, $disable_langs = null, $add_all = true, $conf = array('required' => true)) . '
			<span class="fc-mssg-inline fc-note fc-nobgimage" id="fc_import_about_langcol" style="display:none;">
				' . JText::_('FLEXI_USE_LANGUAGE_COLUMN_TIP') . '
			</span>';
        $lists['states'] = flexicontent_html::buildstateslist('state', ' style="vertical-align:top;" onchange="var m=jQuery(\'#fc_import_about_statecol\'); this.value ? m.hide(600) : m.show(600);"', $formvals['state'], 2) . '<span class="fc-mssg-inline fc-note fc-nobgimage" id="fc_import_about_statecol" style="display:none;">
				' . JText::_('FLEXI_USE_STATE_COLUMN_TIP') . '
			</span>';
        // build access level filter
        $access_levels = JHtml::_('access.assetgroups');
        array_unshift($access_levels, JHtml::_('select.option', '0', "Use 'access' column"));
        array_unshift($access_levels, JHtml::_('select.option', '', 'FLEXI_SELECT_ACCESS_LEVEL'));
        $fieldname = 'access';
        // make multivalue
        $elementid = 'access';
        $attribs = 'class="required use_select2_lib"';
        $lists['access'] = JHTML::_('select.genericlist', $access_levels, $fieldname, $attribs, 'value', 'text', $formvals['access'], $elementid, $translate = true);
        // Ignore warnings because component may not be installed
        $warnHandlers = JERROR::getErrorHandling(E_WARNING);
        JERROR::setErrorHandling(E_WARNING, 'ignore');
        // Reset the warning handler(s)
        foreach ($warnHandlers as $mode) {
            JERROR::setErrorHandling(E_WARNING, $mode);
        }
        // ********************************************************************************
        // Get field names (from the header line (row 0), and remove it form the data array
        // ********************************************************************************
        $file_field_types_list = '"image","file"';
        $q = 'SELECT id, name, label, field_type FROM #__flexicontent_fields AS fi' . ' WHERE fi.field_type IN (' . $file_field_types_list . ')';
        $db->setQuery($q);
        $file_fields = $db->loadObjectList('name');
        //assign data to template
        $this->assignRef('model', $model);
        $this->assignRef('lists', $lists);
        $this->assignRef('user', $user);
        $this->assignRef('cparams', $cparams);
        $this->assignRef('file_fields', $file_fields);
        $this->assignRef('formvals', $formvals);
        parent::display($tpl);
    }
 /**
  * Method to save language associations
  *
  * @return  boolean True if successful
  */
 static function saveAssociations(&$item, &$data, $context)
 {
     $assoc = flexicontent_db::useAssociations();
     if (!$assoc) {
         return true;
     }
     // **********************************
     // Prepare / check associations array
     // **********************************
     // Unset empty associations from associations array, to avoid save them in the associations table
     $associations = isset($data['associations']) ? $data['associations'] : array();
     foreach ($associations as $tag => $id) {
         if (empty($id)) {
             unset($associations[$tag]);
         }
     }
     // Raise notice that associations should be empty if language of current item is '*' (ALL)
     $all_language = $item->language == '*';
     if ($all_language && !empty($associations)) {
         JError::raiseNotice(403, JText::_('FLEXI_ERROR_ALL_LANGUAGE_ASSOCIATED'));
     }
     // Make sure that current item id, is the association id of the language of the current item
     $associations[$item->language] = $item->id;
     // Make sure associations ids are integers
     JArrayHelper::toInteger($associations);
     // ***********************
     // Delete old associations
     // ***********************
     $db = JFactory::getDbo();
     $query = $db->getQuery(true)->delete('#__associations')->where($db->quoteName('context') . ' = ' . $db->quote($context . '.item'))->where($db->quoteName('id') . ' IN (' . implode(',', $associations) . ')');
     $db->setQuery($query);
     $db->execute();
     if ($error = $db->getErrorMsg()) {
         $this->setError($error);
         return false;
     }
     // ********************
     // Add new associations
     // ********************
     // Only add language associations if item language is not '*' (ALL)
     if ($all_language || !count($associations)) {
         return true;
     }
     $key = md5(json_encode($associations));
     $query->clear()->insert('#__associations');
     foreach ($associations as $id) {
         $query->values($id . ',' . $db->quote($context . '.item') . ',' . $db->quote($key));
     }
     $db->setQuery($query);
     $db->execute();
     if ($error = $db->getErrorMsg()) {
         $this->setError($error);
         return false;
     }
     return true;
 }
예제 #21
0
    function display($tpl = null)
    {
        // Initialise variables
        $app = JFactory::getApplication();
        $option = JRequest::getVar('option');
        $db = JFactory::getDBO();
        $document = JFactory::getDocument();
        $user = JFactory::getUser();
        $use_jquery_sortable = true;
        $type = JRequest::getVar('type', 'items', '', 'word');
        $folder = JRequest::getVar('folder', 'default', '', 'cmd');
        $ismodal = JRequest::getVar('ismodal', 'default', '', 'int');
        FLEXIUtilities::loadTemplateLanguageFile($folder);
        //Get data from the model
        $layout = $this->get('Data');
        $conf = $this->get('LayoutConf');
        $fields = $this->get('Fields');
        $fbypos = $this->get('FieldsByPositions');
        $used = $this->get('UsedFields');
        $contentTypes = $this->get('TypesList');
        //$fieldTypes = $this->get( 'FieldTypesList' );
        $fieldTypes = flexicontent_db::getFieldTypes($_grouped = true, $_usage = false, $_published = false);
        // Field types with content type ASSIGNMENT COUNTING
        // Create CONTENT TYPE SELECTOR
        foreach ($fields as $field) {
            $field->type_ids = !empty($field->reltypes) ? explode(",", $field->reltypes) : array();
        }
        $options = array();
        $options[] = JHTML::_('select.option', '', JText::_('FLEXI_ALL'));
        foreach ($contentTypes as $contentType) {
            $options[] = JHTML::_('select.option', $contentType->id, JText::_($contentType->name));
        }
        $fieldname = $elementid = 'content_type__au__';
        $attribs = ' onchange="filterFieldList(\'%s\', \'%s\', \'%s\');" class="use_select2_lib" ';
        $content_type_select = JHTML::_('select.genericlist', $options, $fieldname, $attribs, 'value', 'text', '', $elementid);
        // Create FIELD TYPE SELECTOR
        $ALL = mb_strtoupper(JText::_('FLEXI_ALL'), 'UTF-8') . ' : ';
        $fftypes = array();
        $fftypes[] = array('value' => '', 'text' => JText::_('FLEXI_ALL'));
        //$fftypes[] = array('value'=>'BV', 'text'=>$ALL . JText::_( 'FLEXI_BACKEND_FIELDS' ) );
        //$fftypes[] = array('value'=>'C',  'text'=>$ALL . JText::_( 'FLEXI_CORE_FIELDS' ) );
        //$fftypes[] = array('value'=>'NC', 'text'=>$ALL . JText::_( 'FLEXI_NON_CORE_FIELDS' ));
        foreach ($fieldTypes as $field_group => $ft_types) {
            $fftypes[] = $field_group;
            foreach ($ft_types as $field_type => $ftdata) {
                $fftypes[] = array('value' => $ftdata->field_type, 'text' => $ftdata->friendly);
            }
            $fftypes[] = '';
        }
        $fieldname = $elementid = 'field_type__au__';
        $attribs = ' class="use_select2_lib" onchange="filterFieldList(\'%s\', \'%s\', \'%s\');"';
        $field_type_select = flexicontent_html::buildfieldtypeslist($fftypes, $fieldname, '', $_grouped ? 1 : 0, $attribs, $elementid);
        if (isset($layout->positions)) {
            $sort = array();
            $jssort = array();
            $idsort = array();
            $sort[0] = 'sortablecorefields';
            $sort[1] = 'sortableuserfields';
            $i = 2;
            $count = -1;
            foreach ($layout->positions as $pos) {
                $count++;
                if (isset($layout->attributes[$count]) && isset($layout->attributes[$count]['readonly'])) {
                    continue;
                }
                $sort[$i] = 'sortable-' . $pos;
                $idsort[$i] = $pos;
                $i++;
            }
            foreach ($idsort as $k => $v) {
                if ($k > 1) {
                    $jssort[] = 'storeordering(jQuery("#sortable-' . $v . '"))';
                }
            }
            $positions = implode(',', $idsort);
            $jssort = implode("; ", $jssort);
            $sortable_ids = "#" . implode(",#", $sort);
            $js = "\n\t\t\tjQuery(function() {\n\t\t\t\tmy = jQuery( \"{$sortable_ids}\" ).sortable({\n\t\t\t\t\tconnectWith: \"" . $sortable_ids . "\",\n\t\t\t\t\tupdate: function(event, ui) {\n\t\t\t\t\t\tif(ui.sender) {\n\t\t\t\t\t\t\tstoreordering(jQuery(ui.sender));\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tstoreordering(jQuery(ui.item).parent());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tinitordering();\n\t\t\t});\n\t\t\tfunction storeordering(parent_element) {\n\t\t\t\thidden_id = '#'+jQuery.trim(parent_element.attr('id').replace('sortable-',''));\n\t\t\t\tfields = new Array();\n\t\t\t\ti = 0;\n\t\t\t\tparent_element.children('li').each(function(){\n\t\t\t\t\tfields[i++] = jQuery(this).attr('id').replace('field_', '');\n\t\t\t\t});\n\t\t\t\tjQuery(hidden_id).val(fields.join(','))\n\t\t\t}\n\t\t\t";
            $js .= '
			var fieldListFilters = new Array( "content_type", "field_type" );
			function filterFieldList (containerID, method, group)
			{
				var needed_classes = "";
				for (i=0; i<fieldListFilters.length; i++)
				{
					filter_name = fieldListFilters[i];
					
					var filter_val = jQuery("#" + filter_name + "_" + group).val();
					if (filter_val) {
						needed_classes += "."+filter_name+"_"+filter_val;
					}
				}
				
				if (needed_classes) {
					(method=="hide") ?
						jQuery("#"+containerID).find("li").show().filter(":not("+needed_classes+")").hide() :
						jQuery("#"+containerID).find("li").css({"color":"red"}).filter(":not("+needed_classes+")").css({"color":"black"});
				} else {
					(method=="hide") ?
						jQuery("#"+containerID).find("li").show() :
						jQuery("#"+containerID).find("li").css({"color":"black"});
				}
			}
			
			';
            $document->addScriptDeclaration($js);
        }
        // **************************
        // Add css and js to document
        // **************************
        flexicontent_html::loadFramework('select2');
        JHTML::_('behavior.tooltip');
        JHTML::_('behavior.modal');
        $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontentbackend.css');
        if (FLEXI_J30GE) {
            $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/j3x.css');
        } else {
            if (FLEXI_J16GE) {
                $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/j25.css');
            }
        }
        // *****************************
        // Get user's global permissions
        // *****************************
        $perms = FlexicontentHelperPerm::getPerm();
        if (!$perms->CanTemplates) {
            $app->redirect('index.php?option=com_flexicontent', JText::_('FLEXI_NO_ACCESS'));
        }
        // ************************
        // Create Submenu & Toolbar
        // ************************
        // Create Submenu (and also check access to current view)
        FLEXISubmenu('CanTemplates');
        //create the toolbar
        $bar = JToolBar::getInstance('toolbar');
        JToolBarHelper::title(JText::_('FLEXI_EDIT_TEMPLATE'), 'templates');
        if (!$ismodal) {
            JToolBarHelper::apply('templates.apply');
            JToolBarHelper::save('templates.save');
            JToolBarHelper::cancel('templates.cancel');
        } else {
            JToolBarHelper::apply('templates.apply_modal');
            echo $bar->render();
        }
        // **********************************************************************************
        // Get Templates and apply Template Parameters values into the form fields structures
        // **********************************************************************************
        if (FLEXI_J16GE) {
            $jform = new JForm('com_flexicontent.template.category', array('control' => 'jform', 'load_data' => true));
            $jform->load($layout->params);
            $layout->params = $jform;
            // ... values applied at the template form file
        } else {
            $layout->params->loadINI($row->params);
        }
        //print_r($layout);
        //assign data to template
        //print_r($conf);
        $this->assignRef('conf', $conf);
        $this->assignRef('layout', $layout);
        $this->assignRef('fields', $fields);
        $this->assignRef('user', $user);
        $this->assignRef('type', $type);
        $this->assignRef('folder', $folder);
        $this->assignRef('jssort', $jssort);
        $this->assignRef('positions', $positions);
        $this->assignRef('used', $used);
        $this->assignRef('fbypos', $fbypos);
        $this->assignRef('use_jquery_sortable', $use_jquery_sortable);
        $this->assignRef('content_type_select', $content_type_select);
        $this->assignRef('field_type_select', $field_type_select);
        parent::display($tpl);
    }
예제 #22
0
    /**
     * Creates the item page
     *
     * @since 1.0
     */
    function display($tpl = null)
    {
        // ********************************
        // Initialize variables, flags, etc
        // ********************************
        global $globalcats;
        $categories = $globalcats;
        $app = JFactory::getApplication();
        $dispatcher = JDispatcher::getInstance();
        $document = JFactory::getDocument();
        $config = JFactory::getConfig();
        $session = JFactory::getSession();
        $user = JFactory::getUser();
        $db = JFactory::getDBO();
        $option = JRequest::getVar('option');
        $nullDate = $db->getNullDate();
        // Get the COMPONENT only parameters
        // Get component parameters
        $params = new JRegistry();
        $cparams = JComponentHelper::getParams('com_flexicontent');
        $params->merge($cparams);
        $params = clone JComponentHelper::getParams('com_flexicontent');
        // Some flags
        $enable_translation_groups = flexicontent_db::useAssociations();
        //$params->get("enable_translation_groups");
        $print_logging_info = $params->get('print_logging_info');
        if ($print_logging_info) {
            global $fc_run_times;
        }
        // *****************
        // Load JS/CSS files
        // *****************
        // Add css to document
        $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontentbackend.css', FLEXI_VERSION);
        $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/j3x.css', FLEXI_VERSION);
        // Fields common CSS
        $document->addStyleSheetVersion(JURI::root(true) . '/components/com_flexicontent/assets/css/flexi_form_fields.css', FLEXI_VERSION);
        // Add JS frameworks
        flexicontent_html::loadFramework('select2');
        $prettycheckable_added = flexicontent_html::loadFramework('prettyCheckable');
        flexicontent_html::loadFramework('flexi-lib');
        // Add js function to overload the joomla submitform validation
        JHTML::_('behavior.formvalidation');
        // load default validation JS to make sure it is overriden
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/admin.js', FLEXI_VERSION);
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/validate.js', FLEXI_VERSION);
        // Add js function for custom code used by FLEXIcontent item form
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/itemscreen.js', FLEXI_VERSION);
        // ***********************
        // Get data from the model
        // ***********************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $model = $this->getModel();
        $item = $model->getItem();
        $form = $this->get('Form');
        if ($print_logging_info) {
            $fc_run_times['get_item_data'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // ***************************
        // Get Associated Translations
        // ***************************
        if ($enable_translation_groups) {
            $langAssocs = $this->get('LangAssocs');
        }
        $langs = FLEXIUtilities::getLanguages('code');
        // Get item id and new flag
        $cid = $model->getId();
        $isnew = !$cid;
        // Create and set a unique item id for plugins that needed it
        if ($cid) {
            $unique_tmp_itemid = $cid;
        } else {
            $unique_tmp_itemid = $app->getUserState('com_flexicontent.edit.item.unique_tmp_itemid');
            $unique_tmp_itemid = $unique_tmp_itemid ? $unique_tmp_itemid : date('_Y_m_d_h_i_s_', time()) . uniqid(true);
        }
        //print_r($unique_tmp_itemid);
        JRequest::setVar('unique_tmp_itemid', $unique_tmp_itemid);
        // Get number of subscribers
        $subscribers = $model->getSubscribersCount();
        // ******************
        // Version Panel data
        // ******************
        // Get / calculate some version related variables
        $versioncount = $model->getVersionCount();
        $versionsperpage = $params->get('versionsperpage', 10);
        $pagecount = (int) ceil($versioncount / $versionsperpage);
        // Data need by version panel: (a) current version page, (b) currently active version
        $current_page = 1;
        $k = 1;
        $allversions = $model->getVersionList();
        foreach ($allversions as $v) {
            if ($k > 1 && ($k - 1) % $versionsperpage == 0) {
                $current_page++;
            }
            if ($v->nr == $item->version) {
                break;
            }
            $k++;
        }
        // Finally fetch the version data for versions in current page
        $versions = $model->getVersionList(($current_page - 1) * $versionsperpage, $versionsperpage);
        // Create display of average rating
        $ratings = $model->getRatingDisplay();
        // *****************
        // Type related data
        // *****************
        // Get available types and the currently selected/requested type
        $types = $model->getTypeslist();
        $typesselected = $model->getTypesselected();
        // Get and merge type parameters
        $tparams = $this->get('Typeparams');
        $tparams = new JRegistry($tparams);
        $params->merge($tparams);
        // Apply type configuration if it type is set
        // Get user allowed permissions on the item ... to be used by the form rendering
        // Also hide parameters panel if user can not edit parameters
        $perms = $this->_getItemPerms($item);
        if (!$perms['canparams']) {
            $document->addStyleDeclaration('#details-options {display:none;}');
        }
        // ******************
        // Create the toolbar
        // ******************
        $toolbar = JToolBar::getInstance('toolbar');
        $tip_class = FLEXI_J30GE ? ' hasTooltip' : ' hasTip';
        // SET toolbar title
        if ($cid) {
            JToolBarHelper::title(JText::_('FLEXI_EDIT_ITEM'), 'itemedit');
            // Editing existing item
        } else {
            JToolBarHelper::title(JText::_('FLEXI_NEW_ITEM'), 'itemadd');
            // Creating new item
        }
        // **************
        // Common Buttons
        // **************
        // Applying new item type is a special case that has not loaded custom fieds yet
        JToolBarHelper::apply($item->type_id ? 'items.apply' : 'items.apply_type', !$isnew ? 'FLEXI_APPLY' : ($typesselected->id ? 'FLEXI_ADD' : 'FLEXI_APPLY_TYPE'), false);
        /*if (!$isnew || $item->version) flexicontent_html::addToolBarButton(
        		'FLEXI_FAST_APPLY', $btn_name='apply_ajax', $full_js="Joomla.submitbutton('items.apply_ajax')", $msg_alert='', $msg_confirm='',
        		$btn_task='items.apply_ajax', $extra_js='', $btn_list=false, $btn_menu=true, $btn_confirm=false, $btn_class="".$tip_class, $btn_icon="icon-loop",
        		'data-placement="bottom" title="Fast saving, without reloading the form. <br/><br/>Note: new files will not be uploaded, <br/>- in such a case please use \'Apply\'"');*/
        if (!$isnew || $item->version) {
            JToolBarHelper::save('items.save');
        }
        if (!$isnew || $item->version) {
            JToolBarHelper::custom('items.saveandnew', 'savenew.png', 'savenew.png', 'FLEXI_SAVE_AND_NEW', false);
        }
        JToolBarHelper::cancel('items.cancel');
        // ***********************
        // Add a preview button(s)
        // ***********************
        //$_sh404sef = JPluginHelper::isEnabled('system', 'sh404sef') && $config->get('sef');
        $_sh404sef = defined('SH404SEF_IS_RUNNING') && $config->get('sef');
        if ($cid) {
            // Domain URL and autologin vars
            $server = JURI::getInstance()->toString(array('scheme', 'host', 'port'));
            $autologin = '';
            //$params->get('autoflogin', 1) ? '&fcu='.$user->username . '&fcp='.$user->password : '';
            // Check if we are in the backend, in the back end we need to set the application to the site app instead
            // we do not remove 'isAdmin' check so that we can copy later without change, e.g. to a plugin
            $isAdmin = JFactory::getApplication()->isAdmin();
            if ($isAdmin && !$_sh404sef) {
                JFactory::$application = JApplication::getInstance('site');
            }
            // Create the URL
            $item_url = FlexicontentHelperRoute::getItemRoute($item->id . ':' . $item->alias, $categories[$item->catid]->slug) . ($item->language != '*' ? '&lang=' . substr($item->language, 0, 2) : '');
            $item_url = $_sh404sef ? Sh404sefHelperGeneral::getSefFromNonSef($item_url, $fullyQualified = true, $xhtml = false, $ssl = null) : JRoute::_($item_url);
            // Check if we are in the backend again
            // In backend we need to remove administrator from URL as it is added even though we've set the application to the site app
            if ($isAdmin && !$_sh404sef) {
                $admin_folder = str_replace(JURI::root(true), '', JURI::base(true));
                $item_url = str_replace($admin_folder . '/', '/', $item_url);
                // Restore application
                JFactory::$application = JApplication::getInstance('administrator');
            }
            $previewlink = $item_url . (strstr($item_url, '?') ? '&amp;' : '?') . 'preview=1' . $autologin;
            //$previewlink     = str_replace('&amp;', '&', $previewlink);
            //$previewlink = JRoute::_(JURI::root() . FlexicontentHelperRoute::getItemRoute($item->id.':'.$item->alias, $categories[$item->catid]->slug)) .$autologin;
            // PREVIEW for latest version
            if (!$params->get('use_versioning', 1) || $item->version == $item->current_version && $item->version == $item->last_version) {
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small btn-info spaced-btn" onClick="window.open(\'' . $previewlink . '\');"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('Preview') . '</button>', 'preview');
            } else {
                // Add a preview button for (currently) LOADED version of the item
                $previewlink_loaded_ver = $previewlink . '&version=' . $item->version;
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small" onClick="window.open(\'' . $previewlink_loaded_ver . '\');" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('FLEXI_PREVIEW_FORM_LOADED_VERSION') . ' [' . $item->version . ']</button>', 'preview');
                // Add a preview button for currently ACTIVE version of the item
                $previewlink_active_ver = $previewlink . '&version=' . $item->current_version;
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small" onClick="window.open(\'' . $previewlink_active_ver . '\');" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('FLEXI_PREVIEW_FRONTEND_ACTIVE_VERSION') . ' [' . $item->current_version . ']</button>', 'preview');
                // Add a preview button for currently LATEST version of the item
                $previewlink_last_ver = $previewlink;
                //'&version='.$item->last_version;
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small" onClick="window.open(\'' . $previewlink_last_ver . '\');" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('FLEXI_PREVIEW_LATEST_SAVED_VERSION') . ' [' . $item->last_version . ']</button>', 'preview');
            }
            JToolBarHelper::spacer();
            JToolBarHelper::divider();
            JToolBarHelper::spacer();
        }
        // ************************
        // Add modal layout editing
        // ************************
        if ($perms['cantemplates']) {
            JToolBarHelper::divider();
            if (!$isnew || $item->version) {
                flexicontent_html::addToolBarButton('FLEXI_EDIT_LAYOUT', $btn_name = 'apply_ajax', $full_js = "var url = jQuery(this).attr('data-href'); fc_showDialog(url, 'fc_modal_popup_container'); return false;", $msg_alert = '', $msg_confirm = '', $btn_task = 'items.apply_ajax', $extra_js = '', $btn_list = false, $btn_menu = true, $btn_confirm = false, $btn_class = "btn-info" . $tip_class, $btn_icon = "icon-pencil", 'data-placement="bottom" data-href="index.php?option=com_flexicontent&amp;view=template&amp;type=items&amp;tmpl=component&amp;ismodal=1&amp;folder=' . $item->itemparams->get('ilayout', $tparams->get('ilayout', 'default')) . '" title="Edit the display layout of this item. <br/><br/>Note: this layout maybe assigned to content types or other items, thus changing it will effect them too"');
            }
        }
        // Check if saving an item that translates an original content in site's default language
        $site_default = substr(flexicontent_html::getSiteDefaultLang(), 0, 2);
        $is_content_default_lang = $site_default == substr($item->language, 0, 2);
        // *****************************************************************************
        // Get (CORE & CUSTOM) fields and their VERSIONED values and then
        // (a) Apply Content Type Customization to CORE fields (label, description, etc)
        // (b) Create the edit html of the CUSTOM fields by triggering 'onDisplayField'
        // *****************************************************************************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $fields = $this->get('Extrafields');
        $item->fields =& $fields;
        if ($print_logging_info) {
            $fc_run_times['get_field_vals'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $jcustom = $app->getUserState('com_flexicontent.edit.item.custom');
        //print_r($jcustom);
        foreach ($fields as $field) {
            // a. Apply CONTENT TYPE customizations to CORE FIELDS, e.g a type specific label & description
            // NOTE: the field parameters are already created so there is not need to call this for CUSTOM fields, which do not have CONTENT TYPE customizations
            if ($field->iscore) {
                FlexicontentFields::loadFieldConfig($field, $item);
            }
            // b. Create field 's editing HTML (the form field)
            // NOTE: this is DONE only for CUSTOM fields, since form field html is created by the form for all CORE fields, EXCEPTION is the 'text' field (see bellow)
            if (!$field->iscore) {
                if (isset($jcustom[$field->name])) {
                    $field->value = array();
                    foreach ($jcustom[$field->name] as $i => $_val) {
                        $field->value[$i] = $_val;
                    }
                }
                $is_editable = !$field->valueseditable || $user->authorise('flexicontent.editfieldvalues', 'com_flexicontent.field.' . $field->id);
                if ($is_editable) {
                    FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayField', array(&$field, &$item));
                    if ($field->untranslatable) {
                        $field->html = (!isset($field->html) ? '<div class="fc-mssg-inline fc-warning" style="margin:0 4px 6px 4px; max-width: unset;">' . JText::_('FLEXI_PLEASE_PUBLISH_THIS_PLUGIN') . '</div><div class="clear"></div>' : '') . '<div class="alert alert-info fc-small fc-iblock" style="margin:0 4px 6px 4px; max-width: unset;">' . JText::_('FLEXI_FIELD_VALUE_IS_NON_TRANSLATABLE') . '</div>' . "\n" . (isset($field->html) ? '<div class="clear"></div>' . $field->html : '');
                    }
                } else {
                    if ($field->valueseditable == 1) {
                        $field->html = '<div class="fc-mssg fc-note">' . JText::_($field->parameters->get('no_acc_msg_form') ? $field->parameters->get('no_acc_msg_form') : 'FLEXI_NO_ACCESS_LEVEL_TO_EDIT_FIELD') . '</div>';
                    } else {
                        if ($field->valueseditable == 2) {
                            FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayFieldValue', array(&$field, $item));
                            $field->html = '<div class="fc-mssg fc-note">' . JText::_($field->parameters->get('no_acc_msg_form') ? $field->parameters->get('no_acc_msg_form') : 'FLEXI_NO_ACCESS_LEVEL_TO_EDIT_FIELD') . '</div>' . "\n" . $field->display;
                        } else {
                            if ($field->valueseditable == 3) {
                                FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayFieldValue', array(&$field, $item));
                                $field->html = $field->display;
                            } else {
                                if ($field->valueseditable == 4) {
                                    $field->html = '';
                                    $field->formhidden = 4;
                                }
                            }
                        }
                    }
                }
            }
            // c. Create main text field, via calling the display function of the textarea field (will also check for tabs)
            if ($field->field_type == 'maintext') {
                if (isset($item->item_translations)) {
                    $shortcode = substr($item->language, 0, 2);
                    foreach ($item->item_translations as $lang_id => $t) {
                        if ($shortcode == $t->shortcode) {
                            continue;
                        }
                        $field->name = array('jfdata', $t->shortcode, 'text');
                        $field->value[0] = html_entity_decode($t->fields->text->value, ENT_QUOTES, 'UTF-8');
                        FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
                        $t->fields->text->tab_labels = $field->tab_labels;
                        $t->fields->text->html = $field->html;
                        unset($field->tab_labels);
                        unset($field->html);
                    }
                }
                $field->name = 'text';
                // NOTE: We use the text created by the model and not the text retrieved by the CORE plugin code, which maybe overwritten with JoomFish/Falang data
                $field->value[0] = $item->text;
                // do not decode special characters this was handled during saving !
                // Render the field's (form) HTML
                FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
            }
        }
        if ($print_logging_info) {
            $fc_run_times['render_field_html'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // *************************
        // Get tags used by the item
        // *************************
        $usedtagsIds = $this->get('UsedtagsIds');
        // NOTE: This will normally return the already set versioned value of tags ($item->tags)
        $usedtags = $model->getUsedtagsData($usedtagsIds);
        // *******************************
        // Get categories used by the item
        // *******************************
        if ($isnew) {
            // Case for preselected main category for new items
            $maincat = $item->catid ? $item->catid : JRequest::getInt('maincat', 0);
            if (!$maincat) {
                $maincat = $app->getUserStateFromRequest($option . '.items.filter_cats', 'filter_cats', '', 'int');
            }
            if ($maincat) {
                $selectedcats = array($maincat);
                $item->catid = $maincat;
            } else {
                $selectedcats = array();
            }
            if ($tparams->get('cid_default')) {
                $selectedcats = $tparams->get('cid_default');
            }
            if ($tparams->get('catid_default')) {
                $item->catid = $tparams->get('catid_default');
            }
        } else {
            // NOTE: This will normally return the already set versioned value of categories ($item->categories)
            $selectedcats = $this->get('Catsselected');
        }
        //$selectedcats 	= $isnew ? array() : $fields['categories']->value;
        //echo "<br/>row->tags: "; print_r($item->tags);
        //echo "<br/>usedtagsIds: "; print_r($usedtagsIds);
        //echo "<br/>usedtags (data): "; print_r($usedtags);
        //echo "<br/>row->categories: "; print_r($item->categories);
        //echo "<br/>selectedcats: "; print_r($selectedcats);
        // *********************************************************************************************
        // Build select lists for the form field. Only few of them are used in J1.6+, since we will use:
        // (a) form XML file to declare them and then (b) getInput() method form field to create them
        // *********************************************************************************************
        // First clean form data, we do this after creating the description field which may contain HTML
        JFilterOutput::objectHTMLSafe($item, ENT_QUOTES);
        $lists = array();
        // build state list
        $non_publishers_stategrp = $perms['isSuperAdmin'] || $item->state == -3 || $item->state == -4;
        $special_privelege_stategrp = $item->state == 2 || $perms['canarchive'] || ($item->state == -2 || $perms['candelete']);
        $state = array();
        // Using <select> groups
        if ($non_publishers_stategrp || $special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_PUBLISHERS_WORKFLOW_STATES'));
        }
        $state[] = JHTML::_('select.option', 1, JText::_('FLEXI_PUBLISHED'));
        $state[] = JHTML::_('select.option', 0, JText::_('FLEXI_UNPUBLISHED'));
        $state[] = JHTML::_('select.option', -5, JText::_('FLEXI_IN_PROGRESS'));
        // States reserved for workflow
        if ($non_publishers_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_NON_PUBLISHERS_WORKFLOW_STATES'));
        }
        if ($item->state == -3 || $perms['isSuperAdmin']) {
            $state[] = JHTML::_('select.option', -3, JText::_('FLEXI_PENDING'));
        }
        if ($item->state == -4 || $perms['isSuperAdmin']) {
            $state[] = JHTML::_('select.option', -4, JText::_('FLEXI_TO_WRITE'));
        }
        // Special access states
        if ($special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_SPECIAL_ACTION_STATES'));
        }
        if ($item->state == 2 || $perms['canarchive']) {
            $state[] = JHTML::_('select.option', 2, JText::_('FLEXI_ARCHIVED'));
        }
        if ($item->state == -2 || $perms['candelete']) {
            $state[] = JHTML::_('select.option', -2, JText::_('FLEXI_TRASHED'));
        }
        // Close last <select> group
        if ($non_publishers_stategrp || $special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
        }
        $fieldname = 'jform[state]';
        $elementid = 'jform_state';
        $class = 'use_select2_lib';
        $attribs = 'class="' . $class . '"';
        $lists['state'] = JHTML::_('select.genericlist', $state, $fieldname, $attribs, 'value', 'text', $item->state, $elementid);
        if (!FLEXI_J16GE) {
            $lists['state'] = str_replace('<optgroup label="">', '</optgroup>', $lists['state']);
        }
        // *** BOF: J2.5 SPECIFIC SELECT LISTS
        if (FLEXI_J16GE) {
            // build featured flag
            $fieldname = 'jform[featured]';
            $elementid = 'jform_featured';
            /*
            $options = array();
            $options[] = JHTML::_('select.option',  0, JText::_( 'FLEXI_NO' ) );
            $options[] = JHTML::_('select.option',  1, JText::_( 'FLEXI_YES' ) );
            $attribs = FLEXI_J16GE ? ' style ="float:none!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
            $lists['featured'] = JHTML::_('select.radiolist', $options, $fieldname, $attribs, 'value', 'text', $item->featured, $elementid);
            */
            $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
            $attribs = ' class="' . $classes . '" ';
            $i = 1;
            $options = array(0 => JText::_('FLEXI_NO'), 1 => JText::_('FLEXI_YES'));
            $lists['featured'] = '';
            foreach ($options as $option_id => $option_label) {
                $checked = $option_id == $item->featured ? ' checked="checked"' : '';
                $elementid_no = $elementid . '_' . $i;
                if (!$prettycheckable_added) {
                    $lists['featured'] .= '<label class="fccheckradio_lbl" for="' . $elementid_no . '">';
                }
                $extra_params = !$prettycheckable_added ? '' : ' data-labeltext="' . JText::_($option_label) . '" data-labelPosition="right" data-customClass="fcradiocheck"';
                $lists['featured'] .= ' <input type="radio" id="' . $elementid_no . '" data-element-grpid="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="' . $option_id . '" ' . $checked . $extra_params . ' />';
                if (!$prettycheckable_added) {
                    $lists['featured'] .= '&nbsp;' . JText::_($option_label) . '</label>';
                }
                $i++;
            }
        }
        // *** EOF: J1.5 SPECIFIC SELECT LISTS
        // build version approval list
        $fieldname = 'jform[vstate]';
        $elementid = 'jform_vstate';
        /*
        $options = array();
        $options[] = JHTML::_('select.option',  1, JText::_( 'FLEXI_NO' ) );
        $options[] = JHTML::_('select.option',  2, JText::_( 'FLEXI_YES' ) );
        $attribs = FLEXI_J16GE ? ' style ="float:left!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
        $lists['vstate'] = JHTML::_('select.radiolist', $options, $fieldname, $attribs, 'value', 'text', 2, $elementid);
        */
        $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
        $attribs = ' class="' . $classes . '" ';
        $i = 1;
        $options = array(1 => JText::_('FLEXI_NO'), 2 => JText::_('FLEXI_YES'));
        $lists['vstate'] = '';
        foreach ($options as $option_id => $option_label) {
            $checked = $option_id == 2 ? ' checked="checked"' : '';
            $elementid_no = $elementid . '_' . $i;
            if (!$prettycheckable_added) {
                $lists['vstate'] .= '<label class="fccheckradio_lbl" for="' . $elementid_no . '">';
            }
            $extra_params = !$prettycheckable_added ? '' : ' data-labeltext="' . JText::_($option_label) . '" data-labelPosition="right" data-customClass="fcradiocheck"';
            $lists['vstate'] .= ' <input type="radio" id="' . $elementid_no . '" data-element-grpid="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="' . $option_id . '" ' . $checked . $extra_params . ' />';
            if (!$prettycheckable_added) {
                $lists['vstate'] .= '&nbsp;' . JText::_($option_label) . '</label>';
            }
            $i++;
        }
        // build field for notifying subscribers
        if (!$subscribers) {
            $lists['notify'] = !$isnew ? JText::_('FLEXI_NO_SUBSCRIBERS_EXIST') : '';
        } else {
            // b. Check if notification emails to subscribers , were already sent during current session
            $subscribers_notified = $session->get('subscribers_notified', array(), 'flexicontent');
            if (!empty($subscribers_notified[$item->id])) {
                $lists['notify'] = JText::_('FLEXI_SUBSCRIBERS_ALREADY_NOTIFIED');
            } else {
                // build favs notify field
                $fieldname = 'jform[notify]';
                $elementid = 'jform_notify';
                /*
                $attribs = FLEXI_J16GE ? ' style ="float:none!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
                $lists['notify'] = '<input type="checkbox" name="jform[notify]" id="jform_notify" '.$attribs.' /> '. $lbltxt;
                */
                $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
                $attribs = ' class="' . $classes . '" ';
                $lbltxt = $subscribers . ' ' . JText::_($subscribers > 1 ? 'FLEXI_SUBSCRIBERS' : 'FLEXI_SUBSCRIBER');
                if (!$prettycheckable_added) {
                    $lists['notify'] .= '<label class="fccheckradio_lbl" for="' . $elementid . '">';
                }
                $extra_params = !$prettycheckable_added ? '' : ' data-labeltext="' . $lbltxt . '" data-labelPosition="right" data-customClass="fcradiocheck"';
                $lists['notify'] = ' <input type="checkbox" id="' . $elementid . '" data-element-grpid="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="1" ' . $extra_params . ' checked="checked" />';
                if (!$prettycheckable_added) {
                    $lists['notify'] .= '&nbsp;' . $lbltxt . '</label>';
                }
            }
        }
        // Retrieve author configuration
        $authorparams = flexicontent_db::getUserConfig($user->id);
        // Get author's maximum allowed categories per item and set js limitation
        $max_cat_assign = intval($authorparams->get('max_cat_assign', 0));
        $document->addScriptDeclaration('
			max_cat_assign_fc = ' . $max_cat_assign . ';
			existing_cats_fc  = ["' . implode('","', $selectedcats) . '"];
		');
        JText::script('FLEXI_TOO_MANY_ITEM_CATEGORIES', true);
        // Creating categorories tree for item assignment, we use the 'create' privelege
        $actions_allowed = array('core.create');
        // Featured categories form field
        $featured_cats_parent = $params->get('featured_cats_parent', 0);
        $featured_cats = array();
        $enable_featured_cid_selector = $perms['multicat'] && $perms['canchange_featcat'];
        if ($featured_cats_parent) {
            $featured_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $featured_cats_parent, $depth_limit = 0);
            $disabled_cats = $params->get('featured_cats_parent_disable', 1) ? array($featured_cats_parent) : array();
            $featured_sel = array();
            foreach ($selectedcats as $item_cat) {
                if (isset($featured_tree[$item_cat])) {
                    $featured_sel[] = $item_cat;
                }
            }
            $class = "use_select2_lib select2_list_selected";
            $attribs = 'class="' . $class . '" multiple="multiple" size="8"';
            $attribs .= $enable_featured_cid_selector ? '' : ' disabled="disabled"';
            $fieldname = 'jform[featured_cid][]';
            $lists['featured_cid'] = ($enable_featured_cid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($featured_tree, $fieldname, $featured_sel, 3, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees = array(), $disable_subtrees = array(), $custom_options = array(), $disabled_cats);
        } else {
            // Do not display, if not configured or not allowed to the user
            $lists['featured_cid'] = false;
        }
        // Multi-category form field, for user allowed to use multiple categories
        $lists['cid'] = '';
        $enable_cid_selector = $perms['multicat'] && $perms['canchange_seccat'];
        if (1) {
            if ($tparams->get('cid_allowed_parent')) {
                $cid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $tparams->get('cid_allowed_parent'), $depth_limit = 0);
                $disabled_cats = $tparams->get('cid_allowed_parent_disable', 1) ? array($tparams->get('cid_allowed_parent')) : array();
            } else {
                $cid_tree =& $categories;
                $disabled_cats = array();
            }
            // Get author's maximum allowed categories per item and set js limitation
            $max_cat_assign = !$authorparams ? 0 : intval($authorparams->get('max_cat_assign', 0));
            $document->addScriptDeclaration('
				max_cat_assign_fc = ' . $max_cat_assign . ';
				existing_cats_fc  = ["' . implode('","', $selectedcats) . '"];
			');
            $class = "mcat use_select2_lib select2_list_selected";
            $class .= $max_cat_assign ? " validate-fccats" : " validate";
            $attribs = 'class="' . $class . '" multiple="multiple" size="20"';
            $attribs .= $enable_cid_selector ? '' : ' disabled="disabled"';
            $fieldname = 'jform[cid][]';
            $skip_subtrees = $featured_cats_parent ? array($featured_cats_parent) : array();
            $lists['cid'] = ($enable_cid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($cid_tree, $fieldname, $selectedcats, false, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees, $disable_subtrees = array(), $custom_options = array(), $disabled_cats);
        } else {
            if (count($selectedcats) > 1) {
                foreach ($selectedcats as $catid) {
                    $cat_titles[$catid] = $globalcats[$catid]->title;
                }
                $lists['cid'] .= implode(', ', $cat_titles);
            } else {
                $lists['cid'] = false;
            }
        }
        // Main category form field
        $class = 'scat use_select2_lib';
        if ($perms['multicat']) {
            $class .= ' validate-catid';
        } else {
            $class .= ' required';
        }
        $attribs = 'class="' . $class . '"';
        $fieldname = 'jform[catid]';
        $enable_catid_selector = $isnew && !$tparams->get('catid_default') || !$isnew && empty($item->catid) || $perms['canchange_cat'];
        if ($tparams->get('catid_allowed_parent')) {
            $catid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $tparams->get('catid_allowed_parent'), $depth_limit = 0);
            $disabled_cats = $tparams->get('catid_allowed_parent_disable', 1) ? array($tparams->get('catid_allowed_parent')) : array();
        } else {
            $catid_tree =& $categories;
            $disabled_cats = array();
        }
        $lists['catid'] = false;
        if (!empty($catid_tree)) {
            $disabled = $enable_catid_selector ? '' : ' disabled="disabled"';
            $attribs .= $disabled;
            $lists['catid'] = ($enable_catid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($catid_tree, $fieldname, $item->catid, 2, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees = array(), $disable_subtrees = array(), $custom_options = array(), $disabled_cats);
        } else {
            if (!$isnew && $item->catid) {
                $lists['catid'] = $globalcats[$item->catid]->title;
            }
        }
        //buid types selectlist
        $class = 'required use_select2_lib';
        $attribs = 'class="' . $class . '"';
        $fieldname = 'jform[type_id]';
        $elementid = 'jform_type_id';
        $lists['type'] = flexicontent_html::buildtypesselect($types, $fieldname, $typesselected->id, 1, $attribs, $elementid, $check_perms = true);
        //build languages list
        $allowed_langs = !$authorparams ? null : $authorparams->get('langs_allowed', null);
        $allowed_langs = !$allowed_langs ? null : FLEXIUtilities::paramToArray($allowed_langs);
        if (!$isnew && $allowed_langs) {
            $allowed_langs[] = $item->language;
        }
        // We will not use the default getInput() function of J1.6+ since we want to create a radio selection field with flags
        // we could also create a new class and override getInput() method but maybe this is an overkill, we may do it in the future
        $lists['languages'] = flexicontent_html::buildlanguageslist('jform[language]', 'class="use_select2_lib"', $item->language, 2, $allowed_langs);
        // Label for current item state: published, unpublished, archived etc
        switch ($item->state) {
            case 0:
                $published = JText::_('FLEXI_UNPUBLISHED');
                break;
            case 1:
                $published = JText::_('FLEXI_PUBLISHED');
                break;
            case -1:
                $published = JText::_('FLEXI_ARCHIVED');
                break;
            case -3:
                $published = JText::_('FLEXI_PENDING');
                break;
            case -5:
                $published = JText::_('FLEXI_IN_PROGRESS');
                break;
            case -4:
            default:
                $published = JText::_('FLEXI_TO_WRITE');
                break;
        }
        // **************************************************************
        // Handle Item Parameters Creation and Load their values for J1.5
        // In J1.6+ we declare them in the item form XML file
        // **************************************************************
        if (JHTML::_('date', $item->publish_down, 'Y') <= 1969 || $item->publish_down == $db->getNullDate() || empty($item->publish_down)) {
            $form->setValue('publish_down', null, '');
            // Setting to text will break form date element
        }
        // ****************************
        // Handle Template related work
        // ****************************
        // (a) Get the templates structures used to create form fields for template parameters
        $themes = flexicontent_tmpl::getTemplates();
        $tmpls_all = $themes->items;
        // (b) Get Content Type allowed templates
        $allowed_tmpls = $tparams->get('allowed_ilayouts');
        $type_default_layout = $tparams->get('ilayout', 'default');
        if (empty($allowed_tmpls)) {
            $allowed_tmpls = array();
        } else {
            if (!is_array($allowed_tmpls)) {
                $allowed_tmpls = explode("|", $allowed_tmpls);
            }
        }
        // (c) Add default layout, unless all templates allowed (=array is empty)
        if (count($allowed_tmpls) && !in_array($type_default_layout, $allowed_tmpls)) {
            $allowed_tmpls[] = $type_default_layout;
        }
        // (d) Create array of template data according to the allowed templates for current content type
        if (count($allowed_tmpls)) {
            foreach ($tmpls_all as $tmpl) {
                if (in_array($tmpl->name, $allowed_tmpls)) {
                    $tmpls[] = $tmpl;
                }
            }
        } else {
            $tmpls = $tmpls_all;
        }
        // (e) Apply Template Parameters values into the form fields structures
        foreach ($tmpls as $tmpl) {
            $jform = new JForm('com_flexicontent.template.item', array('control' => 'jform', 'load_data' => true));
            $jform->load($tmpl->params);
            $tmpl->params = $jform;
            foreach ($tmpl->params->getGroup('attribs') as $field) {
                $fieldname = $field->__get('fieldname');
                $value = $item->itemparams->get($fieldname);
                if (strlen($value)) {
                    $tmpl->params->setValue($fieldname, 'attribs', $value);
                }
            }
        }
        // ******************************
        // Assign data to VIEW's template
        // ******************************
        $this->assignRef('document', $document);
        $this->assignRef('lists', $lists);
        $this->assignRef('row', $item);
        if (FLEXI_J16GE) {
            $this->assignRef('form', $form);
        } else {
            $this->assignRef('editor', $editor);
            $this->assignRef('pane', $pane);
            $this->assignRef('formparams', $formparams);
        }
        if ($enable_translation_groups) {
            $this->assignRef('lang_assocs', $langAssocs);
        }
        if (FLEXI_FISH || FLEXI_J16GE) {
            $this->assignRef('langs', $langs);
        }
        $this->assignRef('typesselected', $typesselected);
        $this->assignRef('published', $published);
        $this->assignRef('nullDate', $nullDate);
        $this->assignRef('subscribers', $subscribers);
        $this->assignRef('fields', $fields);
        $this->assignRef('versions', $versions);
        $this->assignRef('ratings', $ratings);
        $this->assignRef('pagecount', $pagecount);
        $this->assignRef('params', $params);
        $this->assignRef('tparams', $tparams);
        $this->assignRef('tmpls', $tmpls);
        $this->assignRef('usedtags', $usedtags);
        $this->assignRef('perms', $perms);
        $this->assignRef('current_page', $current_page);
        // Clear custom form data from session
        $app->setUserState($form->option . '.edit.' . $form->context . '.custom', false);
        $app->setUserState($form->option . '.edit.' . $form->context . '.jfdata', false);
        $app->setUserState($form->option . '.edit.' . $form->context . '.unique_tmp_itemid', false);
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        parent::display($tpl);
        if ($print_logging_info) {
            $fc_run_times['form_rendering'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
    }
예제 #23
0
        ?>
">
					<?php 
        echo $infoimage;
        ?>
				</span>
			</div>
			<?php 
    }
    ?>
		</div>
	</fieldset>
<?php 
    $captured['tags'] = ob_get_clean();
}
if (!isset($all_tab_fields['lang']) && $captured['lang'] || flexicontent_db::useAssociations() && $this->params->get('uselang_fe', 1) == 1) {
    ob_start();
    // language
    ?>
	<fieldset class="basicfields_set" id="fcform_language_container">
		<legend>
			<?php 
    echo !isset($all_tab_fields['lang']) ? JText::_('FLEXI_LANGUAGE') : JText::_('FLEXI_LANGUAGE') . ' ' . JText::_('FLEXI_ASSOCIATIONS');
    ?>
		</legend>
		
		<?php 
    if (!isset($all_tab_fields['lang'])) {
        echo $captured['lang'];
        unset($captured['lang']);
    }
예제 #24
0
 /**
  * Creates the page's display
  *
  * @since 1.0
  */
 function display($tpl = null)
 {
     //initialize variables
     $option = JRequest::getVar('option');
     $app = JFactory::getApplication();
     $document = JFactory::getDocument();
     $db = JFactory::getDBO();
     $menus = $app->getMenu();
     $menu = $menus->getActive();
     $uri = JFactory::getURI();
     $pathway = $app->getPathway();
     // Get view's Model
     $model = $this->getModel();
     $error = '';
     $rows = null;
     $total = 0;
     $form_id = $form_name = "searchForm";
     // Get parameters via model
     $params = $model->getParams();
     // Get various data from the model
     $areas = $this->get('areas');
     $state = $this->get('state');
     $searchword = $state->get('keyword');
     $searchphrase = $state->get('match');
     $searchordering = $state->get('ordering');
     // ***********************************************************
     // some parameter shortcuts common with advanced search plugin
     // ***********************************************************
     $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;
     // ********************************
     // Load needed JS libs & CSS styles
     // ********************************
     FLEXI_J30GE ? JHtml::_('behavior.framework', true) : JHTML::_('behavior.mootools');
     flexicontent_html::loadFramework('jQuery');
     flexicontent_html::loadFramework('flexi_tmpl_common');
     // Add css files to the document <head> section (also load CSS joomla template override)
     if (!$params->get('disablecss', '')) {
         $document->addStyleSheetVersion($this->baseurl . '/components/com_flexicontent/assets/css/flexicontent.css', FLEXI_VERSION);
         $document->addStyleSheetVersion($this->baseurl . '/components/com_flexicontent/assets/css/flexi_filters.css', FLEXI_VERSION);
         //$document->addCustomTag('<!--[if IE]><style type="text/css">.floattext {zoom:1;}</style><![endif]-->');
     }
     if (file_exists(JPATH_SITE . DS . 'templates' . DS . $app->getTemplate() . DS . 'css' . DS . 'flexicontent.css')) {
         $document->addStyleSheetVersion($this->baseurl . '/templates/' . $app->getTemplate() . '/css/flexicontent.css', FLEXI_VERSION);
     }
     // **********************************************************
     // Calculate a (browser window) page title and a page heading
     // **********************************************************
     // Verify menu item points to current FLEXIcontent object
     if ($menu) {
         $view_ok = 'search' == @$menu->query['view'];
         $menu_matches = $view_ok;
         //$menu_params = FLEXI_J16GE ? $menu->params : new JParameter($menu->params);  // Get active menu item parameters
     } else {
         $menu_matches = false;
     }
     // MENU ITEM matched, use its page heading (but use menu title if the former is not set)
     if ($menu_matches) {
         $default_heading = FLEXI_J16GE ? $menu->title : $menu->name;
         // Cross set (show_) page_heading / page_title for compatibility of J2.5+ with J1.5 template (and for J1.5 with J2.5 template)
         $params->def('page_heading', $params->get('page_title', $default_heading));
         $params->def('page_title', $params->get('page_heading', $default_heading));
         $params->def('show_page_heading', $params->get('show_page_title', 0));
         $params->def('show_page_title', $params->get('show_page_heading', 0));
     } else {
         // Clear some menu parameters
         //$params->set('pageclass_sfx',	'');  // CSS class SUFFIX is behavior, so do not clear it ?
         // Calculate default page heading (=called page title in J1.5), which in turn will be document title below !! ...
         // meta_params->get('page_title') is meant for <title> but let's use as ... default page heading
         $default_heading = JText::_('FLEXI_SEARCH');
         // Decide to show page heading (=J1.5 page title), this default to no
         $show_default_heading = 0;
         // Set both (show_) page_heading / page_title for compatibility of J2.5+ with J1.5 template (and for J1.5 with J2.5 template)
         $params->set('page_title', $default_heading);
         $params->set('page_heading', $default_heading);
         $params->set('show_page_heading', $show_default_heading);
         $params->set('show_page_title', $show_default_heading);
     }
     // Prevent showing the page heading if ... currently no reason
     if (0) {
         $params->set('show_page_heading', 0);
         $params->set('show_page_title', 0);
     }
     // ************************************************************
     // Create the document title, by from page title and other data
     // ************************************************************
     // Use the page heading as document title, (already calculated above via 'appropriate' logic ...)
     $doc_title = $params->get('page_title');
     // Check and prepend or append site name to page title
     if ($doc_title != $app->getCfg('sitename')) {
         if ($app->getCfg('sitename_pagetitles', 0) == 1) {
             $doc_title = JText::sprintf('JPAGETITLE', $app->getCfg('sitename'), $doc_title);
         } elseif ($app->getCfg('sitename_pagetitles', 0) == 2) {
             $doc_title = JText::sprintf('JPAGETITLE', $doc_title, $app->getCfg('sitename'));
         }
     }
     // Finally, set document title
     $document->setTitle($doc_title);
     // ************************
     // Set document's META tags
     // ************************
     // Workaround for Joomla not setting the default value for 'robots', so component must do it
     $app_params = $app->getParams();
     if ($_mp = $app_params->get('robots')) {
         $document->setMetadata('robots', $_mp);
     }
     // Overwrite with menu META data if menu matched
     if ($menu_matches) {
         if ($_mp = $menu->params->get('menu-meta_description')) {
             $document->setDescription($_mp);
         }
         if ($_mp = $menu->params->get('menu-meta_keywords')) {
             $document->setMetadata('keywords', $_mp);
         }
         if ($_mp = $menu->params->get('robots')) {
             $document->setMetadata('robots', $_mp);
         }
         if ($_mp = $menu->params->get('secure')) {
             $document->setMetadata('secure', $_mp);
         }
     }
     // ********************************************************************
     // 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();
         }
     }
     // ****************************************
     // Create Form Elements (the 'lists' array)
     // ****************************************
     $lists = array();
     // *** Selector of Content Types
     if ($canseltypes) {
         $types = array();
         if ($show_filters) {
             $types[] = JHTML::_('select.option', '', JText::_('FLEXI_PLEASE_SELECT'));
         }
         foreach ($typeData as $type) {
             $types[] = JHTML::_('select.option', $type->id, JText::_($type->name));
         }
         $multiple_param = $show_filters ? ' onchange="adminFormPrepare(this.form); this.form.submit();" ' : ' multiple="multiple" ';
         $attribs = $multiple_param . ' size="5" class="fc_field_filter use_select2_lib fc_label_internal fc_prompt_internal"';
         $attribs .= ' data-fc_label_text="' . flexicontent_html::escapeJsText(JText::_('FLEXI_CLICK_TO_LIST'), 's') . '"';
         $attribs .= ' data-fc_prompt_text="' . flexicontent_html::escapeJsText(JText::_('FLEXI_TYPE_TO_FILTER'), 's') . '"';
         $lists['contenttypes'] = JHTML::_('select.genericlist', $types, 'contenttypes[]', $attribs, 'value', 'text', empty($form_contenttypes) ? '' : $form_contenttypes, 'contenttypes');
         /*
         $checked = !count($form_contenttypes) || !strlen($form_contenttypes[0]);
         $checked_attr = $checked ? 'checked="checked"' : '';
         $checked_class = $checked ? 'fc_highlight' : '';
         
         $lists['contenttypes']  = '<ul class="fc_field_filter fc_checkradio_group">';
         $lists['contenttypes'] .= ' <li class="fc_checkradio_option fc_checkradio_special">';
         $lists['contenttypes'] .= '  <input href="javascript:;" onclick="fc_toggleClass(this, \'fc_highlight\', 1);" ';
         $lists['contenttypes'] .= '    id="_contenttypes_0" type="checkbox" name="contenttypes[0]" ';
         $lists['contenttypes'] .= '    value="" '.$checked_attr.' class="fc_checkradio" />';
         $lists['contenttypes'] .= '  <label class="'.$checked_class.'" for="_contenttypes_0">';
         $lists['contenttypes'] .= '   -'.JText::_('FLEXI_ALL').'-';
         $lists['contenttypes'] .= '  </label>';
         $lists['contenttypes'] .= ' </li>';
         foreach($typeData as $type) {
         	$checked = in_array($type->value, $form_contenttypes);
         	$checked_attr = $checked ? 'checked=checked' : '';
         	$checked_class = $checked ? ' fc_highlight' : '';
         	$lists['contenttypes'] .= ' <li class="fc_checkradio_option">';
         	$lists['contenttypes'] .= '  <input href="javascript:;" onclick="fc_toggleClass(this, \'fc_highlight\');" ';
         	$lists['contenttypes'] .= '    id="_contenttypes_'.$type->value.'" type="checkbox" name="contenttypes[]" ';
         	$lists['contenttypes'] .= '    value="'.$type->value.'" '.$checked_attr.' class="fc_checkradio" />';
         	$lists['contenttypes'] .= '  <label class="'.$checked_class.'" for="_contenttypes_'.$type->value.'">';
         	$lists['contenttypes'] .= '   '.JText::_($type->text);
         	$lists['contenttypes'] .= '  </label>';
         	$lists['contenttypes'] .= ' </li>';
         }
         $lists['contenttypes'] .= '</ul>';
         */
     }
     // *** Selector of Fields for text searching
     if ($txtmode == 2 && count($fields_text)) {
         // Get selected text fields in the Search Form
         $form_txtflds = JRequest::getVar('txtflds', array());
         if (!$form_txtflds || empty($form_txtflds)) {
             $form_txtflds = array();
             //array('__FC_ALL__'); //array_keys($fields_text);
         }
         $attribs = ' multiple="multiple" size="5" class="fc_field_filter use_select2_lib fc_label_internal fc_prompt_internal"';
         $attribs .= ' data-fc_label_text="' . flexicontent_html::escapeJsText(JText::_('FLEXI_CLICK_TO_LIST'), 's') . '"';
         $attribs .= ' data-fc_prompt_text="' . flexicontent_html::escapeJsText(JText::_('FLEXI_TYPE_TO_FILTER'), 's') . '"';
         $lists['txtflds'] = JHTML::_('select.genericlist', $fields_text, 'txtflds[]', $attribs, 'name', 'label', $form_txtflds, 'txtflds');
         /*
         $checked = !count($form_txtflds) || !strlen($form_txtflds[0]);
         $checked_attr = $checked ? 'checked="checked"' : '';
         $checked_class = $checked ? 'fc_highlight' : '';
         
         $lists['txtflds']  = '<ul class="fc_field_filter fc_checkradio_group">';
         $lists['txtflds'] .= ' <li class="fc_checkradio_option fc_checkradio_special">';
         $lists['txtflds'] .= '  <input href="javascript:;" onclick="fc_toggleClass(this, \'fc_highlight\', 1);" ';
         $lists['txtflds'] .= '    id="_txtflds_0" type="checkbox" name="txtflds[0]" value="" ';
         $lists['txtflds'] .= '    value="" '.$checked_attr.' class="fc_checkradio" />';
         $lists['txtflds'] .= '  <label class="'.$checked_class.'" for="_txtflds_0">';
         $lists['txtflds'] .= '   -'.JText::_('FLEXI_ALL').'-';
         $lists['txtflds'] .= '  </label>';
         $lists['txtflds'] .= ' </li>';
         foreach($fields_text as $field) {
         	$checked = in_array($field->name, $form_txtflds);
         	$checked_attr = $checked ? 'checked=checked' : '';
         	$checked_class = $checked ? ' fc_highlight' : '';
         	$lists['txtflds'] .= ' <li class="fc_checkradio_option">';
         	$lists['txtflds'] .= '  <input href="javascript:;" onclick="fc_toggleClass(this, \'fc_highlight\');" ';
         	$lists['txtflds'] .= '    id="_txtflds_'.$field->id.'" type="checkbox" name="txtflds[]" ';
         	$lists['txtflds'] .= '    value="'.$field->name.'" '.$checked_attr.' class="fc_checkradio" />';
         	$lists['txtflds'] .= '  <label class="class=""'.$checked_class.'" for="_txtflds_'.$field->id.'">';
         	$lists['txtflds'] .= '   '.JText::_($field->label);
         	$lists['txtflds'] .= '  </label>';
         	$lists['txtflds'] .= ' </li>';
         }
         $lists['txtflds'] .= '</ul>';
         */
     }
     // *** Selector of FLEXIcontent Results Ordering
     if ($orderby_override = $params->get('orderby_override', 1)) {
         $lists['orderby'] = flexicontent_html::ordery_selector($params, $form_id, $autosubmit = 0);
     }
     // *** Selector of Pagination Limit
     if ($limit_override = $params->get('limit_override', 1)) {
         $lists['limit'] = flexicontent_html::limit_selector($params, $form_id, $autosubmit = 0);
     }
     // *** Selector of non-FLEXIcontent Results Ordering
     if ($show_searchordering = $params->get('show_searchordering', 1)) {
         // built select lists
         $orders = array();
         $orders[] = JHTML::_('select.option', 'newest', JText::_('FLEXI_ADV_NEWEST_FIRST'));
         $orders[] = JHTML::_('select.option', 'oldest', JText::_('FLEXI_ADV_OLDEST_FIRST'));
         $orders[] = JHTML::_('select.option', 'popular', JText::_('FLEXI_ADV_MOST_POP'));
         $orders[] = JHTML::_('select.option', 'alpha', JText::_('FLEXI_ADV_ALPHA'));
         $orders[] = JHTML::_('select.option', 'category', JText::_('FLEXI_ADV_SEARCH_SEC_CAT'));
         $lists['ordering'] = JHTML::_('select.genericlist', $orders, 'o', 'class="fc_field_filter use_select2_lib"', 'value', 'text', $searchordering, 'ordering');
     }
     // *** Selector for usage of Search Text
     if ($show_searchphrase = $params->get('show_searchphrase', 1)) {
         $searchphrase_names = array('natural' => 'FLEXI_NATURAL_PHRASE', 'natural_expanded' => 'FLEXI_NATURAL_PHRASE_GUESS_RELEVANT', 'all' => 'FLEXI_ALL_WORDS', 'any' => 'FLEXI_ANY_WORDS', 'exact' => 'FLEXI_EXACT_PHRASE');
         $phrases = array();
         foreach ($searchphrase_names as $searchphrase_value => $searchphrase_name) {
             $_obj = new stdClass();
             $_obj->value = $searchphrase_value;
             $_obj->text = $searchphrase_name;
             $phrases[] = $_obj;
         }
         $lists['searchphrase'] = JHTML::_('select.genericlist', $phrases, 'p', 'class="fc_field_filter use_select2_lib"', 'value', 'text', $searchphrase, 'searchphrase', $_translate = true);
         /*$lists['searchphrase']  = '<ul class="fc_field_filter fc_checkradio_group">';
         		foreach ($searchphrase_names as $searchphrase_value => $searchphrase_name) {
         			$lists['searchphrase'] .= ' <li class="fc_checkradio_option fc_checkradio_special">';
         			$checked = $searchphrase_value == $searchphrase;
         			$checked_attr = $checked ? 'checked=checked' : '';
         			$checked_class = $checked ? 'fc_highlight' : '';
         			$lists['searchphrase'] .= '  <input href="javascript:;" onclick="fc_toggleClassGrp(this.parentNode, \'fc_highlight\');" id="searchphrase_'.$searchphrase_value.'" type="radio" name="p" value="'.$searchphrase_value.'" '.$checked_attr.' />';
         			$lists['searchphrase'] .= '  <label class="'.$checked_class.'" style="display:inline-block; white-space:nowrap;" for="searchphrase_'.$searchphrase_value.'">';
         			$lists['searchphrase'] .=     JText::_($searchphrase_name);
         			$lists['searchphrase'] .= '  </label>';
         			$lists['searchphrase'] .= ' </li>';
         		}
         		$lists['searchphrase']  .= '</ul>';*/
     }
     // *** Selector for filter combination
     /*if($show_filtersop = $params->get('show_filtersop', 1)) {
     			$default_filtersop = $params->get('default_filtersop', 'all');
     			$filtersop = JRequest::getVar('filtersop', $default_filtersop);
     			$filtersop_arr		= array();
     			$filtersop_arr[] = JHTML::_('select.option',  'all', JText::_( 'FLEXI_SEARCH_ALL' ) );
     			$filtersop_arr[] = JHTML::_('select.option',  'any', JText::_( 'FLEXI_SEARCH_ANY' ) );
     			$lists['filtersop']= JHTML::_('select.radiolist',  $filtersop_arr, 'filtersop', '', 'value', 'text', $filtersop );
     		}*/
     // *** Selector of Search Areas
     // If showing this is disabled, then FLEXIcontent (advanced) search model will not use all search areas,
     // but instead it will use just 'flexicontent' search area, that is the search area of FLEXIcontent (advanced) search plugin
     if ($params->get('show_searchareas', 0)) {
         // Get Content Types currently selected in the Search Form
         $form_areas = JRequest::getVar('areas', array());
         //if ( empty($form_areas) || !count($form_areas) )  $form_areas = array('flexicontent');
         $checked = empty($form_areas) || !count($form_areas);
         $checked_attr = $checked ? 'checked="checked"' : '';
         $checked_class = $checked ? 'fc_highlight' : '';
         // Create array of area options
         $options = array();
         foreach ($areas['search'] as $area => $label) {
             $_area = new stdClass();
             $_area->text = $label;
             $_area->value = $area;
             $options[] = $_area;
         }
         $attribs = ' multiple="multiple" size="5" class="fc_field_filter use_select2_lib fc_label_internal fc_prompt_internal"';
         $attribs .= ' data-fc_label_text="' . flexicontent_html::escapeJsText(JText::_('FLEXI_CLICK_TO_LIST'), 's') . '"';
         $attribs .= ' data-fc_prompt_text="' . flexicontent_html::escapeJsText(JText::_('FLEXI_TYPE_TO_FILTER'), 's') . '"';
         $lists['areas'] = JHTML::_('select.genericlist', $options, 'areas[]', $attribs, 'value', 'text', $form_areas, 'areas', $do_jtext = true);
         /*
         $lists['areas']  = '<ul class="fc_field_filter fc_checkradio_group">';
         $lists['areas'] .= ' <li class="fc_checkradio_option fc_checkradio_special">';
         $lists['areas'] .= '  <input href="javascript:;" onclick="fc_toggleClass(this, \'fc_highlight\', 1);" ';
         $lists['areas'] .= '    id="area_0" type="checkbox" name="area[0]" ';
         $lists['areas'] .= '    value="" '.$checked_attr.' class="fc_checkradio" />';
         $lists['areas'] .= '  <label class="'.$checked_class.'" for="_txtflds_0">';
         $lists['areas'] .= '   -'.JText::_('FLEXI_CONTENT_ONLY').'-';
         $lists['areas'] .= '  </label>';
         $lists['areas'] .= ' </li>';
         foreach($areas['search'] as $area_name => $area_label) {
         	$checked = in_array($area_name, $form_areas);
         	$checked_attr = $checked ? 'checked=checked' : '';
         	$checked_class = $checked ? ' fc_highlight' : '';
         	$lists['areas'] .= ' <li class="fc_checkradio_option">';
         	$lists['areas'] .= '  <input href="javascript:;" onclick="fc_toggleClass(this, \'fc_highlight\');" ';
         	$lists['areas'] .= '    id="area_'.$area_name.'" type="checkbox" name="areas[]" ';
         	$lists['areas'] .= '    value="'.$area_name.'" '.$checked_attr.' class="fc_checkradio" />';
         	$lists['areas'] .= '  <label class="'.$checked_class.'" for="area_'.$area_name.'">';
         	$lists['areas'] .= '  '.JText::_($area_label);
         	$lists['areas'] .= '  </label>';
         	$lists['areas'] .= ' </li>';
         }
         $lists['areas'] .= '</ul>';
         */
     }
     // log the search
     FLEXIadvsearchHelper::logSearch($searchword);
     //limit searchword
     $min_word_len = $app->getUserState($option . '.min_word_len', 0);
     $min = $min_word_len ? $min_word_len : $params->get('minchars', 3);
     $max = $params->get('maxchars', 200);
     if (FLEXIadvsearchHelper::limitSearchWord($searchword, $min, $max)) {
         $error = JText::sprintf('FLEXI_SEARCH_MESSAGE', $min, $max);
     }
     // sanitise searchword
     if (FLEXIadvsearchHelper::santiseSearchWord($searchword, $state->get('match'), $min)) {
         $error = JText::_('IGNOREKEYWORD');
     }
     if (!$searchword && count(JRequest::get('post'))) {
         //$error = JText::_( 'Enter a search keyword' );
     }
     // put the filtered results back into the model
     // for next release, the checks should be done in the model perhaps...
     $state->set('keyword', $searchword);
     $filter_word_like_any = $params->get('filter_word_like_any', 0);
     if (!$error) {
         require_once JPATH_SITE . DS . 'components' . DS . 'com_flexicontent' . DS . 'helpers' . DS . 'route.php';
         $results = $this->get('data');
         $total = $this->get('total');
         $pageNav = $this->get('pagination');
         // URL-encode filter values
         foreach ($_GET as $i => $v) {
             if (substr($i, 0, 6) === "filter") {
                 $_revert = array('%21' => '!', '%2A' => '*', '%27' => "'", '%28' => '(', '%29' => ')');
                 $v = str_replace('&', '__amp__', $v);
                 $v = strtr(rawurlencode($v), $_revert);
                 $pageNav->setAdditionalUrlParam($i, $v);
             }
         }
         if ($state->get('match') == 'exact') {
             $searchwords = array($searchword);
             //$needle = $searchword;
         } else {
             $searchwords = preg_split("/\\s+/u", $searchword);
             //print_r($searchwords);
         }
         // Create regular expressions, for highlighting the matched words
         $w_regexp_highlight = array();
         foreach ($searchwords as $n => $_word) {
             $w_regexp_highlight[$_word] = mb_strlen($_word, 'utf-8') <= 2 || $n + 1 < count($searchwords) ? '#\\b(' . preg_quote($_word, '#') . ')\\b#iu' : '#\\b(' . preg_quote($_word, '#') . ')#iu';
         }
         for ($i = 0; $i < count($results); $i++) {
             $result =& $results[$i];
             if (strlen($searchwords[0])) {
                 $parts = FLEXIadvsearchHelper::prepareSearchContent($result->text, $params->get('text_chars', 200), $searchwords);
                 //if( count($parts)>1 ) { echo "<pre>"; print_r($parts); exit;}
                 foreach ($parts as $word_found => $part) {
                     if (!$word_found) {
                         continue;
                     }
                     $searchRegex = $w_regexp_highlight[$word_found];
                     $parts[$word_found] = preg_replace($searchRegex, '_fc_highlight_start_\\0_fc_highlight_end_', $part);
                 }
                 $result->text = implode($parts, " <br/> ");
                 $replace_count_total = 0;
                 // This is for LIKE %word% search for languages without spaces
                 if ($filter_word_like_any) {
                     if (strlen($word_found) <= 2) {
                         continue;
                     }
                     // Do not highlight too small words, since we do not consider spaces
                     foreach ($searchwords as $_word) {
                         $searchRegex = '#(' . preg_quote($_word, '#') . '[^\\s]*)#iu';
                         $result->text = preg_replace($searchRegex, '_fc_highlight_start_\\0_fc_highlight_end_', $result->text, 1, $replace_count);
                         if ($replace_count) {
                             $replace_count_total++;
                         }
                     }
                 }
                 $result->text = str_replace('_fc_highlight_start_', '<span class="highlight">', $result->text);
                 $result->text = str_replace('_fc_highlight_end_', '</span>', $result->text);
                 // Add some message about matches
                 /*if ( $state->get('match')=='any' ) {
                 			$text_search_header = "<u><b>".JText::sprintf('Text Search matched at least %d %% (%d out of %d words)', $replace_count_total/count($searchwords) * 100, $replace_count_total, count($searchwords)).": </b></u><br/>";
                 		} else if ( $state->get('match')=='all' ) {
                 			$text_search_header = "<u><b>".JText::sprintf('Text Search (all %d words required)', count($searchwords)).": </b></u><br/>";
                 		} else if ( $state->get('match')=='exact' ) {
                 			$text_search_header = "<u><b>".JText::_('Text Search (exact phrase)').": </b></u><br/>";
                 		} else if ( $state->get('match')=='natural_expanded' ) {
                 			$text_search_header = "<u><b>".JText::_('Text Search (phrase, guessing related)').": </b></u><br/>";
                 		} else if ( $state->get('match')=='natural' ) {
                 			$text_search_header = "<u><b>".JText::_('Text Search (phrase)').": </b></u><br/>";
                 		}
                 		$result->text = $text_search_header . $result->text;*/
             } else {
                 $parts = FLEXIadvsearchHelper::prepareSearchContent($result->text, $params->get('text_chars', 200), array());
                 $result->text = implode($parts, " <br/> ");
             }
             /*if ( !empty($result->fields_text) ) {
             			$result->text .= "<br/><u><b>".JText::_('Attribute filters matched')." : </b></u>";
             			$result->fields_text = str_replace('[span=highlight]', '<span class="highlight">', $result->fields_text);
             			$result->fields_text = str_replace('[/span]', '</span>', $result->fields_text);
             			$result->fields_text = str_replace('[br /]', '<br />', $result->fields_text);
             			$result->text .= $result->fields_text;
             		}*/
             $result->text = str_replace('[[[', '<', $result->text);
             $result->text = str_replace(']]]', '>', $result->text);
             $result->created = $result->created ? JHTML::Date($result->created) : '';
             $result->count = $i + 1;
         }
     }
     $this->result = JText::sprintf('FLEXI_TOTALRESULTSFOUND', $total);
     // ******************************************************************
     // Create HTML of filters (-AFTER- getData of model have been called)
     // ******************************************************************
     foreach ($filters as $filter) {
         $filter->parameters->set('display_label_filter_s', 0);
         $filter->value = JRequest::getVar('filter_' . $filter->id, false);
         //$fieldsearch = $app->getUserStateFromRequest( 'flexicontent.search.'.'filter_'.$filter->id, 'filter_'.$filter->id, array(), 'array' );
         //echo "Field name: ".$filter->name; echo ":: ". 'filter_'.$filter->id ." :: value: "; print_r($filter->value); echo "<br/>\n";
         $field_filename = $filter->iscore ? 'core' : $filter->field_type;
         FLEXIUtilities::call_FC_Field_Func($field_filename, 'onAdvSearchDisplayFilter', array(&$filter, $filter->value, $form_id));
     }
     //echo "<pre>"; print_r($_GET); exit;
     // Create links
     $link = JRoute::_(FlexicontentHelperRoute::getSearchRoute(0, $menu_matches ? $menu->id : 0));
     //$print_link = JRoute::_('index.php?view=search&pop=1&tmpl=component&print=1');
     $curr_url = str_replace('&', '&amp;', $_SERVER['REQUEST_URI']);
     $print_link = $curr_url . (strstr($curr_url, '?') ? '&amp;' : '?') . 'pop=1&amp;tmpl=component&amp;print=1';
     $pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx'));
     $this->assignRef('action', $link);
     // $uri->toString()
     $this->assignRef('print_link', $print_link);
     $this->assignRef('contenttypes', $contenttypes);
     $this->assignRef('filters', $filters);
     $this->assignRef('results', $results);
     $this->assignRef('lists', $lists);
     $this->assignRef('params', $params);
     $this->assignRef('pageNav', $pageNav);
     $this->assignRef('pageclass_sfx', $pageclass_sfx);
     $this->assignRef('typeData', $typeData);
     $this->assign('ordering', $state->get('ordering'));
     $this->assign('searchword', $searchword);
     $this->assign('searchphrase', $state->get('match'));
     $this->assign('searchareas', $areas);
     $this->assign('total', $total);
     $this->assign('error', $error);
     $this->assignRef('document', $document);
     $this->assign('form_id', $form_id);
     $this->assign('form_name', $form_name);
     $print_logging_info = $params->get('print_logging_info');
     if ($print_logging_info) {
         global $fc_run_times;
         $start_microtime = microtime(true);
     }
     parent::display($tpl);
     if ($print_logging_info) {
         @($fc_run_times['template_render'] += round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
     }
 }
 /**
  * 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;
 }
예제 #26
0
$end_text = '<div class="icon-arrow-up-2" title="' . JText::_('FLEXI_HIDE') . '" style="cursor: pointer;" onclick="fc_toggle_box_via_btn(\\\'mainChooseColBox\\\', document.getElementById(\\\'fc_mainChooseColBox_btn\\\'), \\\'btn-primary\\\');"></div>';
flexicontent_html::jscode_to_showhide_table('mainChooseColBox', 'adminListTableFCitems', $start_text, $end_text);
global $globalcats;
$cparams = JComponentHelper::getParams('com_flexicontent');
$limit = $this->pagination->limit;
$ctrl = 'items.';
$items_task = 'task=items.';
$cats_task = 'task=category.';
$db = JFactory::getDBO();
$config = JFactory::getConfig();
$nullDate = $db->getNullDate();
$user = JFactory::getUser();
//$_sh404sef = JPluginHelper::isEnabled('system', 'sh404sef') && $config->get('sef');
$_sh404sef = defined('SH404SEF_IS_RUNNING') && $config->get('sef');
$isAdmin = JFactory::getApplication()->isAdmin();
$enable_translation_groups = flexicontent_db::useAssociations();
//$cparams->get("enable_translation_groups");
$autologin = '';
//$cparams->get('autoflogin', 1) ? '&amp;fcu='.$user->username . '&amp;fcp='.$user->password : '';
$list_total_cols = 18;
if ($enable_translation_groups) {
    $list_total_cols++;
}
$list_total_cols += count($this->extra_fields);
$image_flag_path = "../media/mod_languages/images/";
$attribs_preview = ' class="fc-man-icon-s ' . $tip_class . '" title="' . flexicontent_html::getToolTip('FLEXI_PREVIEW', 'FLEXI_DISPLAY_ENTRY_IN_FRONTEND_DESC', 1, 1) . '" ';
$image_preview = JHTML::image('components/com_flexicontent/assets/images/' . 'monitor_go.png', JText::_('FLEXI_PREVIEW'), $attribs_preview);
$attribs_editlayout = ' class="fc-man-icon-s" title="' . flexicontent_html::getToolTip('FLEXI_EDIT_LAYOUT', null, 1, 1) . '" ';
$image_editlayout = JHTML::image('components/com_flexicontent/assets/images/' . 'layout_edit.png', JText::_('FLEXI_EDIT_LAYOUT'), $attribs_editlayout);
$ordering_draggable = $cparams->get('draggable_reordering', 1);
if ($this->ordering) {
예제 #27
0
 /**
  * Logic to create the view for the edit item screen
  *
  * @access public
  * @return void
  * @since 1.0
  */
 function edit()
 {
     JRequest::setVar('view', 'item');
     JRequest::setVar('hidemainmenu', 1);
     $user = JFactory::getUser();
     $session = JFactory::getSession();
     $document = JFactory::getDocument();
     // Get/Create the view
     $viewType = $document->getType();
     $viewName = $this->input->get('view', $this->default_view, 'cmd');
     $viewLayout = $this->input->get('layout', 'default', 'string');
     $view = $this->getView($viewName, $viewType, '', array('base_path' => $this->basePath, 'layout' => $viewLayout));
     // Get/Create the model
     $model = $this->getModel('item');
     // Push the model into the view (as default), later we will call the view display method instead of calling parent's display task, because it will create a 2nd model instance !!
     $view->setModel($model, true);
     $view->document = $document;
     // FORCE model to load versioned data (URL specified version or latest version (last saved))
     $version = JRequest::getVar('version', 0, 'request', 'int');
     // Load specific item version (non-zero), 0 version: is unversioned data, -1 version: is latest version (=default for edit form)
     $item = $model->getItem(null, $check_view_access = false, $no_cache = true, $force_version = $version != 0 ? $version : -1);
     // -1 version means latest
     $isnew = !$model->getId();
     $canAdd = $model->getItemAccess()->get('access-create');
     $canEdit = $model->getItemAccess()->get('access-edit');
     if (!$canEdit) {
         // No edit privilege, check if item is editable till logoff
         if ($session->has('rendered_uneditable', 'flexicontent')) {
             $rendered_uneditable = $session->get('rendered_uneditable', array(), 'flexicontent');
             $canEdit = isset($rendered_uneditable[$model->get('id')]) && $rendered_uneditable[$model->get('id')];
         }
     }
     // New item: check if user can create in at least one category
     if ($isnew) {
         // A. Check create privilege
         if (!$canAdd) {
             JError::raiseNotice(403, JText::_('FLEXI_NO_ACCESS_CREATE'));
             $this->setRedirect('index.php?option=com_flexicontent&view=items', '');
             return;
         }
         // Get User Group / Author parameters
         $db = JFactory::getDBO();
         $authorparams = flexicontent_db::getUserConfig($user->id);
         $max_auth_limit = intval($authorparams->get('max_auth_limit', 0));
         // maximum number of content items the user can create
         // B. Check if max authored content limit reached
         if ($max_auth_limit) {
             $db->setQuery('SELECT COUNT(id) FROM #__content WHERE created_by = ' . $user->id);
             $authored_count = $db->loadResult();
             if ($authored_count >= $max_auth_limit) {
                 JError::raiseNotice(403, JText::sprintf('FLEXI_ALERTNOTAUTH_CREATE_MORE', $max_auth_limit));
                 $this->setRedirect('index.php?option=com_flexicontent&view=items', '');
                 return;
             }
         }
         // C. Check if Content Type can be created by current user
         $typeid = JRequest::getVar('typeid', 0, '', 'int');
         if ($typeid) {
             $canCreateType = $model->canCreateType(array($typeid), true, $types);
             // Can create given Content Type
         } else {
             $canCreateType = $model->canCreateType();
             // Can create at least one Content Type
         }
         if (!$canCreateType) {
             $type_name = isset($types[${$typeid}]) ? '"' . JText::_($types[${$typeid}]->name) . '"' : JText::_('FLEXI_ANY');
             $msg = JText::sprintf('FLEXI_NO_ACCESS_CREATE_CONTENT_OF_TYPE', $type_name);
             JError::raiseNotice(403, $msg);
             $this->setRedirect('index.php?option=com_flexicontent&view=items', '');
             return;
         }
     } else {
         if (!$canEdit) {
             JError::raiseNotice(403, JText::_('FLEXI_NO_ACCESS_EDIT'));
             $this->setRedirect('index.php?option=com_flexicontent&view=items', '');
             return;
         }
     }
     // Check if record is checked out by other editor
     if ($model->isCheckedOut($user->get('id'))) {
         JError::raiseNotice(500, JText::_('FLEXI_EDITED_BY_ANOTHER_ADMIN'));
         $this->setRedirect('index.php?option=com_flexicontent&view=items', '');
         return;
     }
     // Checkout the record and proceed to edit form
     if (!$model->checkout()) {
         JError::raiseWarning(500, $model->getError());
         $this->setRedirect('index.php?option=com_flexicontent&view=items', '');
         return;
     }
     // Call display method of the view, instead of calling parent's display task, because it will create a 2nd model instance !!
     $view->display();
     //parent::display();
 }
예제 #28
0
    /**
     * Creates the item submit form
     *
     * @since 1.0
     */
    function _displayForm($tpl)
    {
        jimport('joomla.html.parameter');
        // ... we use some strings from administrator part
        // load english language file for 'com_content' component then override with current language file
        JFactory::getLanguage()->load('com_content', JPATH_ADMINISTRATOR, 'en-GB', true);
        JFactory::getLanguage()->load('com_content', JPATH_ADMINISTRATOR, null, true);
        // load english language file for 'com_flexicontent' component then override with current language file
        JFactory::getLanguage()->load('com_flexicontent', JPATH_ADMINISTRATOR, 'en-GB', true);
        JFactory::getLanguage()->load('com_flexicontent', JPATH_ADMINISTRATOR, null, true);
        // ********************************
        // Initialize variables, flags, etc
        // ********************************
        $app = JFactory::getApplication();
        $dispatcher = JDispatcher::getInstance();
        $document = JFactory::getDocument();
        $session = JFactory::getSession();
        $user = JFactory::getUser();
        $db = JFactory::getDBO();
        $uri = JFactory::getURI();
        $nullDate = $db->getNullDate();
        $menu = $app->getMenu()->getActive();
        // We do not have item parameters yet, but we need to do some work before creating the item
        // Get the COMPONENT only parameter
        $params = new JRegistry();
        $cparams = JComponentHelper::getParams('com_flexicontent');
        $params->merge($cparams);
        // Merge the active menu parameters
        if ($menu) {
            $params->merge($menu->params);
        }
        // Some flags
        $enable_translation_groups = flexicontent_db::useAssociations();
        //$params->get("enable_translation_groups");
        $print_logging_info = $params->get('print_logging_info');
        if ($print_logging_info) {
            global $fc_run_times;
        }
        // *****************
        // Load JS/CSS files
        // *****************
        FLEXI_J30GE ? JHtml::_('behavior.framework', true) : JHTML::_('behavior.mootools');
        flexicontent_html::loadFramework('jQuery');
        flexicontent_html::loadFramework('select2');
        flexicontent_html::loadFramework('flexi-lib');
        // Load custom behaviours: form validation, popup tooltips
        JHTML::_('behavior.formvalidation');
        // load default validation JS to make sure it is overriden
        JHTML::_('behavior.tooltip');
        if (FLEXI_J30GE) {
            JHtml::_('bootstrap.tooltip');
        }
        //JHTML::_('script', 'joomla.javascript.js', 'includes/js/');
        // Add css files to the document <head> section (also load CSS joomla template override)
        $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontent.css');
        if (file_exists(JPATH_SITE . DS . 'templates' . DS . $app->getTemplate() . DS . 'css' . DS . 'flexicontent.css')) {
            $document->addStyleSheet($this->baseurl . '/templates/' . $app->getTemplate() . '/css/flexicontent.css');
        }
        // Fields common CSS
        $document->addStyleSheet($this->baseurl . '/components/com_flexicontent/assets/css/flexi_form_fields.css');
        // Load backend / frontend shared and Joomla version specific CSS (different for frontend / backend)
        FLEXI_J30GE ? $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/j3x.css') : $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/j25.css');
        // Add js function to overload the joomla submitform
        $document->addScript(JURI::base(true) . '/components/com_flexicontent/assets/js/admin.js');
        $document->addScript(JURI::base(true) . '/components/com_flexicontent/assets/js/validate.js');
        // Add js function for custom code used by FLEXIcontent item form
        $document->addScript(JURI::base(true) . '/components/com_flexicontent/assets/js/itemscreen.js');
        // *********************************************************
        // Get item data and create item form (that loads item data)
        // *********************************************************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $model = $this->getModel();
        // ** WE NEED TO get OR decide the Content Type, before we call the getItem
        // ** We rely on typeid Request variable to decide type for new items so make sure this is set,
        // ZERO means allow user to select type, but if user is only allowed a single type, then autoselect it!
        // Try type from session
        $jdata = $app->getUserState('com_flexicontent.edit.item.data');
        //print_r($jdata);
        if (!empty($jdata['type_id'])) {
            JRequest::setVar('typeid', (int) $jdata['type_id']);
            // This also forces zero if value not set
        } else {
            if ($menu && isset($menu->query['typeid'])) {
                JRequest::setVar('typeid', (int) $menu->query['typeid']);
                // This also forces zero if value not set
            }
        }
        $new_typeid = JRequest::getVar('typeid', 0, '', 'int');
        // Verify type is allowed to the user
        if (!$new_typeid) {
            $types = $model->getTypeslist($type_ids_arr = false, $check_perms = true, $_published = true);
            if ($types && count($types) == 1) {
                $new_typeid = $types[0]->id;
            }
            JRequest::setVar('typeid', $new_typeid);
            $canCreateType = true;
        }
        // FORCE model to load versioned data (URL specified version or latest version (last saved))
        $version = JRequest::getVar('version', 0, 'request', 'int');
        // Load specific item version (non-zero), 0 version: is unversioned data, -1 version: is latest version (=default for edit form)
        $item = $model->getItem(null, $check_view_access = false, $no_cache = true, $force_version = $version != 0 ? $version : -1);
        // -1 version means latest
        // Replace component/menu 'params' with thee merged component/category/type/item/menu ETC ... parameters
        $params =& $item->parameters;
        if ($print_logging_info) {
            $fc_run_times['get_item_data'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // Load permissions (used by form template)
        $perms = $this->_getItemPerms($item);
        // Create submit configuration (for new items) into the session, this is needed before creating the item form
        $submitConf = $this->_createSubmitConf($item, $perms);
        // Most core field are created via calling methods of the form (J2.5)
        $form = $this->get('Form');
        // is new item and ownership Flags
        $isnew = !$item->id;
        $isOwner = $item->created_by == $user->get('id');
        // Get available types and the currently selected/requested type
        $types = $model->getTypeslist();
        $typesselected = $model->getTypesselected();
        // Get type parameters, these are needed besides the 'merged' item parameters, e.g. to get Type's default layout
        $tparams = $this->get('Typeparams');
        $tparams = new JRegistry($tparams);
        // *********************************************************************************************************
        // Get language stuff, and also load Template-Specific language file to override or add new language strings
        // *********************************************************************************************************
        if ($enable_translation_groups) {
            $langAssocs = $params->get('uselang_fe') == 1 ? $this->get('LangAssocs') : false;
        }
        $langs = FLEXIUtilities::getLanguages('code');
        FLEXIUtilities::loadTemplateLanguageFile($params->get('ilayout', 'default'));
        // *************************************
        // Create captcha field via custom logic
        // *************************************
        // create and set (into HTTP request) a unique item id for plugins that needed it
        if ($item->id) {
            $unique_tmp_itemid = $item->id;
        } else {
            $unique_tmp_itemid = $app->getUserState('com_flexicontent.edit.item.unique_tmp_itemid');
            $unique_tmp_itemid = $unique_tmp_itemid ? $unique_tmp_itemid : date('_Y_m_d_h_i_s_', time()) . uniqid(true);
        }
        //print_r($unique_tmp_itemid);
        JRequest::setVar('unique_tmp_itemid', $unique_tmp_itemid);
        // Component / Menu Item parameters
        $allowunauthorize = $params->get('allowunauthorize', 0);
        // allow unauthorised user to submit new content
        $unauthorized_page = $params->get('unauthorized_page', '');
        // page URL for unauthorized users (via global configuration)
        $notauth_itemid = $params->get('notauthurl', '');
        // menu itemid (to redirect) when user is not authorized to create content
        // Create captcha field or messages
        // Maybe some code can be removed by using Joomla's built-in form element (in XML file), instead of calling the captcha plugin ourselves
        $use_captcha = $params->get('use_captcha', 1);
        // 1 for guests, 2 for any user
        $captcha_formop = $params->get('captcha_formop', 0);
        // 0 for submit, 1 for submit/edit (aka always)
        $display_captcha = $use_captcha >= 2 || $use_captcha == 1 && $user->guest;
        $display_captcha = $display_captcha && ($isnew || $captcha_formop);
        // Trigger the configured captcha plugin
        if ($display_captcha) {
            // Get configured captcha plugin
            $c_plugin = $params->get('captcha', $app->getCfg('captcha'));
            // TODO add param to override default
            if ($c_plugin) {
                $c_name = 'captcha_response_field';
                $c_id = $c_plugin == 'recaptcha' ? 'dynamic_recaptcha_1' : 'fc_dynamic_captcha';
                $c_class = ' required';
                $c_namespace = 'fc_item_form';
                // Try to load the configured captcha plugin, (check if disabled or uninstalled), Joomla will enqueue an error message if needed
                $captcha_obj = JCaptcha::getInstance($c_plugin, array('namespace' => $c_namespace));
                if ($captcha_obj) {
                    $captcha_field = $captcha_obj->display($c_name, $c_id, $c_class);
                    $label_class = 'flexi_label';
                    $label_class .= FLEXI_J30GE ? ' hasTooltip' : ' hasTip';
                    $label_tooltip = flexicontent_html::getToolTip(null, 'FLEXI_CAPTCHA_ENTER_CODE_DESC', 1, 1);
                    $captcha_field = '
						<label id="' . $c_name . '-lbl" for="' . $c_name . '" class="' . $label_class . '" title="' . $label_tooltip . '" >
						' . JText::_('FLEXI_CAPTCHA_ENTER_CODE') . '
						</label>
						<div id="container_fcfield_' . $c_plugin . '" class="container_fcfield container_fcfield_name_' . $c_plugin . '">
							<div class="fcfieldval_container valuebox fcfieldval_container_' . $c_plugin . '">
							' . $captcha_field . '
							</div>
						</div>';
                }
            }
        }
        // *******************************
        // CHECK EDIT / CREATE PERMISSIONS
        // *******************************
        // User Group / Author parameters
        $authorparams = flexicontent_db::getUserConfig($user->id);
        $max_auth_limit = intval($authorparams->get('max_auth_limit', 0));
        // maximum number of content items the user can create
        $hasTmpEdit = false;
        $hasCoupon = false;
        // Check session
        if ($session->has('rendered_uneditable', 'flexicontent')) {
            $rendered_uneditable = $session->get('rendered_uneditable', array(), 'flexicontent');
            $hasTmpEdit = !empty($rendered_uneditable[$model->get('id')]);
            $hasCoupon = !empty($rendered_uneditable[$model->get('id')]) && $rendered_uneditable[$model->get('id')] == 2;
            // editable via coupon
        }
        if (!$isnew) {
            // EDIT action
            // Finally check if item is currently being checked-out (currently being edited)
            if ($model->isCheckedOut($user->get('id'))) {
                $msg = JText::sprintf('FLEXI_DESCBEINGEDITTED', $model->get('title'));
                $app->redirect(JRoute::_('index.php?view=' . FLEXI_ITEMVIEW . '&cid=' . $model->get('catid') . '&id=' . $model->get('id'), false), $msg);
            }
            //Checkout the item
            $model->checkout();
            // Get edit access, this includes privileges edit and edit-own and the temporary EDIT flag ('rendered_uneditable')
            $canEdit = $model->getItemAccess()->get('access-edit');
            // If no edit privilege, check if edit COUPON was provided
            if (!$canEdit) {
                $edittok = JRequest::getCmd('edittok', false);
                if ($edittok) {
                    $query = 'SHOW TABLES LIKE "' . $app->getCfg('dbprefix') . 'flexicontent_edit_coupons"';
                    $db->setQuery($query);
                    $tbl_exists = (bool) count($db->loadObjectList());
                    if ($tbl_exists) {
                        $query = 'SELECT * FROM #__flexicontent_edit_coupons ' . ' WHERE token = ' . $db->Quote($edittok) . ' AND id = ' . $model->get('id');
                        $db->setQuery($query);
                        $tokdata = $db->loadObject();
                        if ($tokdata) {
                            $hasCoupon = true;
                            $rendered_uneditable = $session->get('rendered_uneditable', array(), 'flexicontent');
                            $rendered_uneditable[$model->get('id')] = 2;
                            // 2: indicates, that has edit via EDIT Coupon
                            $session->set('rendered_uneditable', $rendered_uneditable, 'flexicontent');
                            $canEdit = 1;
                        } else {
                            JError::raiseNotice(403, JText::_('EDIT_TOKEN_IS_INVALID') . ' : ' . $edittok);
                        }
                    }
                }
            }
            // Edit check finished, throw error if needed
            if (!$canEdit) {
                if ($user->guest) {
                    $uri = JFactory::getURI();
                    $return = $uri->toString();
                    $fcreturn = serialize(array('id' => @$this->_item->id, 'cid' => $cid));
                    // a special url parameter, used by some SEF code
                    $com_users = FLEXI_J16GE ? 'com_users' : 'com_user';
                    $url = $params->get('login_page', 'index.php?option=' . $com_users . '&view=login');
                    $return = strtr(base64_encode($return), '+/=', '-_,');
                    $url .= '&return=' . $return;
                    //$url .= '&return='.urlencode(base64_encode($return));
                    $url .= '&fcreturn=' . base64_encode($fcreturn);
                    JError::raiseWarning(403, JText::sprintf("FLEXI_LOGIN_TO_ACCESS", $url));
                    $app->redirect($url);
                } else {
                    if ($unauthorized_page) {
                        //  unauthorized page via global configuration
                        JError::raiseNotice(403, JText::_('FLEXI_ALERTNOTAUTH_TASK'));
                        $app->redirect($unauthorized_page);
                    } else {
                        // user isn't authorize to edit this content
                        $msg = JText::_('FLEXI_ALERTNOTAUTH_TASK');
                        if (FLEXI_J16GE) {
                            throw new Exception($msg, 403);
                        } else {
                            JError::raiseError(403, $msg);
                        }
                    }
                }
            }
        } else {
            // CREATE action
            // Get create access, this includes check of creating in at least one category, and type's "create items"
            $canAdd = $model->getItemAccess()->get('access-create');
            $not_authorised = !$canAdd;
            // Check if Content Type can be created by current user
            if (empty($canCreateType)) {
                if ($new_typeid) {
                    // not needed, already done be model when type_id is set, check and remove
                    $canCreateType = $model->canCreateType(array($new_typeid));
                    // Can create given Content Type
                } else {
                    // needed not done be model yet
                    $canCreateType = $model->canCreateType();
                    // Can create at least one Content Type
                }
            }
            $not_authorised = $not_authorised || !$canCreateType;
            // Allow item submission by unauthorized users, ... even guests ...
            if ($allowunauthorize == 2) {
                $allowunauthorize = !$user->guest;
            }
            if ($not_authorised && !$allowunauthorize) {
                if (!$canCreateType) {
                    $type_name = isset($types[$new_typeid]) ? '"' . JText::_($types[$new_typeid]->name) . '"' : JText::_('FLEXI_ANY');
                    $msg = JText::sprintf('FLEXI_NO_ACCESS_CREATE_CONTENT_OF_TYPE', $type_name);
                } else {
                    $msg = JText::_('FLEXI_ALERTNOTAUTH_CREATE');
                }
            } else {
                if ($max_auth_limit) {
                    $db->setQuery('SELECT COUNT(id) FROM #__content WHERE created_by = ' . $user->id);
                    $authored_count = $db->loadResult();
                    $content_is_limited = $authored_count >= $max_auth_limit;
                    $msg = $content_is_limited ? JText::sprintf('FLEXI_ALERTNOTAUTH_CREATE_MORE', $max_auth_limit) : '';
                }
            }
            if ($not_authorised && !$allowunauthorize || @$content_is_limited) {
                // User isn't authorize to add ANY content
                if ($notauth_menu = $app->getMenu()->getItem($notauth_itemid)) {
                    // a. custom unauthorized submission page via menu item
                    $internal_link_vars = @$notauth_menu->component ? '&Itemid=' . $notauth_itemid . '&option=' . $notauth_menu->component : '';
                    $notauthurl = JRoute::_($notauth_menu->link . $internal_link_vars, false);
                    JError::raiseNotice(403, $msg);
                    $app->redirect($notauthurl);
                } else {
                    if ($unauthorized_page) {
                        // b. General unauthorized page via global configuration
                        JError::raiseNotice(403, $msg);
                        $app->redirect($unauthorized_page);
                    } else {
                        // c. Finally fallback to raising a 403 Exception/Error that will redirect to site's default 403 unauthorized page
                        if (FLEXI_J16GE) {
                            throw new Exception($msg, 403);
                        } else {
                            JError::raiseError(403, $msg);
                        }
                    }
                }
            }
        }
        // *****************************************************************************
        // Get (CORE & CUSTOM) fields and their VERSIONED values and then
        // (a) Apply Content Type Customization to CORE fields (label, description, etc)
        // (b) Create the edit html of the CUSTOM fields by triggering 'onDisplayField'
        // *****************************************************************************
        // Check if saving an item that translates an original content in site's default language
        $site_default = substr(flexicontent_html::getSiteDefaultLang(), 0, 2);
        $is_content_default_lang = $site_default == substr($item->language, 0, 2);
        //$modify_untraslatable_values = $enable_translation_groups && !$is_content_default_lang; // && $item->lang_parent_id && $item->lang_parent_id!=$item->id;
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $fields = $this->get('Extrafields');
        $item->fields =& $fields;
        if ($print_logging_info) {
            $fc_run_times['get_field_vals'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $jcustom = $app->getUserState('com_flexicontent.edit.item.custom');
        //print_r($jcustom);
        foreach ($fields as $field) {
            // a. Apply CONTENT TYPE customizations to CORE FIELDS, e.g a type specific label & description
            // NOTE: the field parameters are already created so there is not need to call this for CUSTOM fields, which do not have CONTENT TYPE customizations
            if ($field->iscore) {
                FlexicontentFields::loadFieldConfig($field, $item);
            }
            // b. Create field 's editing HTML (the form field)
            // NOTE: this is DONE only for CUSTOM fields, since form field html is created by the form for all CORE fields, EXCEPTION is the 'text' field (see bellow)
            if (!$field->iscore) {
                if (isset($jcustom[$field->name])) {
                    $field->value = array();
                    foreach ($jcustom[$field->name] as $i => $_val) {
                        $field->value[$i] = $_val;
                    }
                }
                $is_editable = !$field->valueseditable || $user->authorise('flexicontent.editfieldvalues', 'com_flexicontent.field.' . $field->id);
                if ($is_editable) {
                    FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayField', array(&$field, &$item));
                    if ($field->untranslatable) {
                        $field->html = '<div class="alert alert-info fc-small fc-iblock">' . JText::_('FLEXI_FIELD_VALUE_IS_NON_TRANSLATABLE') . '</div>' . "\n" . $field->html;
                    }
                } else {
                    if ($field->valueseditable == 1) {
                        $field->html = '<div class="fc-mssg fc-note">' . JText::_($field->parameters->get('no_acc_msg_form') ? $field->parameters->get('no_acc_msg_form') : 'FLEXI_NO_ACCESS_LEVEL_TO_EDIT_FIELD') . '</div>';
                    } else {
                        if ($field->valueseditable == 2) {
                            FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayFieldValue', array(&$field, $item));
                            $field->html = '<div class="fc-mssg fc-note">' . JText::_($field->parameters->get('no_acc_msg_form') ? $field->parameters->get('no_acc_msg_form') : 'FLEXI_NO_ACCESS_LEVEL_TO_EDIT_FIELD') . '</div>' . "\n" . $field->display;
                        } else {
                            if ($field->valueseditable == 3) {
                                FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayFieldValue', array(&$field, $item));
                                $field->html = $field->display;
                            } else {
                                if ($field->valueseditable == 4) {
                                    $field->html = '';
                                    $field->formhidden = 4;
                                }
                            }
                        }
                    }
                }
            }
            // c. Create main text field, via calling the display function of the textarea field (will also check for tabs)
            if ($field->field_type == 'maintext') {
                if (isset($item->item_translations)) {
                    $shortcode = substr($item->language, 0, 2);
                    foreach ($item->item_translations as $lang_id => $t) {
                        if ($shortcode == $t->shortcode) {
                            continue;
                        }
                        $field->name = array('jfdata', $t->shortcode, 'text');
                        $field->value[0] = html_entity_decode($t->fields->text->value, ENT_QUOTES, 'UTF-8');
                        FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
                        $t->fields->text->tab_labels = $field->tab_labels;
                        $t->fields->text->html = $field->html;
                        unset($field->tab_labels);
                        unset($field->html);
                    }
                }
                $field->name = 'text';
                // NOTE: We use the text created by the model and not the text retrieved by the CORE plugin code, which maybe overwritten with JoomFish/Falang data
                $field->value[0] = $item->text;
                // do not decode special characters this was handled during saving !
                // Render the field's (form) HTML
                FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
            }
        }
        if ($print_logging_info) {
            $fc_run_times['render_field_html'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // Tags used by the item
        $usedtagsids = $this->get('UsedtagsIds');
        // NOTE: This will normally return the already set versioned value of tags ($item->tags)
        $usedtagsdata = $model->getUsedtagsData($usedtagsids);
        // Get the edit lists
        $lists = $this->_buildEditLists($perms, $params, $authorparams);
        // Get number of subscribers
        $subscribers = $this->get('SubscribersCount');
        // Get menu overridden categories/main category fields
        $menuCats = $this->_getMenuCats($item, $perms);
        // Create placement configuration for CORE properties
        $placementConf = $this->_createPlacementConf($item, $fields);
        // Item language related vars
        $languages = FLEXIUtilities::getLanguages();
        $itemlang = new stdClass();
        $itemlang->shortcode = substr($item->language, 0, 2);
        $itemlang->name = $languages->{$item->language}->name;
        $itemlang->image = '<img src="' . @$languages->{$item->language}->imgsrc . '" alt="' . $languages->{$item->language}->name . '" />';
        //Load the JEditor object
        $editor = JFactory::getEditor();
        // **********************************************************
        // Calculate a (browser window) page title and a page heading
        // **********************************************************
        // Verify menu item points to current FLEXIcontent object
        if ($menu) {
            $menu_matches = false;
            $view_ok = FLEXI_ITEMVIEW == @$menu->query['view'] || 'article' == @$menu->query['view'];
            $menu_matches = $view_ok;
            //$menu_params = $menu->params;  // Get active menu item parameters
        } else {
            $menu_matches = false;
        }
        // MENU ITEM matched, use its page heading (but use menu title if the former is not set)
        if ($menu_matches) {
            $default_heading = FLEXI_J16GE ? $menu->title : $menu->name;
            // Cross set (show_) page_heading / page_title for compatibility of J2.5+ with J1.5 template (and for J1.5 with J2.5 template)
            $params->def('page_heading', $params->get('page_title', $default_heading));
            $params->def('page_title', $params->get('page_heading', $default_heading));
            $params->def('show_page_heading', $params->get('show_page_title', 0));
            $params->def('show_page_title', $params->get('show_page_heading', 0));
        } else {
            // Calculate default page heading (=called page title in J1.5), which in turn will be document title below !! ...
            $default_heading = !$isnew ? JText::_('FLEXI_EDIT') : JText::_('FLEXI_NEW');
            // Decide to show page heading (=J1.5 page title), there is no need for this in item view
            $show_default_heading = 0;
            // Set both (show_) page_heading / page_title for compatibility of J2.5+ with J1.5 template (and for J1.5 with J2.5 template)
            $params->set('page_title', $default_heading);
            $params->set('page_heading', $default_heading);
            $params->set('show_page_heading', $show_default_heading);
            $params->set('show_page_title', $show_default_heading);
        }
        // ************************************************************
        // Create the document title, by from page title and other data
        // ************************************************************
        // Use the page heading as document title, (already calculated above via 'appropriate' logic ...)
        $doc_title = $params->get('page_title');
        // Check and prepend or append site name
        // Add Site Name to page title
        if ($app->getCfg('sitename_pagetitles', 0) == 1) {
            $doc_title = $app->getCfg('sitename') . " - " . $doc_title;
        } elseif ($app->getCfg('sitename_pagetitles', 0) == 2) {
            $doc_title = $doc_title . " - " . $app->getCfg('sitename');
        }
        // Finally, set document title
        $document->setTitle($doc_title);
        // Add title to pathway
        $pathway = $app->getPathWay();
        $pathway->addItem($doc_title, '');
        // Get pageclass suffix
        $pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx'));
        // Ensure the row data is safe html
        // @TODO: check if this is really required as it conflicts with the escape function in the tmpl
        //JFilterOutput::objectHTMLSafe( $item );
        $this->assign('action', $uri->toString());
        $this->assignRef('item', $item);
        $this->assignRef('form', $form);
        // most core field are created via calling methods of the form (J2.5)
        if ($enable_translation_groups) {
            $this->assignRef('lang_assocs', $langAssocs);
        }
        $this->assignRef('langs', $langs);
        $this->assignRef('params', $params);
        $this->assignRef('lists', $lists);
        $this->assignRef('subscribers', $subscribers);
        $this->assignRef('editor', $editor);
        $this->assignRef('user', $user);
        $this->assignRef('usedtagsdata', $usedtagsdata);
        $this->assignRef('fields', $fields);
        $this->assignRef('tparams', $tparams);
        $this->assignRef('perms', $perms);
        $this->assignRef('document', $document);
        $this->assignRef('nullDate', $nullDate);
        $this->assignRef('menuCats', $menuCats);
        $this->assignRef('submitConf', $submitConf);
        $this->assignRef('placementConf', $placementConf);
        $this->assignRef('itemlang', $itemlang);
        $this->assignRef('pageclass_sfx', $pageclass_sfx);
        $this->assign('captcha_errmsg', @$captcha_errmsg);
        $this->assign('captcha_field', @$captcha_field);
        // ****************************************************************
        // SET INTO THE FORM, parameter values for various parameter groups
        // ****************************************************************
        if (JHTML::_('date', $item->publish_down, 'Y') <= 1969 || $item->publish_down == $nullDate) {
            $item->publish_down = JText::_('FLEXI_NEVER');
        }
        // ****************************
        // Handle Template related work
        // ****************************
        // (a) Get the templates structures used to create form fields for template parameters
        $themes = flexicontent_tmpl::getTemplates();
        $tmpls_all = $themes->items;
        // (b) Get Content Type allowed templates
        $allowed_tmpls = $tparams->get('allowed_ilayouts');
        $type_default_layout = $tparams->get('ilayout', 'default');
        if (empty($allowed_tmpls)) {
            $allowed_tmpls = array();
        }
        if (!is_array($allowed_tmpls)) {
            $allowed_tmpls = explode("|", $allowed_tmpls);
        }
        // (c) Add default layout, unless all templates allowed (=array is empty)
        if (count($allowed_tmpls) && !in_array($type_default_layout, $allowed_tmpls)) {
            $allowed_tmpls[] = $type_default_layout;
        }
        // (d) Create array of template data according to the allowed templates for current content type
        if (count($allowed_tmpls)) {
            foreach ($tmpls_all as $tmpl) {
                if (in_array($tmpl->name, $allowed_tmpls)) {
                    $tmpls[] = $tmpl;
                }
            }
        } else {
            $tmpls = $tmpls_all;
        }
        // (e) Apply Template Parameters values into the form fields structures
        foreach ($tmpls as $tmpl) {
            if (FLEXI_J16GE) {
                $jform = new JForm('com_flexicontent.template.item', array('control' => 'jform', 'load_data' => true));
                $jform->load($tmpl->params);
                $tmpl->params = $jform;
                foreach ($tmpl->params->getGroup('attribs') as $field) {
                    $fieldname = $field->__get('fieldname');
                    $value = $item->itemparams->get($fieldname);
                    if (strlen($value)) {
                        $tmpl->params->setValue($fieldname, 'attribs', $value);
                    }
                }
            } else {
                $tmpl->params->loadINI($item->attribs);
            }
        }
        $this->assignRef('tmpls', $tmpls);
        // Clear custom form data from session
        $app->setUserState($form->option . '.edit.' . $form->context . '.custom', false);
        $app->setUserState($form->option . '.edit.' . $form->context . '.jfdata', false);
        $app->setUserState($form->option . '.edit.' . $form->context . '.unique_tmp_itemid', false);
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        parent::display($tpl);
        if ($print_logging_info) {
            $fc_run_times['form_rendering'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
    }
예제 #29
0
 static function createItemsListSQL(&$params, &$_item_data = null, $isform = 0, $reverse_field = 0, &$parentfield, &$parentitem)
 {
     $db = JFactory::getDBO();
     $sfx = $isform ? '_form' : '';
     // Get data like aliases and published state
     $publish_where = '';
     if ($params->get('use_publish_dates', 1)) {
         // 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();
         $publish_where = ' AND ( i.publish_up = ' . $db->Quote($nullDate) . ' OR i.publish_up <= ' . $_nowDate . ' )';
         $publish_where .= ' AND ( i.publish_down = ' . $db->Quote($nullDate) . ' OR i.publish_down >= ' . $_nowDate . ' )';
     }
     // item IDs via reversing a relation field
     if ($reverse_field) {
         $item_join = ' JOIN #__flexicontent_fields_item_relations AS fi_rel' . '  ON i.id=fi_rel.item_id AND fi_rel.field_id=' . $reverse_field . ' AND CAST(fi_rel.value AS UNSIGNED)=' . $parentitem->id;
     } else {
         $item_where = ' AND i.id IN (' . implode(",", array_keys($_item_data)) . ')';
     }
     // Get orderby SQL CLAUSE ('ordering' is passed by reference but no frontend user override is used (we give empty 'request_var')
     $order = $params->get('orderby' . $sfx, 'alpha');
     $orderby = flexicontent_db::buildItemOrderBy($params, $order, $request_var = '', $config_param = '', $item_tbl_alias = 'i', $relcat_tbl_alias = 'rel', '', '', $sfx, $support_2nd_lvl = true);
     $orderby_join = '';
     // Create JOIN for ordering items by a custom field (use SFC)
     if ('field' == $order[1]) {
         $orderbycustomfieldid = (int) $params->get('orderbycustomfieldid' . $sfx, 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 ($sfx == '' && '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 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 author name
     if (in_array('author', $order) || in_array('rauthor', $order)) {
         $orderby_join .= ' LEFT JOIN #__users AS u ON u.id = i.created_by';
     }
     // Because query includes specific items it should be fast
     $query = 'SELECT i.*, ext.type_id,' . ' GROUP_CONCAT(c.id SEPARATOR  ",") AS catidlist, ' . ' GROUP_CONCAT(c.alias SEPARATOR  ",") AS  cataliaslist ' . @$orderby_col . ' FROM #__content AS i ' . ' LEFT JOIN #__flexicontent_items_ext AS ext ON i.id=ext.item_id ' . @$item_join . @$orderby_join . ' LEFT JOIN #__flexicontent_cats_item_relations AS rel ON i.id=rel.itemid ' . ' LEFT JOIN #__categories AS c ON c.id=rel.catid ' . ' WHERE 1 ' . @$item_where . $publish_where . ' GROUP BY i.id ' . $orderby;
     //echo "<pre>".$query."</pre>";
     return $query;
 }
예제 #30
0
 /**
  * Method to get if language of items is initialized properly
  * 
  * @access	public
  * @return	boolean	True on success
  * @since 1.5
  */
 function getItemsNoLang()
 {
     static $return;
     if ($return !== NULL) {
         return $return;
     }
     $return = false;
     $cparams = JComponentHelper::getParams('com_flexicontent');
     $enable_translation_groups = flexicontent_db::useAssociations();
     //$cparams->get("enable_translation_groups");
     // Check for emtpy language in flexicontent EXT table
     $query = "SELECT COUNT(*)" . " FROM #__flexicontent_items_ext as ie" . " WHERE ie.language='' " . " LIMIT 1";
     $this->_db->setQuery($query);
     $cnt = $this->_db->loadResult();
     if ($cnt) {
         return $return = true;
     }
     $query = "SELECT COUNT(*)" . " FROM #__content as i" . " WHERE i.language=''" . " LIMIT 1";
     $this->_db->setQuery($query);
     $cnt = $this->_db->loadResult();
     if ($cnt) {
         return $return = true;
     }
     $query = "SELECT COUNT(*)" . " FROM #__content as i" . " JOIN #__flexicontent_items_ext as ie ON i.id=ie.item_id " . " WHERE i.language<>ie.language" . " LIMIT 1";
     $this->_db->setQuery($query);
     $cnt = $this->_db->loadResult();
     if ($cnt) {
         return $return = true;
     }
     // Check for not yet transfered language associations
     $query = "SELECT COUNT(*)" . " FROM #__flexicontent_items_ext as ie" . " WHERE ie.lang_parent_id <> 0" . " LIMIT 1";
     $this->_db->setQuery($query);
     $cnt = $this->_db->loadResult();
     if ($cnt) {
         return $return = true;
     }
     return $return;
 }