Example #1
0
 function display($tpl = null)
 {
     $user = JFactory::getUser();
     $dispatcher = JDispatcher::getInstance();
     // Initialize some variables
     $item =& $this->get('Item');
     $params =& $item->parameters;
     $fields =& $this->get('Extrafields');
     $tags =& $item->tags;
     $categories =& $item->categories;
     $favourites = $item->favourites;
     $favoured = $item->favoured;
     // process the new plugins
     JPluginHelper::importPlugin('content', 'image');
     if (!FLEXI_J16GE) {
         $dispatcher->trigger('onPrepareContent', array(&$item, &$params, 0));
     } else {
         $dispatcher->trigger('onContentPrepare', array('com_content.article', &$item, &$params, 0));
     }
     $document = JFactory::getDocument();
     // set document information
     $document->setTitle($item->title);
     $document->setName($item->alias);
     $document->setDescription($item->metadesc);
     $document->setMetaData('keywords', $item->metakey);
     // prepare header lines
     $document->setHeader($this->_getHeaderText($item, $params));
     $pdf_format_fields = trim($params->get("pdf_format_fields"));
     $pdf_format_fields = !$pdf_format_fields ? array() : preg_split("/[\\s]*,[\\s]*/", $pdf_format_fields);
     $methodnames = array();
     foreach ($pdf_format_fields as $pdf_format_field) {
         @(list($fieldname, $methodname) = preg_split("/[\\s]*:[\\s]*/", $pdf_format_field));
         $methodnames[$fieldname] = empty($methodname) ? 'display' : $methodname;
     }
     // IF no fields set then just print the item's description text
     if (!count($pdf_format_fields)) {
         echo $item->text;
         return;
     }
     foreach ($fields as $field) {
         if (!isset($methodnames[$field->name])) {
             continue;
         }
         if ($field->iscore) {
             FlexicontentFields::loadFieldConfig($field, $item);
             //$results = $dispatcher->trigger('onDisplayCoreFieldValue', array( &$field, $item, &$params, $tags, $categories, $favourites, $favoured ));
             FLEXIUtilities::call_FC_Field_Func('core', 'onDisplayCoreFieldValue', array(&$field, $item, &$params, $tags, $categories, $favourites, $favoured));
         } else {
             //$results = $dispatcher->trigger('onDisplayFieldValue', array( &$field, $item ));
             FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayFieldValue', array(&$field, $item));
         }
         if (@$field->display) {
             echo '<b>' . $field->label . '</b>: ';
             echo $field->display . '<br /><br />';
         }
     }
 }
Example #2
0
 function getInput()
 {
     $doc = JFactory::getDocument();
     $db = JFactory::getDBO();
     // Get field configuration
     if (FLEXI_J16GE) {
         $node =& $this->element;
         $attributes = get_object_vars($node->attributes());
         $attributes = $attributes['@attributes'];
     } else {
         $attributes =& $node->_attributes;
     }
     // Get values
     $values = FLEXI_J16GE ? $this->value : $value;
     if (empty($values)) {
         $values = array();
     } else {
         if (!is_array($values)) {
             $values = !FLEXI_J16GE ? array($values) : explode("|", $values);
         }
     }
     // Field name and HTML tag id
     $fieldname = FLEXI_J16GE ? $this->name : $control_name . '[' . $name . ']';
     $element_id = FLEXI_J16GE ? $this->id : $control_name . $name;
     // Create options
     $langs = array();
     // Add 'use global' (no value option)
     if (@$attributes['use_global']) {
         $langs[] = JHTML::_('select.option', '', JText::_('FLEXI_USE_GLOBAL'));
     }
     // Add 'please select' (no value option)
     if (@$attributes['please_select']) {
         $langs[] = JHTML::_('select.option', '', JText::_('FLEXI_PLEASE_SELECT'));
     }
     $languages = FLEXIUtilities::getlanguageslist();
     foreach ($languages as $lang) {
         $langs[] = JHTML::_('select.option', $lang->code, $lang->name);
     }
     // Create HTML tag parameters
     $attribs = ' style="float:left;" ';
     if (@$attributes['multiple'] == 'multiple' || @$attributes['multiple'] == 'true') {
         $attribs .= ' multiple="multiple" ';
         $attribs .= @$attributes['size'] ? ' size="' . @$attributes['size'] . '" ' : ' size="6" ';
         $fieldname .= !FLEXI_J16GE ? "[]" : "";
         // NOTE: this added automatically in J2.5
         $maximize_link = "<a style='display:inline-block;" . (FLEXI_J16GE ? 'float:left; margin: 6px 0px 0px 18px;' : 'margin:0px 0px 6px 12px') . "' href='javascript:;' onclick='{$element_id} = document.getElementById(\"{$element_id}\"); if ({$element_id}.size<16) { {$element_id}_oldsize={$element_id}.size; {$element_id}.size=16;} else { {$element_id}.size={$element_id}_oldsize; } ' >Maximize/Minimize</a>";
     } else {
         $attribs .= 'class="inputbox"';
         $maximize_link = '';
     }
     if ($onchange = @$attributes['onchange']) {
         $attribs .= ' onchange="' . $onchange . '"';
     }
     // Render the field's HTML
     $html = JHTML::_('select.genericlist', $langs, $fieldname, $attribs, 'value', 'text', $values, $element_id);
     return $html . $maximize_link;
 }
Example #3
0
 function display($tpl = null)
 {
     $mainframe = JFactory::getApplication();
     $option = JRequest::getVar('option');
     //initialise variables
     $db = JFactory::getDBO();
     $document = JFactory::getDocument();
     $template = $mainframe->getTemplate();
     $dispatcher = JDispatcher::getInstance();
     $rev = JRequest::getInt('version', '', 'request');
     $codemode = JRequest::getInt('codemode', 0);
     $cparams = JComponentHelper::getParams('com_flexicontent');
     FLEXI_J30GE ? JHtml::_('behavior.framework', true) : JHTML::_('behavior.mootools');
     flexicontent_html::loadFramework('jQuery');
     JHTML::_('behavior.tooltip');
     JHTML::_('behavior.modal');
     //a trick to avoid loosing general style in modal window
     $css = 'body, td, th { font-size: 11px; } .novalue { color: gray; font-style: italic; }';
     $document->addStyleDeclaration($css);
     //Get data from the model
     $model = $this->getModel();
     $row = $this->get('Item');
     $fields = $this->get('Extrafields');
     $versions = $this->get('VersionList');
     $tparams = $this->get('Typeparams');
     // Create the type parameters
     $tparams = FLEXI_J16GE ? new JRegistry($tparams) : new JParameter($tparams);
     // Add html to field object trought plugins
     foreach ($fields as $field) {
         if ($field->value) {
             //$results = $dispatcher->trigger('onDisplayFieldValue', array( &$field, $row ));
             $fieldname = $field->iscore ? 'core' : $field->field_type;
             FLEXIUtilities::call_FC_Field_Func($fieldname, 'onDisplayFieldValue', array(&$field, $row));
         } else {
             $field->display = '<span class="novalue">' . JText::_('FLEXI_NO_VALUE') . '</span>';
         }
         if ($field->version) {
             //$results = $dispatcher->trigger('onDisplayFieldValue', array( &$field, $row, $field->version, 'displayversion' ));
             $fieldname = $field->iscore ? 'core' : $field->field_type;
             FLEXIUtilities::call_FC_Field_Func($fieldname, 'onDisplayFieldValue', array(&$field, $row, $field->version, 'displayversion'));
         } else {
             $field->displayversion = '<span class="novalue">' . JText::_('FLEXI_NO_VALUE') . '</span>';
         }
     }
     //assign data to template
     $this->assignRef('document', $document);
     $this->assignRef('row', $row);
     $this->assignRef('fields', $fields);
     $this->assignRef('versions', $versions);
     $this->assignRef('rev', $rev);
     $this->assignRef('tparams', $tparams);
     $this->assignRef('cparams', $cparams);
     $this->assignRef('codemode', $codemode);
     parent::display($tpl);
 }
 function getInput()
 {
     $doc = JFactory::getDocument();
     $db = JFactory::getDBO();
     // Get field configuration
     $node =& $this->element;
     $attributes = get_object_vars($node->attributes());
     $attributes = $attributes['@attributes'];
     // Get values
     $values = $this->value;
     if (empty($values)) {
         $values = array();
     } else {
         if (!is_array($values)) {
             $values = explode("|", $values);
         }
     }
     // Field name and HTML tag id
     $fieldname = $this->name;
     $element_id = $this->id;
     // Create options
     $langs = array();
     // Add 'use global' (no value option)
     if (@$attributes['use_global']) {
         $langs[] = JHTML::_('select.option', '', JText::_('FLEXI_USE_GLOBAL'));
     }
     // Add 'please select' (no value option)
     if (@$attributes['please_select']) {
         $langs[] = JHTML::_('select.option', '', JText::_('FLEXI_PLEASE_SELECT'));
     }
     foreach ($node->children() as $option) {
         $val = $option->attributes()->value;
         $text = JText::_(FLEXI_J30GE ? $option->__toString() : $option->data());
         $langs[] = JHTML::_('select.option', $val, $text);
     }
     $languages = FLEXIUtilities::getlanguageslist();
     foreach ($languages as $lang) {
         $langs[] = JHTML::_('select.option', $lang->code, $lang->name);
     }
     // Create HTML tag parameters
     $attribs = '';
     $classes = 'use_select2_lib';
     if (@$attributes['multiple'] == 'multiple' || @$attributes['multiple'] == 'true') {
         $attribs .= ' multiple="multiple" ';
         $attribs .= @$attributes['size'] ? ' size="' . @$attributes['size'] . '" ' : ' size="6" ';
     }
     if ($onchange = @$attributes['onchange']) {
         $attribs .= ' onchange="' . $onchange . '"';
     }
     $attribs .= ' class="' . $classes . '" ';
     // Render the field's HTML
     return JHTML::_('select.genericlist', $langs, $fieldname, $attribs, 'value', 'text', $values, $element_id);
 }
Example #5
0
	public function onDisplayFieldValue(&$field, $item, $values=null, $prop='display')
	{
		// execute the code only if the field type match the plugin type
		if ( !in_array($field->field_type, self::$field_types) ) return;
		
		static $all_langs = null;
		
		$props_type = $field->parameters->get('props_type');
		if ($props_type == 'language')
		{
			if ($all_langs===null) {
				$all_langs= FLEXIUtilities::getLanguages($hash='code');
			}
			$lang_data = $all_langs->{$item->language};
			
			$field->{$prop} = @$lang_data->title_native ? $lang_data->title_native : $lang_data->name;
		}
	}
Example #6
0
 public function onDisplayFieldValue(&$field, $item, $values = null, $prop = 'display')
 {
     if (!in_array($field->field_type, self::$field_types)) {
         return;
     }
     static $all_langs = null;
     $props_type = $field->parameters->get('props_type');
     if ($props_type == 'language') {
         if ($all_langs === null) {
             $all_langs = FLEXIUtilities::getLanguages($hash = 'code');
         }
         $lang_data = $all_langs->{$item->language};
         $field->{$prop} = @$lang_data->title_native ? $lang_data->title_native : $lang_data->name;
     } else {
         if ($props_type == 'alias') {
             $field->{$prop} = $item->{$props_type};
         } else {
             $field->{$prop} = $props_type;
         }
     }
 }
Example #7
0
 /**
  * Method to get the active filter result
  * 
  * @access private
  * @return string
  * @since 1.5
  */
 function _getFiltered(&$filter, $value, $return_sql = true)
 {
     $field_type = $filter->field_type;
     // Sanitize filter values as integers for field that use integer values
     if (in_array($field_type, array('createdby', 'modifiedby', 'type', 'categories', 'tags'))) {
         $values = is_array($value) ? $value : array($value);
         foreach ($values as $i => $v) {
             $values[$i] = (int) $v;
         }
     }
     switch ($field_type) {
         case 'createdby':
             $filter_query = ' AND i.created_by IN (' . implode(",", $values) . ')';
             // no db quoting needed since these were typecasted to ints
             break;
         case 'modifiedby':
             $filter_query = ' AND i.modified_by IN (' . implode(",", $values) . ')';
             // no db quoting needed since these were typecasted to ints
             break;
         case 'type':
             //$filter_query = ' AND ie.type_id IN ('. implode(",", $values) .')';   // no db quoting needed since these were typecasted to ints
             $query = 'SELECT item_id' . ' FROM #__flexicontent_items_ext' . ' WHERE type_id IN (' . implode(",", $values) . ')';
             //$filter_query = ' AND i.id IN (' . $query . ')';
             break;
         case 'state':
             $stateids = array('PE' => -3, 'OQ' => -4, 'IP' => -5, 'P' => 1, 'U' => 0, 'A' => FLEXI_J16GE ? 2 : -1, 'T' => -2);
             $values = is_array($value) ? $value : array($value);
             $filt_states = array();
             foreach ($values as $i => $v) {
                 if (isset($stateids[$v])) {
                     $filt_states[] = $stateids[$v];
                 }
             }
             $filter_query = !count($values) ? ' AND 0 ' : ' AND i.state IN (' . implode(",", $filt_states) . ')';
             // no db quoting needed since these were typecasted to ints
             break;
         case 'categories':
             //$filter_query = ' AND rel.catid IN ('. implode(",", $values) .')';
             global $globalcats;
             $cparams = $this->_params;
             $display_subcats = $cparams->get('display_subcategories_items', 2);
             // include subcategory items
             $query_catids = array();
             foreach ($values as $id) {
                 $query_catids[$id] = 1;
                 if ($display_subcats == 2 && !empty($globalcats[$id]->descendantsarray)) {
                     foreach ($globalcats[$id]->descendantsarray as $subcatid) {
                         $query_catids[$subcatid] = 1;
                     }
                 }
             }
             $query_catids = array_keys($query_catids);
             $query = 'SELECT itemid' . ' FROM #__flexicontent_cats_item_relations' . ' WHERE catid IN (' . implode(",", $query_catids) . ')';
             //$filter_query = ' AND i.id IN (' . $query . ')';
             break;
         case 'tags':
             $query = 'SELECT itemid' . ' FROM #__flexicontent_tags_item_relations' . ' WHERE tid IN (' . implode(",", $values) . ')';
             //$filter_query = ' AND i.id IN (' . $query . ')';
             break;
         default:
             // Make sure plugin file of current file is loaded and then check if custom filtering function exists
             $field_type_file = $filter->iscore ? 'core' : $field_type;
             $path = JPATH_ROOT . DS . 'plugins' . DS . 'flexicontent_fields' . DS . strtolower($field_type_file) . (FLEXI_J16GE ? DS . strtolower($field_type_file) : "") . '.php';
             if (file_exists($path)) {
                 require_once $path;
                 $method_exists = method_exists("plgFlexicontent_fields{$field_type_file}", "getFiltered");
             }
             // Use custom field filtering if 'getFiltered' plugin method exists, otherwise try to use our default filtering function
             $filtered = !@$method_exists ? FlexicontentFields::getFiltered($filter, $value, $return_sql) : FLEXIUtilities::call_FC_Field_Func($field_type_file, 'getFiltered', array(&$filter, &$value, &$return_sql));
             break;
     }
     if (!isset($filter_query)) {
         if (isset($filtered)) {
             // nothing to do
         } else {
             if (!isset($query)) {
                 $filtered = '';
                 echo "Unhandled case for filter: " . $field->name . " in 'FlexicontentModelCategory::getFiltered()', query variable not set<br/>\n";
             } else {
                 if (!$return_sql) {
                     //echo "<br>GET FILTERED Items (cat model) -- [".$filter->name."] using in-query ids :<br>". $query."<br>\n";
                     $db = JFactory::getDBO();
                     $db->setQuery($query);
                     $filtered = $db->loadColumn();
                     if ($db->getErrorNum()) {
                         JFactory::getApplication()->enqueueMessage(__FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($db->getErrorMsg()), 'error');
                     }
                 } else {
                     if ($return_sql === 2) {
                         $db = JFactory::getDBO();
                         static $iids_tblname = array();
                         if (!isset($iids_tblname[$filter->id])) {
                             $iids_tblname[$filter->id] = 'fc_filter_iids_' . $filter->id;
                         }
                         $tmp_tbl = $iids_tblname[$filter->id];
                         try {
                             // Use sub-query on temporary table
                             $db->setQuery('CREATE TEMPORARY TABLE IF NOT EXISTS ' . $tmp_tbl . ' (id INT, KEY(`id`))');
                             $db->query();
                             $db->setQuery('TRUNCATE TABLE ' . $tmp_tbl);
                             $db->query();
                             $db->setQuery('INSERT INTO ' . $tmp_tbl . ' ' . $query);
                             $db->query();
                             $_query = $query;
                             $query = 'SELECT id FROM ' . $tmp_tbl;
                             //echo "<br/><br/>GET FILTERED Items (cat model) -- [".$filter->name."] using temporary table: ".$query." for :".$_query ." <br/><br/>";
                             /*$db->setQuery($query);
                             		$data = $db->loadObjectList();
                             		echo "<pre>";
                             		print_r($data);
                             		exit;*/
                         } catch (Exception $e) {
                             // Ignore table creation error
                             //if ($db->getErrorNum())  echo 'SQL QUERY ERROR:<br/>'.nl2br($db->getErrorMsg());
                             //echo "<br/><br/>GET FILTERED Items (cat model) -- [".$filter->name."] using subquery: ".$query." <br/><br/>";
                         }
                     } else {
                         //echo "<br/><br/>GET FILTERED Items (cat model) -- [".$filter->name."] using subquery: ".$query." <br/><br/>";
                     }
                 }
             }
         }
         if (!isset($filtered) && isset($query)) {
             $filtered = ' AND i.id IN (' . $query . ')';
         }
         // 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
         $filter_query = is_array($filtered) ? ' AND i.id IN (' . implode(',', $filtered) . ')' : $filtered;
     }
     //echo "<br/>".$filter_query."<br/>";
     return $filter_query;
 }
Example #8
0
 /**
  * Logic to set the access level of the Items
  *
  * @access public
  * @return void
  * @since 1.5
  */
 function access()
 {
     // Check for request forgeries
     JRequest::checkToken() or jexit('Invalid Token');
     $user = JFactory::getUser();
     $cid = JRequest::getVar('cid', array(0), 'post', 'array');
     $id = (int) $cid[0];
     $task = JRequest::getVar('task');
     // Decide / Retrieve new access level
     $accesses = JRequest::getVar('access', array(0), 'post', 'array');
     $access = $accesses[$id];
     $model = $this->getModel('item');
     $canEdit = $model->getItemAccess()->get('access-edit');
     // Check if user can edit the item
     if (!$canEdit) {
         $msg_noauth = JText::_('FLEXI_CANNOT_CHANGE_ACCLEVEL_ASSETS');
         $msg_noauth .= ": " . implode(',', $non_auth_cid) . " - " . JText::_('FLEXI_REASON_NO_PUBLISH_PERMISSION');
     }
     if ($msg_noauth) {
         JError::raiseNotice(500, $msg_noauth);
         $this->setRedirect('index.php?option=com_flexicontent&view=items', '');
         return;
     }
     $model = $this->getModel('items');
     if (!$model->saveaccess($id, $access)) {
         $msg = JText::_('FLEXI_ERROR_SETTING_ITEM_ACCESS_LEVEL');
         JError::raiseWarning(500, $msg . " " . $model->getError());
         $msg = '';
     } else {
         $cache = FLEXIUtilities::getCache($group = '', 0);
         $cache->clean('com_flexicontent_items');
         $cache->clean('com_flexicontent_filters');
         $cache = FLEXIUtilities::getCache($group = '', 1);
         $cache->clean('com_flexicontent_items');
         $cache->clean('com_flexicontent_filters');
     }
     $this->setRedirect('index.php?option=com_flexicontent&view=items');
 }
    function onDisplayField(&$field, &$item)
    {
        if (!in_array($field->field_type, self::$field_types)) {
            return;
        }
        // Check max allowed version
        $manifest_path = JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_flexicontent' . DS . 'manifest.xml';
        $com_xml = JApplicationHelper::parseXMLInstallFile($manifest_path);
        if (version_compare(str_replace(' ', '.', $com_xml['version']), str_replace(' ', '.', self::$prior_to_version), '>=')) {
            echo '
			<span class="fc-note fc-nobgimage fc-mssg">
				Warning: installed version of Field: \'<b>' . $field->field_type . '</b>\' was meant for FLEXIcontent versions prior to: v' . self::$prior_to_version . ' <br/> It may or may not work properly in later versions<br/>
			</span>';
        }
        $field->label = JText::_($field->label);
        $use_ingroup = 0;
        // Field grouped should not be recursively grouped
        if ($use_ingroup) {
            $field->formhidden = 3;
        }
        if ($use_ingroup && empty($field->ingroup)) {
            return;
        }
        $compact_edit = $field->parameters->get('compact_edit', 0);
        // initialize framework objects and other variables
        $document = JFactory::getDocument();
        $db = JFactory::getDBO();
        $tooltip_class = FLEXI_J30GE ? 'hasTooltip' : 'hasTip';
        // ****************
        // Number of values
        // ****************
        $multiple = $use_ingroup || (int) $field->parameters->get('allow_multiple', 0);
        $max_values = $use_ingroup ? 0 : (int) $field->parameters->get('max_values', 0);
        $required = $field->parameters->get('required', 0);
        $required = $required ? ' required' : '';
        $add_position = (int) $field->parameters->get('add_position', 3);
        // **************
        // Value handling
        // **************
        // Get fields belonging to this field group
        $grouped_fields = $this->getGroupFields($field);
        // Get values of fields making sure that also empty values are created too
        $max_count = 1;
        $this->getGroupFieldsValues($grouped_fields, $item, $max_count);
        // Render Form HTML of the field
        foreach ($grouped_fields as $field_id => $grouped_field) {
            for ($n = count($grouped_field->value); $n < $max_count; $n++) {
                $grouped_field->value[$n] = null;
            }
            $grouped_field->ingroup = 1;
            $grouped_field->item_id = $item->id;
            FLEXIUtilities::call_FC_Field_Func($grouped_field->field_type, 'onDisplayField', array(&$grouped_field, &$item));
            unset($grouped_field->ingroup);
        }
        $js = "";
        $css = "";
        if ($multiple) {
            // Add the drag and drop sorting feature
            if (!$use_ingroup) {
                $js .= "\n\t\t\tjQuery(document).ready(function(){\n\t\t\t\tjQuery('#sortables_" . $field->id . "').sortable({\n\t\t\t\t\thandle: '.fcfield-drag-handle',\n\t\t\t\t\tcontainment: 'parent',\n\t\t\t\t\ttolerance: 'pointer'\n\t\t\t\t});\n\t\t\t});\n\t\t\t";
            }
            $js .= "\n\t\t\tjQuery(document).ready(function(){" . ($compact_edit == 2 ? "jQuery('#sortables_" . $field->id . "').find('.toggle_group_down').trigger('click');" : "") . ($compact_edit == 1 ? "jQuery('#sortables_" . $field->id . "').find('.toggle_group_up').trigger('click');" : "") . "});\n\t\t\t";
            if ($max_values) {
                FLEXI_J16GE ? JText::script("FLEXI_FIELD_MAX_ALLOWED_VALUES_REACHED", true) : fcjsJText::script("FLEXI_FIELD_MAX_ALLOWED_VALUES_REACHED", true);
            }
            $js .= "\n\t\t\tvar uniqueRowNum" . $field->id . "\t= " . $max_count . ";  // Unique row number incremented only\n\t\t\tvar rowCount" . $field->id . "\t= " . $max_count . ";      // Counts existing rows to be able to limit a max number of values\n\t\t\tvar maxValues" . $field->id . " = " . $max_values . ";\n\t\t\t";
            // Create function call for add/deleting Field values
            $addField_pattern = "\n\t\t\t\tvar fieldval_box = groupval_box.find('.fcfieldval_container__GRP_FID_');\n\t\t\t\tfieldval_box.find('.invalid').removeClass('invalid').attr('aria-invalid', 'false');\n\t\t\t\tvar newSubLabel = fieldval_box.prev('label.sub_label');\n\t\t\t\tvar newLabelFor = 'custom_%s_'+uniqueRowNum" . $field->id . ";\n\t\t\t\tnewSubLabel.attr('for', newLabelFor);\n\t\t\t\tnewSubLabel.attr('for_bck', newLabelFor);\n\t\t\t\tfcflabels[ newLabelFor ] = newSubLabel;\n\t\t\t\taddField_GRP_FID_(null, groupval_box, groupval_box.find('.fcfieldval_container__GRP_FID_'), add_params);";
            $delField_pattern = "\n\t\t\t\tif(rowCount" . $field->id . " == 1)\n\t\t\t\t{\n\t\t\t\t\t// We need to update the current grouped label of the field if this was the last element being re-added\n\t\t\t\t\tvar fieldval_box = groupval_box.find('.fcfieldval_container__GRP_FID_');\n\t\t\t\t\tfieldval_box.find('.invalid').removeClass('invalid').attr('aria-invalid', 'false');\n\t\t\t\t\tvar newSubLabel = fieldval_box.prev('label.sub_label');\n\t\t\t\t\tvar newLabelFor = 'custom_%s_'+uniqueRowNum" . $field->id . ";\n\t\t\t\t\tnewSubLabel.attr('for', newLabelFor);\n\t\t\t\t\tnewSubLabel.attr('for_bck', newLabelFor);\n\t\t\t\t\tfcflabels[ newLabelFor ] = newSubLabel;\n\t\t\t\t}\n\t\t\t\tdeleteField_GRP_FID_(null, groupval_box, groupval_box.find('.fcfieldval_container__GRP_FID_'));\n\t\t\t\t";
            $addField_funcs = $delField_funcs = '';
            foreach ($grouped_fields as $field_id => $grouped_field) {
                $addField_funcs .= str_replace("_GRP_FID_", $grouped_field->id, sprintf($addField_pattern, $grouped_field->name));
                $delField_funcs .= str_replace("_GRP_FID_", $grouped_field->id, sprintf($delField_pattern, $grouped_field->name));
            }
            $js .= "\n\t\t\tfunction addField" . $field->id . "(el, groupval_box, fieldval_box, params)\n\t\t\t{\n\t\t\t\tvar insert_before   = (typeof params!== 'undefined' && typeof params.insert_before   !== 'undefined') ? params.insert_before   : 0;\n\t\t\t\tvar remove_previous = (typeof params!== 'undefined' && typeof params.remove_previous !== 'undefined') ? params.remove_previous : 0;\n\t\t\t\tvar scroll_visible  = (typeof params!== 'undefined' && typeof params.scroll_visible  !== 'undefined') ? params.scroll_visible  : 1;\n\t\t\t\tvar animate_visible = (typeof params!== 'undefined' && typeof params.animate_visible !== 'undefined') ? params.animate_visible : 1;\n\t\t\t\t\n\t\t\t\tif((rowCount" . $field->id . " >= maxValues" . $field->id . ") && (maxValues" . $field->id . " != 0)) {\n\t\t\t\t\talert(Joomla.JText._('FLEXI_FIELD_MAX_ALLOWED_VALUES_REACHED') + maxValues" . $field->id . ");\n\t\t\t\t\treturn 'cancel';\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Find last container of fields and clone it to create a new container of fields\n\t\t\t\tvar lastField = fieldval_box ? fieldval_box : jQuery(el).prev().children().last();\n\t\t\t\tvar newField  = lastField.clone();\n\t\t\t\t\n\t\t\t\t// Need to at least change FORM field names and HTML tag IDs before adding the container to the DOM\n\t\t\t\tvar theSet = newField.find('input, select');\n\t\t\t\tvar nr = 0;\n\t\t\t\ttheSet.each(function() {\n\t\t\t\t\tvar elem = jQuery(this);\n\t\t\t\t\telem.attr('name', '_duplicated_" . $field->id . "_'+uniqueRowNum" . $field->id . "+'_'+nr);\n\t\t\t\t\telem.attr('id', '_duplicated_" . $field->id . "_'+uniqueRowNum" . $field->id . "+'_'+nr);\n\t\t\t\t\tnr++;\n\t\t\t\t});\n\t\t\t\t";
            // Add new field to DOM
            $js .= "\n\t\t\t\tlastField ?\n\t\t\t\t\t(insert_before ? newField.insertBefore( lastField ) : newField.insertAfter( lastField ) ) :\n\t\t\t\t\tnewField.appendTo( jQuery('#sortables_" . $field->id . "') ) ;\n\t\t\t\t";
            // Add new element to sortable objects (if field not in group)
            if (!$use_ingroup) {
                $js .= "\n\t\t\t\tjQuery('#sortables_" . $field->id . "').sortable({\n\t\t\t\t\thandle: '.fcfield-drag-handle',\n\t\t\t\t\tcontainment: 'parent',\n\t\t\t\t\ttolerance: 'pointer'\n\t\t\t\t});\n\t\t\t\t\n\t\t\t\t// Add new values for each field\n\t\t\t\tvar groupval_box = newField;\n\t\t\t\tvar add_params = {remove_previous: 1, scroll_visible: 0, animate_visible: 0};\n\t\t\t\t" . $addField_funcs . "\n\t\t\t\t";
            }
            // Readd prettyCheckable and remove previous if so requested
            $js .= "\n\t\t\t\tif (remove_previous) lastField.remove();\n\t\t\t\t";
            // Show new field, increment counters
            $js .= "\n\t\t\t\t//newField.fadeOut({ duration: 400, easing: 'swing' }).fadeIn({ duration: 200, easing: 'swing' });\n\t\t\t\tif (scroll_visible) fc_scrollIntoView(newField, 1);\n\t\t\t\tif (animate_visible) newField.css({opacity: 0.1}).animate({ opacity: 1 }, 800);\n\t\t\t\t\n\t\t\t\t// Enable tooltips on new element\n\t\t\t\tnewField.find('.hasTooltip').tooltip({'html': true,'container': newField});\n\t\t\t\t\n\t\t\t\trowCount" . $field->id . "++;       // incremented / decremented\n\t\t\t\tuniqueRowNum" . $field->id . "++;   // incremented only\n\t\t\t}\n\n\t\t\tfunction deleteField" . $field->id . "(el)\n\t\t\t{\n\t\t\t\tvar row = jQuery(el).closest('li');\n\t\t\t\t\n\t\t\t\t// Do cleanup by calling the deleteField of each individual field, these functions will re-add last element as empty if needed\n\t\t\t\tvar groupval_box = jQuery(el).closest('li');\n\t\t\t\t" . $delField_funcs . "\n\t\t\t\tif(rowCount" . $field->id . " == 1)\n\t\t\t\t{\n\t\t\t\t\tuniqueRowNum" . $field->id . "++;   // increment unique row id, since last group was re-added\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Also remove the group field values container if not last one\n\t\t\t\tif(rowCount" . $field->id . " > 1) {\n\t\t\t\t\t// Destroy the remove/add/etc buttons, so that they are not reclicked, while we do the hide effect (before DOM removal of field value)\n\t\t\t\t\trow.find('.fcfield-delvalue').remove();\n\t\t\t\t\trow.find('.fcfield-insertvalue').remove();\n\t\t\t\t\trow.find('.fcfield-drag-handle').remove();\n\t\t\t\t\t// Do hide effect then remove from DOM\n\t\t\t\t\trow.fadeOut(420, function(){ this.remove(); });\n\t\t\t\t\trowCount" . $field->id . "--;\n\t\t\t\t}\n\t\t\t}\n\t\t\t";
            $css .= '';
            $remove_button = '<span class="fcfield-delvalue" title="' . JText::_('FLEXI_REMOVE_VALUE') . '" onclick="deleteField' . $field->id . '(this);"></span>';
            $move2 = '<span class="fcfield-drag-handle" title="' . JText::_('FLEXI_CLICK_TO_DRAG') . '"></span>';
            $add_here = '';
            $add_here .= $add_position == 2 || $add_position == 3 ? '<span class="fcfield-insertvalue fc_before" onclick="addField' . $field->id . '(null, jQuery(this).closest(\'ul\'), jQuery(this).closest(\'li\'), {insert_before: 1});" title="' . JText::_('FLEXI_ADD_BEFORE') . '"></span> ' : '';
            $add_here .= $add_position == 1 || $add_position == 3 ? '<span class="fcfield-insertvalue fc_after"  onclick="addField' . $field->id . '(null, jQuery(this).closest(\'ul\'), jQuery(this).closest(\'li\'), {insert_before: 0});" title="' . JText::_('FLEXI_ADD_AFTER') . '"></span> ' : '';
            if ($compact_edit) {
                $add_here .= '
				<button class="toggle_group_down btn btn-small btn-success" style="' . ($compact_edit == 2 ? 'display:none;' : '') . ' min-width: 120px;" onclick="fc_toggle_box_via_btn(jQuery(this).closest(\'li\').find(\'.fcfieldval_container_outer:not(.fcAlwaysVisibleField)\'), this, \'\', jQuery(this).next(), 1); return false;">
					<i class="icon-downarrow"></i>' . JText::_('FLEXI_FIELD_GROUP_EDIT_DETAILS') . '
				</button>
				<button class="toggle_group_up   btn btn-small" style="' . ($compact_edit == 1 ? 'display:none;' : '') . ' min-width: 120px;" onclick="fc_toggle_box_via_btn(jQuery(this).closest(\'li\').find(\'.fcfieldval_container_outer:not(.fcAlwaysVisibleField)\'), this, \'\', jQuery(this).prev(), 0); return false;">
					<i class="icon-uparrow"></i>' . JText::_('FLEXI_FIELD_GROUP_HIDE_DETAILS') . '
				</button>
			';
            }
        } else {
            $remove_button = '';
            $move2 = '';
            $add_here = '';
            $js .= '';
            $css .= '';
        }
        if ($js) {
            $document->addScriptDeclaration($js);
        }
        if ($css) {
            $document->addStyleDeclaration($css);
        }
        $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>';
        $alert_box = FLEXI_J30GE ? '<div %s class="alert alert-%s %s">' . $close_btn . '%s</div>' : '<div %s class="fc-mssg fc-%s %s">' . $close_btn . '%s</div>';
        if ($compact_edit) {
            $compact_edit_excluded = $field->parameters->get('compact_edit_excluded', array());
            if (empty($compact_edit_excluded)) {
                $compact_edit_excluded = array();
            }
            if (!is_array($compact_edit_excluded)) {
                $compact_edit_excluded = preg_split("/[\\|,]/", $compact_edit_excluded);
            }
            $compact_edit_excluded = array_flip($compact_edit_excluded);
        }
        $field->html = array();
        for ($n = 0; $n < $max_count; $n++) {
            $field->html[$n] = '
				' . ($use_ingroup ? '' : $move2) . '
				' . ($use_ingroup ? '' : $remove_button) . '
				' . ($use_ingroup || !$add_position ? '' : $add_here) . '
				';
            // Append item-form display HTML of the every field in the group
            $i = 0;
            foreach ($grouped_fields as $field_id => $grouped_field) {
                $lbl_class = 'flexi label sub_label';
                $lbl_title = '';
                // field has tooltip
                $edithelp = $grouped_field->edithelp ? $grouped_field->edithelp : 1;
                if ($grouped_field->description && ($edithelp == 1 || $edithelp == 2)) {
                    $lbl_class .= ($edithelp == 2 ? ' fc_tooltip_icon ' : ' ') . $tooltip_class;
                    $lbl_title = flexicontent_html::getToolTip(trim($field->label, ':'), $grouped_field->description, 0, 1);
                }
                $field->html[$n] .= '<div class="fcclear"></div>
				<div class="fcfieldval_container_outer' . ($compact_edit && isset($compact_edit_excluded[$field_id]) ? ' fcAlwaysVisibleField' : '') . '">
					<label class="' . $lbl_class . '" title="' . $lbl_title . '" for="custom_' . $grouped_field->name . '_' . $n . '" for_bck="custom_' . $grouped_field->name . '_' . $n . '">' . $grouped_field->label . '</label>
					<div class="fcfieldval_container valuebox fcfieldval_container_' . $grouped_field->id . ' container_fcfield_name_' . $grouped_field->name . '" >
						' . ($grouped_field->description && $edithelp == 3 ? sprintf($alert_box, '', 'info', 'fc-nobgimage', $grouped_field->description) : '') . '
						' . @$grouped_field->html[$n] . '
					</div>
				</div>
				';
                $i++;
            }
            if (!$multiple) {
                break;
            }
            // multiple values disabled, break out of the loop, not adding further values even if the exist
        }
        // Non value HTML
        $non_value_html = '';
        foreach ($grouped_fields as $field_id => $grouped_field) {
            $non_value_html .= @$grouped_field->html[-1];
        }
        // Implode form HTML as a list
        $list_classes = "fcfield-sortables";
        $list_classes .= " fcfield-group";
        if (count($field->html)) {
            $field->html = '<li class="fcfieldval_container valuebox fcfieldval_container_' . $field->id . ' container_fcfield_name_' . $field->name . '">' . implode('</li><li class="fcfieldval_container valuebox fcfieldval_container_' . $field->id . ' container_fcfield_name_' . $field->name . '">', $field->html) . '</li>';
            $field->html = '<div id="sortables_outer_' . $field->id . '"><ul class="' . $list_classes . '" id="sortables_' . $field->id . '">' . $field->html . '</ul></div>';
        } else {
            $field->html = '';
        }
        if (!$add_position) {
            $field->html .= '<span class="fcfield-addvalue fccleared" onclick="addField' . $field->id . '(this);" title="' . JText::_('FLEXI_ADD_TO_BOTTOM') . '"></span>';
        }
        // Append non value html of fields
        $field->html = ($field->parameters->get('compact_edit_global', 0) ? '
			<div class="toggle_all_values_buttons_box">
				<span id="sortables_' . $field->id . '_btn" class="btn" onclick="fc_toggle_box_via_btn(jQuery(\'#sortables_outer_' . $field->id . '\'), this, \'\', jQuery(this).next(), 0); return false;">
					<i class="icon-uparrow"></i>' . JText::_('FLEXI_FIELD_GROUP_HIDE_VALUES') . '
				</span>
				<span id="sortables_' . $field->id . '_btn" class="btn btn-success" onclick="fc_toggle_box_via_btn(jQuery(\'#sortables_outer_' . $field->id . '\'), this, \'\', jQuery(this).prev(), 1); return false;" style="display:none;">
					<i class="icon-downarrow"></i>' . JText::_('FLEXI_FIELD_GROUP_SHOW_VALUES') . '
				</span>
			</div>
				' : '') . '
			' . $field->html . ($non_value_html ? '
				<div class="fcclear"></div>' . $non_value_html : '');
    }
 /**
  * Search method
  *
  * The sql must return the following fields that are used in a common display routine:
  *
  *   href, title, section, created, text, browsernav
  *
  * @param string Target search string
  * @param string matching option, natural|natural_expanded|exact|any|all
  * @param string ordering option, newest|oldest|popular|alpha|category
  * @param mixed An array if restricted to areas, null if search all
  */
 function onContentSearch($text, $phrase = '', $ordering = '', $areas = null)
 {
     $app = JFactory::getApplication();
     $view = JRequest::getCMD('view');
     $app->setUserState('fc_view_total_' . $view, 0);
     $app->setUserState('fc_view_limit_max_' . $view, 0);
     // Check if not requested search areas, inside this search areas of this plugin
     if (is_array($areas) && !array_intersect($areas, array_keys($this->onContentSearchAreas()))) {
         return array();
     }
     // Initialize some variables
     $db = JFactory::getDBO();
     $user = JFactory::getUser();
     $menu = $app->getMenu()->getActive();
     // Get the COMPONENT only parameters and merge current menu item parameters
     $params = clone JComponentHelper::getParams('com_flexicontent');
     if ($menu) {
         $params->merge($menu->params);
     }
     // some parameter shortcuts for SQL query
     $show_noauth = $params->get('show_noauth', 0);
     $orderby_override = $params->get('orderby_override', 1);
     // Compatibility text search (LIKE %word%) for language without spaces
     $filter_word_like_any = $params->get('filter_word_like_any', 0);
     // ************************************************
     // some parameter shortcuts common with search view
     // ************************************************
     $canseltypes = $params->get('canseltypes', 1);
     $txtmode = $params->get('txtmode', 0);
     // 0: BASIC Index, 1: ADVANCED Index without search fields user selection, 2: ADVANCED Index with search fields user selection
     // Get if text searching according to specific (single) content type
     $show_txtfields = $params->get('show_txtfields', 1);
     //0:hide, 1:according to content, 2:use custom configuration
     $show_txtfields = $txtmode ? 0 : $show_txtfields;
     // disable this flag if using BASIC index for text search
     // Get if filtering according to specific (single) content type
     $show_filters = $params->get('show_filters', 1);
     //0:hide, 1:according to content, 2:use custom configuration
     // Force single type selection and showing the content type selector
     $type_based_search = $show_filters == 1 || $show_txtfields == 1;
     $canseltypes = $type_based_search ? 1 : $canseltypes;
     // ********************************************************************
     // Get Content Types allowed for user selection in the Search Form
     // Also retrieve their configuration, plus the currently selected types
     // ********************************************************************
     // Get them from configuration
     $contenttypes = $params->get('contenttypes', array());
     // Sanitize them
     $contenttypes = !is_array($contenttypes) ? array($contenttypes) : $contenttypes;
     $contenttypes = array_unique(array_map('intval', $contenttypes));
     // Make sure these are integers since we will be using them UNQUOTED
     // Force hidden content type selection if only 1 content type was initially configured
     $canseltypes = count($contenttypes) == 1 ? 0 : $canseltypes;
     // Type data and configuration (parameters), if no content types specified then all will be retrieved
     $typeData = flexicontent_db::getTypeData(implode(",", $contenttypes));
     $contenttypes = array();
     foreach ($typeData as $tdata) {
         $contenttypes[] = $tdata->id;
     }
     // Get Content Types to use either those currently selected in the Search Form, or those hard-configured in the search menu item
     if ($canseltypes) {
         $form_contenttypes = JRequest::getVar('contenttypes', array());
         // Sanitize them
         $form_contenttypes = !is_array($form_contenttypes) ? array($form_contenttypes) : $form_contenttypes;
         $form_contenttypes = array_unique(array_map('intval', $form_contenttypes));
         // Make sure these are integers since we will be using them UNQUOTED
         $_contenttypes = array_intersect($contenttypes, $form_contenttypes);
         if (!empty($_contenttypes)) {
             $contenttypes = $_contenttypes;
         }
         // catch empty case: no content types were given or not-allowed content types were passed
     }
     // Check for zero content type (can occur during sanitizing content ids to integers)
     if (!empty($contenttypes)) {
         foreach ($contenttypes as $i => $v) {
             if (!strlen($contenttypes[$i])) {
                 unset($contenttypes[$i]);
             }
         }
     }
     // Type based seach, get a single content type (first one, if more than 1 were given ...)
     if ($type_based_search && !empty($contenttypes)) {
         $single_contenttype = reset($contenttypes);
         $contenttypes = array($single_contenttype);
     } else {
         $single_contenttype = false;
     }
     // *************************************
     // Text Search Fields of the search form
     // *************************************
     if (!$txtmode) {
         $txtflds = array();
         $fields_text = array();
     } else {
         $txtflds = '';
         if ($show_txtfields) {
             if ($show_txtfields == 1) {
                 $txtflds = $single_contenttype ? $typeData[$single_contenttype]->params->get('searchable', '') : '';
             } else {
                 $txtflds = $params->get('txtflds', '');
             }
         }
         // Sanitize them
         $txtflds = preg_replace("/[\"'\\\\]/u", "", $txtflds);
         $txtflds = array_unique(preg_split("/\\s*,\\s*/u", $txtflds));
         if (!strlen($txtflds[0])) {
             unset($txtflds[0]);
         }
         // Create a comma list of them
         $txtflds_list = count($txtflds) ? "'" . implode("','", $txtflds) . "'" : '';
         // Retrieve field properties/parameters, verifying the support to be used as Text Search Fields
         // This will return all supported fields if field limiting list is empty
         $fields_text = FlexicontentFields::getSearchFields($key = 'id', $indexer = 'advanced', $txtflds_list, $contenttypes, $load_params = true, 0, 'search');
         if (empty($fields_text)) {
             // all entries of field limiting list were invalid , get ALL
             if (!empty($contenttypes)) {
                 $fields_text = FlexicontentFields::getSearchFields($key = 'id', $indexer = 'advanced', null, $contenttypes, $load_params = true, 0, 'search');
             } else {
                 $fields_text = array();
             }
         }
     }
     // ********************************
     // Filter Fields of the search form
     // ********************************
     // Get them from type configuration or from search menu item
     $filtflds = '';
     if ($show_filters) {
         if ($show_filters == 1) {
             $filtflds = $single_contenttype ? $typeData[$single_contenttype]->params->get('filters', '') : '';
         } else {
             $filtflds = $params->get('filtflds', '');
         }
     }
     // Sanitize them
     $filtflds = preg_replace("/[\"'\\\\]/u", "", $filtflds);
     $filtflds = array_unique(preg_split("/\\s*,\\s*/u", $filtflds));
     if (!strlen($filtflds[0])) {
         unset($filtflds[0]);
     }
     // Create a comma list of them
     $filtflds_list = count($filtflds) ? "'" . implode("','", $filtflds) . "'" : '';
     // Retrieve field properties/parameters, verifying the support to be used as Filter Fields
     // This will return all supported fields if field limiting list is empty
     if (count($filtflds)) {
         $filters_tmp = FlexicontentFields::getSearchFields($key = 'name', $indexer = 'advanced', $filtflds_list, $contenttypes, $load_params = true, 0, 'filter');
         // Use custom order
         $filters = array();
         if ($canseltypes && $show_filters) {
             foreach ($filtflds as $field_name) {
                 if (empty($filters_tmp[$field_name])) {
                     continue;
                 }
                 $filter_id = $filters_tmp[$field_name]->id;
                 $filters[$filter_id] = $filters_tmp[$field_name];
             }
         } else {
             foreach ($filters_tmp as $filter) {
                 $filters[$filter->id] = $filter;
                 // index by filter_id in this case too (for consistency, although we do not use the array index ?)
             }
         }
         unset($filters_tmp);
     }
     // If configured filters were not found/invalid for the current content type(s)
     // then retrieve all fields marked as filterable for the give content type(s) this is useful to list per content type filters automatically, even when not set or misconfigured
     if (empty($filters)) {
         if (!empty($contenttypes)) {
             $filters = FlexicontentFields::getSearchFields($key = 'id', $indexer = 'advanced', null, $contenttypes, $load_params = true, 0, 'filter');
         } else {
             $filters = array();
         }
     }
     // **********************
     // Load Plugin parameters
     // **********************
     $plugin = JPluginHelper::getPlugin('search', 'flexiadvsearch');
     $pluginParams = new JRegistry($plugin->params);
     // Shortcuts for plugin parameters
     $search_limit = $params->get('search_limit', $pluginParams->get('search_limit', 20));
     // Limits the returned results of this seach plugin
     $filter_lang = $params->get('filter_lang', $pluginParams->get('filter_lang', 1));
     // Language filtering enabled
     $search_archived = $params->get('search_archived', $pluginParams->get('search_archived', 1));
     // Include archive items into the search
     $browsernav = $params->get('browsernav', $pluginParams->get('browsernav', 2));
     // Open search in window (for value 1)
     // ***************************************************************************************************************
     // Varous other variable USED in the SQL query like (a) current frontend language and (b) -this- plugin specific ordering, (c) null / now dates, (d) etc
     // ***************************************************************************************************************
     // Get current frontend language (fronted user selected)
     $lang = flexicontent_html::getUserCurrentLang();
     // NULL and CURRENT dates,
     // NOTE: the current date needs to use built-in MYSQL function, otherwise filter caching can not work because the CURRENT DATETIME is continuously different !!!
     //$now = JFactory::getDate()->toSql();
     $_nowDate = 'UTC_TIMESTAMP()';
     //$db->Quote($now);
     $nullDate = $db->getNullDate();
     // Section name
     $searchFlexicontent = JText::_('FLEXICONTENT');
     // REMOVED / COMMENTED OUT this feature:
     // Require any OR all Filters ... this can be user selectable
     //$show_filtersop = $params->get('show_filtersop', 1);
     //$default_filtersop = $params->get('default_filtersop', 'all');
     //$FILTERSOP = !$show_filtersop ? $default_filtersop : JRequest::getVar('filtersop', $default_filtersop);
     // ****************************************
     // Create WHERE clause part for Text Search
     // ****************************************
     $si_tbl = !$txtmode ? 'flexicontent_items_ext' : 'flexicontent_advsearch_index';
     $search_prefix = JComponentHelper::getParams('com_flexicontent')->get('add_search_prefix') ? 'vvv' : '';
     // SEARCH WORD Prefix
     $text = preg_replace('/(\\b[^\\s,\\.]+\\b)/u', $search_prefix . '$0', trim($text));
     if (strlen($text)) {
         $ts = !$txtmode ? 'ie' : 'ts';
         $escaped_text = $db->escape($text, true);
         $quoted_text = $db->Quote($escaped_text, false);
         switch ($phrase) {
             case 'natural':
                 if ($filter_word_like_any) {
                     $_text_match = ' LOWER (' . $ts . '.search_index) LIKE ' . $db->Quote('%' . $escaped_text . '%', false);
                 } else {
                     $_text_match = ' MATCH (' . $ts . '.search_index) AGAINST (' . $quoted_text . ') ';
                 }
                 break;
             case 'natural_expanded':
                 $_text_match = ' MATCH (' . $ts . '.search_index) AGAINST (' . $quoted_text . ' WITH QUERY EXPANSION) ';
                 break;
             case 'exact':
                 $words = preg_split('/\\s\\s*/u', $text);
                 $stopwords = array();
                 $shortwords = array();
                 if (!$search_prefix) {
                     $words = flexicontent_db::removeInvalidWords($words, $stopwords, $shortwords, $si_tbl, 'search_index', $isprefix = 0);
                 }
                 if (empty($words)) {
                     // All words are stop-words or too short, we could try to execute a query that only contains a LIKE %...% , but it would be too slow
                     JRequest::setVar('ignoredwords', implode(' ', $stopwords));
                     JRequest::setVar('shortwords', implode(' ', $shortwords));
                     $_text_match = ' 0=1 ';
                 } else {
                     // speed optimization ... 2-level searching: first require ALL words, then require exact text
                     $newtext = '+' . implode(' +', $words);
                     $quoted_text = $db->escape($newtext, true);
                     $quoted_text = $db->Quote($quoted_text, false);
                     $exact_text = $db->Quote('%' . $escaped_text . '%', false);
                     $_text_match = ' MATCH (' . $ts . '.search_index) AGAINST (' . $quoted_text . ' IN BOOLEAN MODE) AND ' . $ts . '.search_index LIKE ' . $exact_text;
                 }
                 break;
             case 'all':
                 $words = preg_split('/\\s\\s*/u', $text);
                 $stopwords = array();
                 $shortwords = array();
                 if (!$search_prefix) {
                     $words = flexicontent_db::removeInvalidWords($words, $stopwords, $shortwords, $si_tbl, 'search_index', $isprefix = 1);
                 }
                 JRequest::setVar('ignoredwords', implode(' ', $stopwords));
                 JRequest::setVar('shortwords', implode(' ', $shortwords));
                 $newtext = '+' . implode('* +', $words) . '*';
                 $quoted_text = $db->escape($newtext, true);
                 $quoted_text = $db->Quote($quoted_text, false);
                 $_text_match = ' MATCH (' . $ts . '.search_index) AGAINST (' . $quoted_text . ' IN BOOLEAN MODE) ';
                 break;
             case 'any':
             default:
                 if ($filter_word_like_any) {
                     $_text_match = ' LOWER (' . $ts . '.search_index) LIKE ' . $db->Quote('%' . $escaped_text . '%', false);
                 } else {
                     $words = preg_split('/\\s\\s*/u', $text);
                     $stopwords = array();
                     $shortwords = array();
                     if (!$search_prefix) {
                         $words = flexicontent_db::removeInvalidWords($words, $stopwords, $shortwords, $si_tbl, 'search_index', $isprefix = 1);
                     }
                     JRequest::setVar('ignoredwords', implode(' ', $stopwords));
                     JRequest::setVar('shortwords', implode(' ', $shortwords));
                     $newtext = implode('* ', $words) . '*';
                     $quoted_text = $db->escape($newtext, true);
                     $quoted_text = $db->Quote($quoted_text, false);
                     $_text_match = ' MATCH (' . $ts . '.search_index) AGAINST (' . $quoted_text . ' IN BOOLEAN MODE) ';
                 }
                 break;
         }
         // Construct TEXT SEARCH limitation SUB-QUERY (contained in a AND-WHERE clause)
         $text_where = ' AND ' . $_text_match;
     } else {
         $text_where = '';
     }
     // *******************
     // Create ORDER clause
     // *******************
     // FLEXIcontent search view, use FLEXIcontent ordering
     $orderby_join = '';
     $orderby_col = '';
     if (JRequest::getVar('option') == 'com_flexicontent') {
         $order = '';
         $orderby = flexicontent_db::buildItemOrderBy($params, $order, $_request_var = 'orderby', $_config_param = 'orderby', $_item_tbl_alias = 'i', $_relcat_tbl_alias = 'rel', $_default_order = '', $_default_order_dir = '', $sfx = '', $support_2nd_lvl = false);
         // Create JOIN for ordering items by a custom field (Level 1)
         if ('field' == $order[1]) {
             $orderbycustomfieldid = (int) $params->get('orderbycustomfieldid', 0);
             $orderby_join .= ' LEFT JOIN #__flexicontent_fields_item_relations AS f ON f.item_id = i.id AND f.field_id=' . $orderbycustomfieldid;
         }
         // Create JOIN for ordering items by a custom field (Level 2)
         if ('field' == $order[2]) {
             $orderbycustomfieldid_2nd = (int) $params->get('orderbycustomfieldid' . '_2nd', 0);
             $orderby_join .= ' LEFT JOIN #__flexicontent_fields_item_relations AS f2 ON f2.item_id = i.id AND f2.field_id=' . $orderbycustomfieldid_2nd;
         }
         // Create JOIN for ordering items by author's name
         if (in_array('author', $order) || in_array('rauthor', $order)) {
             $orderby_col = '';
             $orderby_join .= ' LEFT JOIN #__users AS u ON u.id = i.created_by';
         }
         // Create JOIN for ordering items by a most commented
         if (in_array('commented', $order)) {
             $orderby_col = ', count(com.object_id) AS comments_total';
             $orderby_join .= ' LEFT JOIN #__jcomments AS com ON com.object_id = i.id';
         }
         // Create JOIN for ordering items by a most rated
         if (in_array('rated', $order)) {
             $orderby_col = ', (cr.rating_sum / cr.rating_count) * 20 AS votes';
             $orderby_join .= ' LEFT JOIN #__content_rating AS cr ON cr.content_id = i.id';
         }
         // Create JOIN for ordering items by their ordering attribute (in item's main category)
         if (in_array('order', $order)) {
             $orderby_join .= ' LEFT JOIN #__flexicontent_cats_item_relations AS rel ON rel.itemid = i.id AND rel.catid = i.catid';
         }
     } else {
         switch ($ordering) {
             //case 'relevance': $orderby = ' ORDER BY score DESC, i.title ASC'; break;
             case 'oldest':
                 $orderby = 'i.created ASC';
                 break;
             case 'popular':
                 $orderby = 'i.hits DESC';
                 break;
             case 'alpha':
                 $orderby = 'i.title ASC';
                 break;
             case 'category':
                 $orderby = 'c.title ASC, i.title ASC';
                 break;
             case 'newest':
                 $orderby = 'i.created DESC';
                 break;
             default:
                 $orderby = 'i.created DESC';
                 break;
         }
         $orderby = ' ORDER BY ' . $orderby;
     }
     // ****************************************************************************************
     // Create JOIN clause and WHERE clause part for filtering by current (viewing) access level
     // ****************************************************************************************
     $joinaccess = '';
     $andaccess = '';
     $select_access = '';
     // Extra access columns for main category and content type (item access will be added as 'access')
     $select_access .= ',  c.access as category_access, ty.access as type_access';
     if (!$show_noauth) {
         // User not allowed to LIST unauthorized items
         $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
         $aid_list = implode(",", $aid_arr);
         $andaccess .= ' AND ty.access IN (0,' . $aid_list . ')';
         $andaccess .= ' AND  c.access IN (0,' . $aid_list . ')';
         $andaccess .= ' AND  i.access IN (0,' . $aid_list . ')';
         $select_access .= ', 1 AS has_access';
     } else {
         // Access Flags for: content type, main category, item
         $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
         $aid_list = implode(",", $aid_arr);
         $select_access .= ', ' . ' CASE WHEN ' . '  ty.access IN (' . $aid_list . ') AND ' . '   c.access IN (' . $aid_list . ') AND ' . '   i.access IN (' . $aid_list . ') ' . ' THEN 1 ELSE 0 END AS has_access';
     }
     // **********************************************************************************************************************************************************
     // Create WHERE clause part for filtering by current active language, and current selected contend types ( !! although this is possible via a filter too ...)
     // **********************************************************************************************************************************************************
     $andlang = '';
     if ($app->isSite() && (FLEXI_FISH || FLEXI_J16GE && $app->getLanguageFilter()) && $filter_lang) {
         $andlang .= ' AND ( ie.language LIKE ' . $db->Quote($lang . '%') . (FLEXI_J16GE ? ' OR ie.language="*" ' : '') . ' ) ';
     }
     // Filter by currently selected content types
     $andcontenttypes = count($contenttypes) ? ' AND ie.type_id IN (' . implode(",", $contenttypes) . ') ' : '';
     // ***********************************************************************
     // Create the AND-WHERE clause parts for the currentl active Field Filters
     // ***********************************************************************
     $return_sql = 2;
     $filters_where = array();
     foreach ($filters as $field) {
         // Get value of current filter, and SKIP it if value is EMPTY
         $filtervalue = JRequest::getVar('filter_' . $field->id, '');
         $empty_filtervalue_array = is_array($filtervalue) && !strlen(trim(implode('', $filtervalue)));
         $empty_filtervalue_string = !is_array($filtervalue) && !strlen(trim($filtervalue));
         if ($empty_filtervalue_array || $empty_filtervalue_string) {
             continue;
         }
         // Call field filtering of advanced search to find items matching the field filter (an SQL SUB-QUERY is returned)
         $field_filename = $field->iscore ? 'core' : $field->field_type;
         $filtered = FLEXIUtilities::call_FC_Field_Func($field_filename, 'getFilteredSearch', array(&$field, &$filtervalue, &$return_sql));
         // An empty return value means no matching values were found
         $filtered = empty($filtered) ? ' AND 0 ' : $filtered;
         // A string mean a subquery was returned, while an array means that item ids we returned
         $filters_where[$field->id] = is_array($filtered) ? ' AND i.id IN (' . implode(',', $filtered) . ')' : $filtered;
         /*if ($filters_where[$field->id]) {
         			echo "\n<br/>Filter:". $field->name ." : ";   print_r($filtervalue);
         			echo "<br>".$filters_where[$field->id]."<br/>";
         		}*/
     }
     //echo "\n<br/><br/>Filters Active: ". count($filters_where)."<br/>";
     //echo "<pre>"; print_r($filters_where);
     //exit;
     // ******************************************************
     // Create Filters JOIN clauses and AND-WHERE clause parts
     // ******************************************************
     // JOIN clause - USED - to limit returned 'text' to the text of TEXT-SEARCHABLE only fields ... (NOT shared with filters)
     if (!$txtmode) {
         $onBasic_textsearch = $text_where;
         $onAdvanced_textsearch = '';
         $join_textsearch = '';
         $join_textfields = '';
     } else {
         $onBasic_textsearch = '';
         $onAdvanced_textsearch = $text_where;
         $join_textsearch = ' JOIN #__flexicontent_advsearch_index as ts ON ts.item_id = i.id ' . (count($fields_text) ? 'AND ts.field_id IN (' . implode(',', array_keys($fields_text)) . ')' : '');
         $join_textfields = ' JOIN #__flexicontent_fields as f ON f.id=ts.field_id';
     }
     // JOIN clauses ... (shared with filters)
     $join_clauses = '' . ' JOIN #__categories AS c ON c.id = i.catid' . ' JOIN #__flexicontent_items_ext AS ie ON ie.item_id = i.id' . ' JOIN #__flexicontent_types AS ty ON ie.type_id = ty.id';
     $join_clauses_with_text = '' . ' JOIN #__categories AS c ON c.id = i.catid' . ' JOIN #__flexicontent_items_ext AS ie ON ie.item_id = i.id' . $onBasic_textsearch . ' JOIN #__flexicontent_types AS ty ON ie.type_id = ty.id' . ($text_where ? $join_textsearch . $onAdvanced_textsearch . $join_textfields : '');
     // AND-WHERE sub-clauses ... (shared with filters)
     $where_conf = ' WHERE 1 ' . ' AND i.state IN (1,-5' . ($search_archived ? ',' . (FLEXI_J16GE ? 2 : -1) : '') . ') ' . ' AND c.published = 1 ' . ' AND ( i.publish_up = ' . $db->Quote($nullDate) . ' OR i.publish_up <= ' . $_nowDate . ' )' . ' AND ( i.publish_down = ' . $db->Quote($nullDate) . ' OR i.publish_down >= ' . $_nowDate . ' )' . $andaccess . $andlang . $andcontenttypes;
     // AND-WHERE sub-clauses for text search ... (shared with filters)
     $and_where_filters = count($filters_where) ? implode(" ", $filters_where) : '';
     // ************************************************
     // Set variables used by filters creation mechanism
     // ************************************************
     global $fc_searchview;
     $fc_searchview['join_clauses'] = $join_clauses;
     $fc_searchview['join_clauses_with_text'] = $join_clauses_with_text;
     $fc_searchview['where_conf_only'] = $where_conf;
     // WHERE of the view (mainly configuration dependent)
     $fc_searchview['filters_where'] = $filters_where;
     // WHERE of the filters
     $fc_searchview['search'] = $text_where;
     // WHERE for text search
     $fc_searchview['params'] = $params;
     // view's parameters
     // *****************************************************************************************************
     // Execute search query.  NOTE this is skipped it if (a) no text-search and no (b) no filters are active
     // *****************************************************************************************************
     // Do not check for 'contentypes' this are based on configuration and not on form submitted data,
     // considering contenttypes or other configuration based parameters, will return all items on initial search view display !
     if (!count($filters_where) && !strlen($text)) {
         return array();
     }
     $print_logging_info = $params->get('print_logging_info');
     if ($print_logging_info) {
         global $fc_run_times;
         $start_microtime = microtime(true);
     }
     // *****************************************
     // Overcome possible group concat limitation
     // *****************************************
     $query = "SET SESSION group_concat_max_len = 9999999";
     $db->setQuery($query);
     $db->execute();
     // *************
     // Get the items
     // *************
     $query = 'SELECT SQL_CALC_FOUND_ROWS i.id' . $orderby_col . ' FROM #__content AS i' . $join_clauses_with_text . $orderby_join . $joinaccess . $where_conf . $and_where_filters . ' GROUP BY i.id ' . $orderby;
     //echo "Adv search plugin main SQL query: ".nl2br($query)."<br/><br/>";
     // NOTE: The plugin will return a PRECONFIGURED limited number of results, the SEARCH VIEW to do the pagination, splicing (appropriately) the data returned by all search plugins
     try {
         // Get items, we use direct query because some extensions break the SQL_CALC_FOUND_ROWS, so let's bypass them (at this point it is OK)
         // *** Usage of FOUND_ROWS() will fail when (e.g.) Joom!Fish or Falang are installed, in this case we will be forced to re-execute the query ...
         // PLUS, we don't need Joom!Fish or Falang layer at --this-- STEP which may slow down the query considerably in large sites
         $query_limited = $query . ' LIMIT ' . $search_limit . ' OFFSET 0';
         $rows = flexicontent_db::directQuery($query_limited);
         $item_ids = array();
         foreach ($rows as $row) {
             $item_ids[] = $row->id;
         }
         // Get current items total for pagination
         $db->setQuery("SELECT FOUND_ROWS()");
         $fc_searchview['view_total'] = $db->loadResult();
         $app->setUserState('fc_view_total_' . $view, $fc_searchview['view_total']);
     } catch (Exception $e) {
         // Get items via normal joomla SQL layer
         $db->setQuery(str_replace('SQL_CALC_FOUND_ROWS', '', $query), 0, $search_limit);
         $item_ids = $db->loadColumn(0);
     }
     if (!count($item_ids)) {
         return array();
     }
     // No items found
     // *****************
     // Get the item data
     // *****************
     $query_data = 'SELECT i.id, i.title AS title, i.created, i.id AS fc_item_id, i.access, ie.type_id, i.language' . (!$txtmode ? ', ie.search_index AS text' : ', GROUP_CONCAT(ts.search_index ORDER BY f.ordering ASC SEPARATOR \' \') AS text') . ', CASE WHEN CHAR_LENGTH(i.alias) THEN CONCAT_WS(\':\', i.id, i.alias) ELSE i.id END as slug' . ', CASE WHEN CHAR_LENGTH(c.alias) THEN CONCAT_WS(\':\', c.id, c.alias) ELSE c.id END as categoryslug' . ', CONCAT_WS( " / ", ' . $db->Quote($searchFlexicontent) . ', c.title, i.title ) AS section' . $select_access . ' FROM #__content AS i' . $join_clauses . $join_textsearch . $join_textfields . ' WHERE i.id IN (' . implode(',', $item_ids) . ') ' . ' GROUP BY i.id ' . ' ORDER BY FIELD(i.id, ' . implode(',', $item_ids) . ')';
     //echo nl2br($query)."<br/><br/>";
     $db->setQuery($query_data);
     $list = $db->loadObjectList();
     if ($db->getErrorNum()) {
         echo $db->getErrorMsg();
     }
     if ($print_logging_info) {
         @($fc_run_times['search_query_runtime'] += round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
     }
     // *************************************
     // Create item links and other variables
     // *************************************
     //echo "<pre>"; print_r($list); echo "</pre>";
     if ($list) {
         if (count($list) >= $search_limit) {
             $app->setUserState('fc_view_limit_max_' . $view, $search_limit);
         }
         $item_cats = FlexicontentFields::_getCategories($list);
         foreach ($list as $key => $item) {
             $item->text = preg_replace('/\\b' . $search_prefix . '/', '', $item->text);
             $item->categories = isset($item_cats[$item->id]) ? $item_cats[$item->id] : array();
             // in case of item categories missing
             // If joomla article view is allowed allowed and then search view may optional create Joomla article links
             if ($typeData[$item->type_id]->params->get('allow_jview', 0) && $typeData[$item->type_id]->params->get('search_jlinks', 1)) {
                 $item->href = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->categoryslug, $item->language));
             } else {
                 $item->href = JRoute::_(FlexicontentHelperRoute::getItemRoute($item->slug, $item->categoryslug, 0, $item));
             }
             $item->browsernav = $browsernav;
         }
     }
     return $list;
 }
Example #11
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);
    }
Example #12
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 build an array of languages hashed by id or by language code
  *
  * @return object
  * @since 1.5
  */
 static function getLanguages($hash = 'code', $published_only = false)
 {
     static $langs = array();
     static $languages;
     if (isset($langs[$hash])) {
         return $langs[$hash];
     }
     if (!$languages) {
         $languages = FLEXIUtilities::getlanguageslist($published_only);
     }
     $langs[$hash] = new stdClass();
     foreach ($languages as $language) {
         $langs[$hash]->{$language->{$hash}} = $language;
     }
     return $langs[$hash];
 }
 /**
  * Logic to delete files
  *
  * @access public
  * @return void
  * @since 1.5
  */
 function remove()
 {
     // Check for request forgeries
     JRequest::checkToken() or jexit('Invalid Token');
     require_once JPATH_COMPONENT_ADMINISTRATOR . DS . 'models' . DS . 'file.php';
     $user = JFactory::getUser();
     $db = JFactory::getDBO();
     $model = $this->getModel('file');
     $file = $model->getFile();
     $app = JFactory::getApplication();
     $fieldid = JRequest::getVar('fieldid', 0);
     $u_item_id = JRequest::getVar('u_item_id', 0);
     $file_mode = JRequest::getVar('folder_mode', 0) ? 'folder_mode' : 'db_mode';
     if ($file_mode == 'folder_mode') {
         $filename = JRequest::getVar('filename');
         $db->setQuery("SELECT * FROM #__flexicontent_fields WHERE id='" . $fieldid . "'");
         $field = $db->loadObject();
         $field->parameters = new JRegistry($field->attribs);
         $field->item_id = $u_item_id;
         $result = FLEXIUtilities::call_FC_Field_Func($field->field_type, 'removeOriginalFile', array(&$field, $filename));
         if (!$result) {
             JError::raiseWarning(100, JText::_('FLEXI_UNABLE_TO_CLEANUP_ORIGINAL_FILE') . ": " . $path);
             $msg = '';
         } else {
             $msg = JText::_('FLEXI_FILES_DELETED');
         }
         $vc_start = mb_strrpos('?', $_SERVER['HTTP_REFERER']) ? '&' : '?';
         $this->setRedirect($_SERVER['HTTP_REFERER'] . $vc_start . 'delfilename=' . base64_encode($filename), $msg);
         return;
     }
     // calculate access
     $candelete = $user->authorise('flexicontent.deletefile', 'com_flexicontent');
     $candeleteown = $user->authorise('flexicontent.deleteownfile', 'com_flexicontent') && $file->uploaded_by == $user->get('id');
     $is_authorised = $candelete || $candeleteown;
     // check access
     if (!$is_authorised) {
         JError::raiseNotice(403, JText::_('FLEXI_ALERTNOTAUTH'));
         $this->setRedirect('index.php?option=com_flexicontent&view=filemanager', '');
         return;
     }
     $cid = JRequest::getVar('cid', array(0), 'post', 'array');
     $model = $this->getModel('filemanager');
     if (!is_array($cid) || count($cid) < 1) {
         $msg = '';
         JError::raiseWarning(500, JText::_('FLEXI_SELECT_ITEM_DELETE'));
     } else {
         if (!$model->candelete($cid)) {
             JError::raiseWarning(500, JText::_('FLEXI_YOU_CANNOT_REMOVE_THIS_FILE'));
         } else {
             if (!$model->delete($cid)) {
                 $msg = JText::_('FLEXI_OPERATION_FAILED') . ' : ' . $model->getError();
                 if (FLEXI_J16GE) {
                     throw new Exception($msg, 500);
                 } else {
                     JError::raiseError(500, $msg);
                 }
             }
             $msg = count($cid) . ' ' . JText::_('FLEXI_FILES_DELETED');
             $cache = JFactory::getCache('com_flexicontent');
             $cache->clean();
         }
     }
     $this->setRedirect('index.php?option=com_flexicontent&view=filemanager', $msg);
 }
Example #15
0
 function onDisplayFieldValue(&$field, $item, $values = null, $prop = 'display')
 {
     if (!in_array($field->field_type, self::$field_types)) {
         return;
     }
     $field->label = JText::_($field->label);
     // Some variables
     $is_ingroup = !empty($field->ingroup);
     $use_ingroup = $field->parameters->get('use_ingroup', 0);
     $multiple = $use_ingroup || (int) $field->parameters->get('allow_multiple', 0);
     $view = JRequest::getVar('flexi_callview', JRequest::getVar('view', FLEXI_ITEMVIEW));
     // Value handling parameters
     $lang_filter_values = 0;
     //$field->parameters->get( 'lang_filter_values', 1);
     $clean_output = $field->parameters->get('clean_output', 0);
     $encode_output = $field->parameters->get('encode_output', 0);
     $use_html = $field->field_type == 'maintext' ? !$field->parameters->get('hide_html', 0) : $field->parameters->get('use_html', 0);
     // Default value
     $value_usage = $field->parameters->get('default_value_use', 0);
     $default_value = $value_usage == 2 ? $field->parameters->get('default_value', '') : '';
     $default_value = $default_value ? JText::_($default_value) : '';
     // Get field values
     $values = $values ? $values : $field->value;
     // Check for no values and no default value, and return empty display
     if (empty($values)) {
         if (!strlen($default_value)) {
             $field->{$prop} = $is_ingroup ? array() : '';
             return;
         }
         $values = array($default_value);
     }
     // ******************************************
     // Language filter, clean output, encode HTML
     // ******************************************
     if ($clean_output) {
         $ifilter = $clean_output == 1 ? JFilterInput::getInstance(null, null, 1, 1) : JFilterInput::getInstance();
     }
     if ($lang_filter_values || $clean_output || $encode_output || !$use_html) {
         // (* BECAUSE OF THIS, the value display loop expects unserialized values)
         foreach ($values as &$value) {
             if (empty($value)) {
                 continue;
             }
             // skip further actions
             if ($lang_filter_values) {
                 $value = JText::_($value);
             }
             if ($clean_output) {
                 $value = $ifilter->clean($value, 'string');
             }
             if ($encode_output) {
                 $value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
             }
             if (!$use_html) {
                 $value = nl2br(preg_replace("/(\r\n|\r|\n){3,}/", "\n\n", $value));
             }
         }
         unset($value);
         // Unset this or you are looking for trouble !!!, because it is a reference and reusing it will overwrite the pointed variable !!!
     }
     // Prefix - Suffix - Separator parameters, replacing other field values if found
     $remove_space = $field->parameters->get('remove_space', 0);
     $pretext = FlexicontentFields::replaceFieldValue($field, $item, $field->parameters->get('pretext', ''), 'pretext');
     $posttext = FlexicontentFields::replaceFieldValue($field, $item, $field->parameters->get('posttext', ''), 'posttext');
     $separatorf = $field->parameters->get('separatorf', 1);
     $opentag = FlexicontentFields::replaceFieldValue($field, $item, $field->parameters->get('opentag', ''), 'opentag');
     $closetag = FlexicontentFields::replaceFieldValue($field, $item, $field->parameters->get('closetag', ''), 'closetag');
     if ($pretext) {
         $pretext = $remove_space ? $pretext : $pretext . ' ';
     }
     if ($posttext) {
         $posttext = $remove_space ? $posttext : ' ' . $posttext;
     }
     switch ($separatorf) {
         case 0:
             $separatorf = '&nbsp;';
             break;
         case 1:
             $separatorf = '<br />';
             break;
         case 2:
             $separatorf = '&nbsp;|&nbsp;';
             break;
         case 3:
             $separatorf = ',&nbsp;';
             break;
         case 4:
             $separatorf = $closetag . $opentag;
             break;
         case 5:
             $separatorf = '';
             break;
         default:
             $separatorf = '&nbsp;';
             break;
     }
     // Create field's HTML
     $field->{$prop} = array();
     $n = 0;
     foreach ($values as $value) {
         if (!strlen($value) && !$is_ingroup) {
             continue;
         }
         // Skip empty if not in field group
         if (!strlen($value)) {
             $field->{$prop}[$n++] = '';
             continue;
         }
         // Add prefix / suffix
         $field->{$prop}[$n] = $pretext . $value . $posttext;
         $n++;
         if (!$multiple) {
             break;
         }
         // multiple values disabled, break out of the loop, not adding further values even if the exist
     }
     if (!$is_ingroup) {
         // Apply separator and open/close tags
         $field->{$prop} = implode($separatorf, $field->{$prop});
         if ($field->{$prop} !== '') {
             $field->{$prop} = $opentag . $field->{$prop} . $closetag;
         } else {
             $field->{$prop} = '';
         }
     }
     // ************
     // Add OGP tags
     // ************
     if ($field->parameters->get('useogp', 0) && !empty($field->{$prop})) {
         // Get ogp configuration
         $ogpinview = $field->parameters->get('ogpinview', array());
         $ogpinview = FLEXIUtilities::paramToArray($ogpinview);
         $ogpmaxlen = $field->parameters->get('ogpmaxlen', 300);
         $ogpusage = $field->parameters->get('ogpusage', 0);
         if (in_array($view, $ogpinview)) {
             switch ($ogpusage) {
                 case 1:
                     $usagetype = 'title';
                     break;
                 case 2:
                     $usagetype = 'description';
                     break;
                 default:
                     $usagetype = '';
                     break;
             }
             if ($usagetype) {
                 $content_val = !$is_ingroup ? flexicontent_html::striptagsandcut($field->{$prop}, $ogpmaxlen) : flexicontent_html::striptagsandcut($opentag . implode($separatorf, $field->{$prop}) . $closetag, $ogpmaxlen);
                 JFactory::getDocument()->addCustomTag('<meta property="og:' . $usagetype . '" content="' . $content_val . '" />');
             }
         }
     }
 }
Example #16
0
 /**
  * Method to get the active filter result
  * 
  * @access private
  * @return string
  * @since 1.5
  */
 function _getFiltered(&$filter, $value)
 {
     $field_type = $filter->field_type;
     // Sanitize filter values as integers for field that use integer values
     if (in_array($field_type, array('createdby', 'modifiedby', 'type', 'categories', 'tags'))) {
         $values = is_array($value) ? $value : array($value);
         foreach ($values as $i => $v) {
             $values[$i] = (int) $v;
         }
     }
     switch ($field_type) {
         case 'createdby':
             $filter_query = ' AND i.created_by IN (' . implode(",", $values) . ')';
             // no db quoting needed since these were typecasted to ints
             break;
         case 'modifiedby':
             $filter_query = ' AND i.modified_by IN (' . implode(",", $values) . ')';
             // no db quoting needed since these were typecasted to ints
             break;
         case 'type':
             //$filter_query = ' AND ie.type_id IN ('. implode(",", $values) .')';   // no db quoting needed since these were typecasted to ints
             $query = 'SELECT item_id' . ' FROM #__flexicontent_items_ext' . ' WHERE type_id IN (' . implode(",", $values) . ')';
             $filter_query = ' AND i.id IN (' . $query . ')';
             break;
         case 'state':
             $stateids = array('PE' => -3, 'OQ' => -4, 'IP' => -5, 'P' => 1, 'U' => 0, 'A' => FLEXI_J16GE ? 2 : -1, 'T' => -2);
             $values = is_array($value) ? $value : array($value);
             $filt_states = array();
             foreach ($values as $i => $v) {
                 if (isset($stateids[$v])) {
                     $filt_states[] = $stateids[$v];
                 }
             }
             $filter_query = !count($values) ? ' AND 1=0 ' : ' AND i.state IN (' . implode(",", $filt_states) . ')';
             // no db quoting needed since these were typecasted to ints
             break;
         case 'categories':
             //$filter_query = ' AND rel.catid IN ('. implode(",", $values) .')';
             $query = 'SELECT itemid' . ' FROM #__flexicontent_cats_item_relations' . ' WHERE catid IN (' . implode(",", $values) . ')';
             $filter_query = ' AND i.id IN (' . $query . ')';
             break;
         case 'tags':
             $query = 'SELECT itemid' . ' FROM #__flexicontent_tags_item_relations' . ' WHERE tid IN (' . implode(",", $values) . ')';
             $filter_query = ' AND i.id IN (' . $query . ')';
             break;
         default:
             // Make sure plugin file of current file is loaded and then check if custom filtering function exists
             $field_type_file = $filter->iscore ? 'core' : $field_type;
             $path = JPATH_ROOT . DS . 'plugins' . DS . 'flexicontent_fields' . DS . strtolower($field_type_file) . (FLEXI_J16GE ? DS . strtolower($field_type_file) : "") . '.php';
             if (file_exists($path)) {
                 require_once $path;
                 $method_exists = method_exists("plgFlexicontent_fields{$field_type_file}", "getFiltered");
             }
             // Use custom field filtering if 'getFiltered' plugin method exists, otherwise try to use our default filtering function
             $filtered = !@$method_exists ? FlexicontentFields::getFiltered($filter, $value, $return_sql = true) : FLEXIUtilities::call_FC_Field_Func($field_type_file, 'getFiltered', array(&$filter, &$value));
             // An empty return value means no matching values we found
             $filtered = empty($filtered) ? ' AND 1=0' : $filtered;
             // A string mean a subquery was returned, while an array means that item ids we returned
             $filter_query = is_array($filtered) ? ' AND i.id IN (' . implode(',', $filtered) . ')' : $filtered;
             break;
     }
     //echo "<br/>".$filter_query."<br/>";
     return $filter_query;
 }
Example #17
0
 function addCurrentVersionData($item_id = null, $clean_database = false)
 {
     // check if the section was chosen to avoid adding data on static contents
     if (!FLEXI_SECTION) {
         return true;
     }
     $db =& $this->_db;
     $nullDate = $db->getNullDate();
     // @TODO: move somewhere else
     $this->formatFlexiPlugins();
     // Clean categories cache
     $catscache = JFactory::getCache('com_flexicontent_cats');
     $catscache->clean();
     // Get some basic info of all items, or of the given item
     $query = "SELECT c.id,c.catid,c.version,c.created,c.modified,c.created_by,c.introtext,c.`fulltext`" . " FROM #__content as c" . " WHERE sectionid='" . FLEXI_SECTION . "'" . ($item_id ? " AND c.id=" . $item_id : "");
     $db->setQuery($query);
     $rows = $db->loadObjectList('id');
     if (!$item_id) {
         // Get current version ids of ALL ITEMS not having current versions
         $diff_arrays = $this->getDiffVersions();
     } else {
         // Get current version id of a SPECIFIC ITEM
         $diff_arrays = array(FLEXIUtilities::getCurrentVersions($item_id));
     }
     //$jcorefields = flexicontent_html::getJCoreFields();
     $add_cats = true;
     $add_tags = true;
     // For all items not having the current version, add it
     foreach ($diff_arrays as $item) {
         $item_id = @(int) $item["id"];
         if (isset($rows[$item_id])) {
             $row =& $rows[$item_id];
             // Get field values of the current item version
             $query = "SELECT f.id,fir.value,f.field_type,f.name,fir.valueorder,f.iscore " . " FROM #__flexicontent_fields_item_relations as fir" . " LEFT JOIN #__flexicontent_fields as f on f.id=fir.field_id " . " WHERE fir.item_id=" . $row->id . " AND f.iscore=0";
             // old versions stored categories & tags into __flexicontent_fields_item_relations
             $db->setQuery($query);
             $fieldsvals = $db->loadObjectList();
             // Delete existing unversioned (current version) field values ONLY if we are asked to 'clean' the database
             if ($clean_database && $fieldsvals) {
                 $query = 'DELETE FROM #__flexicontent_fields_item_relations WHERE item_id = ' . $row->id;
                 $db->setQuery($query);
                 $db->query();
             }
             // Delete any existing versioned field values to avoid conflicts, this maybe redudant, since they should not exist,
             // but we do it anyway because someone may have truncated or delete records only in table 'flexicontent_versions' ...
             // NOTE: we do not delete data with field_id negative as these exist only in the versioning table
             $query = 'DELETE FROM #__flexicontent_items_versions WHERE item_id = ' . $row->id . ' AND version= ' . $row->version . ' AND field_id > 0';
             $db->setQuery($query);
             $db->query();
             // Add the 'maintext' field to the fields array for adding to versioning table
             $f = new stdClass();
             $f->id = 1;
             $f->iscore = 1;
             $f->valueorder = 1;
             $f->field_type = "maintext";
             $f->name = "text";
             $f->value = $row->introtext;
             if (JString::strlen($row->fulltext) > 1) {
                 $f->value .= '<hr id="system-readmore" />' . $row->fulltext;
             }
             if (substr($f->value, 0, 3) != "<p>") {
                 $f->value = "<p>" . $f->value . "</p>";
             }
             $fieldsvals[] = $f;
             // Add the 'categories' field to the fields array for adding to versioning table
             $query = "SELECT catid FROM #__flexicontent_cats_item_relations WHERE itemid='" . $row->id . "';";
             $db->setQuery($query);
             $categories = FLEXI_J16GE ? $db->loadColumn() : $db->loadResultArray();
             if (!$categories || !count($categories)) {
                 $categories = array($catid = $row->catid);
                 $query = "INSERT INTO #__flexicontent_cats_item_relations VALUES('{$catid}','" . $row->id . "', '0');";
                 $db->setQuery($query);
                 $db->query();
             }
             $f = new stdClass();
             $f->id = 13;
             $f->iscore = 1;
             $f->valueorder = 1;
             $f->version = (int) $row->version;
             $f->value = serialize($categories);
             if ($add_cats) {
                 $fieldsvals[] = $f;
             }
             // Add the 'tags' field to the fields array for adding to versioning table
             $query = "SELECT tid FROM #__flexicontent_tags_item_relations WHERE itemid='" . $row->id . "';";
             $db->setQuery($query);
             $tags = FLEXI_J16GE ? $db->loadColumn() : $db->loadResultArray();
             $f = new stdClass();
             $f->id = 14;
             $f->iscore = 1;
             $f->valueorder = 1;
             $f->version = (int) $row->version;
             $f->value = serialize($tags);
             if ($add_tags) {
                 $fieldsvals[] = $f;
             }
             // Add field values to field value versioning table
             foreach ($fieldsvals as $fieldval) {
                 // add the new values to the database
                 $obj = new stdClass();
                 $obj->field_id = $fieldval->id;
                 $obj->item_id = $row->id;
                 $obj->valueorder = $fieldval->valueorder;
                 $obj->version = (int) $row->version;
                 $obj->value = $fieldval->value;
                 //echo "version: ".$obj->version.",fieldid : ".$obj->field_id.",value : ".$obj->value.",valueorder : ".$obj->valueorder."<br />";
                 //echo "inserting into __flexicontent_items_versions<br />";
                 $db->insertObject('#__flexicontent_items_versions', $obj);
                 if ($clean_database && !$fieldval->iscore) {
                     // If clean_database is on we need to re-add the deleted values
                     unset($obj->version);
                     //echo "inserting into __flexicontent_fields_item_relations<br />";
                     $db->insertObject('#__flexicontent_fields_item_relations', $obj);
                 }
                 //$searchindex 	.= @$fieldval->search;
             }
             // **********************************************************************************
             // Add basic METADATA of current item version (kept in table #__flexicontent_versions)
             // **********************************************************************************
             $v = new stdClass();
             $v->item_id = (int) $row->id;
             $v->version_id = (int) $row->version;
             $v->created = $row->modified && $row->modified != $nullDate ? $row->modified : $row->created;
             $v->created_by = $row->created_by;
             $v->comment = '';
             //echo "inserting into __flexicontent_versions<br />";
             $db->insertObject('#__flexicontent_versions', $v);
         }
     }
     return true;
 }
Example #18
0
 function doPlgAct()
 {
     FLEXIUtilities::doPlgAct();
 }
Example #19
0
 /**
  * Method to decide which item layout to use
  *
  * @access	public
  * @param	int item identifier
  */
 function decideLayout(&$compParams, &$typeParams, &$itemParams)
 {
     // Decide to use mobile or normal item template layout
     $useMobile = $compParams->get('use_mobile_layouts', 0);
     if ($useMobile) {
         $force_desktop_layout = $compParams->get('force_desktop_layout', 0);
         $mobileDetector = flexicontent_html::getMobileDetector();
         $isMobile = $mobileDetector->isMobile();
         $isTablet = $mobileDetector->isTablet();
         $useMobile = $force_desktop_layout ? $isMobile && !$isTablet : $isMobile;
     }
     $_ilayout = $useMobile ? 'ilayout_mobile' : 'ilayout';
     // Get item layout (... if not already set), from the configuration parameter (that was decided above)
     $ilayout = $this->_ilayout == '__request__' ? JRequest::getVar($_ilayout, false) : false;
     if (!$ilayout) {
         $desktop_ilayout = $itemParams->get('ilayout', $typeParams->get('ilayout', 'default'));
         $ilayout = !$useMobile ? $desktop_ilayout : $itemParams->get('ilayout_mobile', $typeParams->get('ilayout_mobile', $desktop_ilayout));
     }
     // Verify the layout is within allowed templates, that is Content Type 's default template OR Content Type allowed templates
     $allowed_tmpls = $typeParams->get('allowed_ilayouts');
     $type_default_layout = $typeParams->get('ilayout', 'default');
     if (empty($allowed_tmpls)) {
         $allowed_tmpls = array();
     } else {
         if (!is_array($allowed_tmpls)) {
             $allowed_tmpls = explode("|", $allowed_tmpls);
         }
     }
     // Verify the item layout is within templates: Content Type default template OR Content Type allowed templates
     if ($ilayout != $type_default_layout && count($allowed_tmpls) && !in_array($ilayout, $allowed_tmpls)) {
         $app->enqueueMessage("<small>Current item Layout (template) is '{$ilayout}':<br/>- This is neither the Content Type Default Template, nor does it belong to the Content Type allowed templates.<br/>- Please correct this in the URL or in Content Type configuration.<br/>- Using Content Type Default Template Layout: '{$type_default_layout}'</small>", 'notice');
         $ilayout = $type_default_layout;
     }
     // Get cached template data, without loading language file, (this will be done at the view)
     $themes = flexicontent_tmpl::getTemplates(null);
     // Verify the item layout exists
     if (!isset($themes->items->{$ilayout})) {
         $fixed_ilayout = isset($themes->items->{$type_default_layout}) ? $type_default_layout : 'default';
         $app->enqueueMessage("<small>Current Item Layout Template is '{$ilayout}' does not exist<br/>- Please correct this in the URL or in Content Type configuration.<br/>- Using Template Layout: '{$fixed_ilayout}'</small>", 'notice');
         $ilayout = $fixed_ilayout;
         FLEXIUtilities::loadTemplateLanguageFile($ilayout);
         // Manually load Template-Specific language file of back fall ilayout
     }
     // Finally set the ilayout (template name) into model / item's parameters / HTTP Request
     $this->setItemLayout($ilayout);
     $itemParams->set('ilayout', $ilayout);
     JRequest::setVar('ilayout', $ilayout);
 }
    /**
     * 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;
        }
    }
Example #21
0
    /**
     * Logic to import csv files with content item data
     *
     * @access public
     * @return void
     * @since 1.5
     */
    function importcsv()
    {
        // Check for request forgeries
        if (JRequest::getCmd('task') != 'importcsv') {
            JRequest::checkToken() or jexit('Invalid Token');
            echo '<link rel="stylesheet" href="' . JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontentbackend.css?' . FLEXI_VERSION . '" />';
            $fc_css = JURI::base(true) . '/components/com_flexicontent/assets/css/j3x.css';
            echo '<link rel="stylesheet" href="' . $fc_css . '?' . FLEXI_VERSION . '" />';
        } else {
            // output this before every other output
            echo 'success||||' . (FLEXI_J30GE ? JSession::getFormToken() : JUtility::getToken()) . '||||';
        }
        // Get item model
        $itemmodel = $this->getModel('item');
        $model = $this->getModel('import');
        // Set some variables
        $link = 'index.php?option=com_flexicontent&view=import';
        // $_SERVER['HTTP_REFERER'];
        $task = JRequest::getCmd('task');
        $app = JFactory::getApplication();
        $db = JFactory::getDBO();
        $user = JFactory::getUser();
        $session = JFactory::getSession();
        $has_zlib = version_compare(PHP_VERSION, '5.4.0', '>=');
        $parse_log = "\n\n\n" . '<b>please click</b> <a href="' . $link . '">here</a> to return previous page' . "\n\n\n";
        $log_filename = 'importcsv_' . $user->id . '.php';
        jimport('joomla.log.log');
        JLog::addLogger(array('text_file' => $log_filename));
        // *************************
        // Execute according to task
        // *************************
        switch ($task) {
            // ***********************************************************************************************
            // RESET/CLEAR an already started import task, e.g. import process was interrupted for some reason
            // ***********************************************************************************************
            case 'clearcsv':
                // Clear any import data from session
                $conf = $has_zlib ? base64_encode(zlib_encode(serialize(null), -15)) : base64_encode(serialize(null));
                $session->set('csvimport_config', $conf, 'flexicontent');
                $session->set('csvimport_lineno', 0, 'flexicontent');
                // Set a message that import task was cleared and redirect
                $app->enqueueMessage('Import task cleared', 'notice');
                $this->setRedirect($link);
                return;
                break;
                // ****************************************************
                // CONTINUE an already started (multi-step) import task
                // ****************************************************
            // ****************************************************
            // CONTINUE an already started (multi-step) import task
            // ****************************************************
            case 'importcsv':
                $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');
                if (empty($conf)) {
                    $app->enqueueMessage('Can not continue import, import task not initialized or already finished', 'error');
                    $this->setRedirect($link);
                    return;
                }
                // CONTINUE to do the import
                // ...
                break;
                // *************************************************************************
                // INITIALIZE (prepare) import by getting configuration and reading CSV file
                // *************************************************************************
            // *************************************************************************
            // INITIALIZE (prepare) import by getting configuration and reading CSV file
            // *************************************************************************
            case 'initcsv':
            case 'testcsv':
                $conf = array();
                $conf['failure_count'] = $conf['success_count'] = 0;
                // Retrieve Basic configuration
                $conf['type_id'] = JRequest::getInt('type_id', 0);
                $conf['language'] = JRequest::getVar('language', '');
                $conf['state'] = JRequest::getInt('state', '');
                $conf['access'] = JRequest::getInt('access', '');
                // Main and secondary categories
                $conf['maincat'] = JRequest::getInt('maincat', 0);
                $conf['maincat_col'] = JRequest::getInt('maincat_col', 0);
                $conf['seccats'] = JRequest::getVar('seccats', array(), 'post', 'array');
                $conf['seccats_col'] = JRequest::getInt('seccats_col', 0);
                // Tags
                $conf['tags_col'] = JRequest::getInt('tags_col', 0);
                // Publication: META data
                $conf['created_by_col'] = JRequest::getInt('created_by_col', 0);
                $conf['modified_by_col'] = JRequest::getInt('modified_by_col', 0);
                // Publication: META data
                $conf['metadesc_col'] = JRequest::getInt('metadesc_col', 0);
                $conf['metakey_col'] = JRequest::getInt('metakey_col', 0);
                // Publication: dates
                $conf['modified_col'] = JRequest::getInt('modified_col', 0);
                $conf['created_col'] = JRequest::getInt('created_col', 0);
                $conf['publish_up_col'] = JRequest::getInt('publish_up_col', 0);
                $conf['publish_down_col'] = JRequest::getInt('publish_down_col', 0);
                // Advanced configuration
                $conf['ignore_unused_cols'] = JRequest::getInt('ignore_unused_cols', 0);
                $conf['id_col'] = JRequest::getInt('id_col', 0);
                $conf['items_per_step'] = JRequest::getInt('items_per_step', 5);
                if ($conf['items_per_step'] > 50) {
                    $conf['items_per_step'] = 50;
                }
                if (!$conf['items_per_step']) {
                    $conf['items_per_step'] = 5;
                }
                // CSV file format
                $conf['mval_separator'] = JRequest::getVar('mval_separator');
                $conf['mprop_separator'] = JRequest::getVar('mprop_separator');
                $conf['field_separator'] = JRequest::getVar('field_separator');
                $conf['enclosure_char'] = JRequest::getVar('enclosure_char');
                $conf['record_separator'] = JRequest::getVar('record_separator');
                $conf['debug_records'] = JRequest::getInt('debug_records', 0);
                // Debug, print parsed data without importing
                // ********************************************************************************************
                // Obligatory form fields, js validation should have prevented form submission but check anyway
                // ********************************************************************************************
                // Check for the required Content Type Id
                if (!$conf['type_id']) {
                    $app->enqueueMessage('Please select Content Type for the imported items', 'error');
                    $app->redirect($link);
                }
                // Check for the required main category
                if (!$conf['maincat'] && !$conf['maincat_col']) {
                    $app->enqueueMessage('Please select main category for the imported items', 'error');
                    $app->redirect($link);
                }
                // ********************************************************************************************************************
                // Check for (required) CSV file format variables, js validation should have prevented form submission but check anyway
                // ********************************************************************************************************************
                if ($conf['mval_separator'] == '' || $conf['mprop_separator'] == '') {
                    $app->enqueueMessage('CSV format not valid, please enter multi-value, and multi-property Separators', 'error');
                    $app->redirect($link);
                }
                if ($conf['field_separator'] == '' || $conf['record_separator'] == '') {
                    $app->enqueueMessage('CSV format not valid, please enter Field Separator and Item Separator', 'error');
                    $app->redirect($link);
                }
                // Retrieve the uploaded CSV file
                $csvfile = @$_FILES["csvfile"]["tmp_name"];
                if (!is_file($csvfile)) {
                    $app->enqueueMessage('Upload file error!', 'error');
                    $app->redirect($link);
                }
                // ******************************************************************************************************
                // Retrieve CSV file format variables, EXPANDING the Escape Characters like '\n' ... provided by the form
                // ******************************************************************************************************
                $pattern = '/(?<!\\\\)(\\\\(?:n|r|t|v|f|[0-7]{1,3}|x[0-9a-f]{1,2}))/i';
                $replace = 'eval(\'return "$1";\')';
                $conf['mval_separator'] = preg_replace_callback($pattern, function ($matches) {
                    $r = $matches[1];
                    eval("\$r = \"{$r}\";");
                    return $r;
                }, $conf['mval_separator']);
                $conf['mprop_separator'] = preg_replace_callback($pattern, function ($matches) {
                    $r = $matches[1];
                    eval("\$r = \"{$r}\";");
                    return $r;
                }, $conf['mprop_separator']);
                $conf['field_separator'] = preg_replace_callback($pattern, function ($matches) {
                    $r = $matches[1];
                    eval("\$r = \"{$r}\";");
                    return $r;
                }, $conf['field_separator']);
                $conf['enclosure_char'] = preg_replace_callback($pattern, function ($matches) {
                    $r = $matches[1];
                    eval("\$r = \"{$r}\";");
                    return $r;
                }, $conf['enclosure_char']);
                $conf['record_separator'] = preg_replace_callback($pattern, function ($matches) {
                    $r = $matches[1];
                    eval("\$r = \"{$r}\";");
                    return $r;
                }, $conf['record_separator']);
                // ****************************************************
                // Read & Parse the CSV file according the given format
                // ****************************************************
                $contents = FLEXIUtilities::csvstring_to_array(file_get_contents($csvfile), $conf['field_separator'], $conf['enclosure_char'], $conf['record_separator']);
                // Basic error checking, for empty data
                if (!$contents || count($contents[0]) <= 0) {
                    $app->enqueueMessage('CSV file format is not correct!', 'error');
                    $app->redirect($link);
                }
                // ********************************************************************************
                // Get field names (from the header line (row 0), and remove it form the data array
                // ********************************************************************************
                $conf['columns'] = flexicontent_html::arrayTrim($contents[0]);
                unset($contents[0]);
                $q = 'SELECT id, name, field_type, label FROM #__flexicontent_fields AS fi' . ' JOIN #__flexicontent_fields_type_relations AS ftrel ON ftrel.field_id = fi.id AND ftrel.type_id=' . $conf['type_id'];
                $db->setQuery($q);
                $conf['thefields'] = $db->loadObjectList('name');
                unset($conf['thefields']['tags']);
                // Prevent Automated Raw insertion of tags, we will use special code
                // ******************************************************************
                // Check for REQUIRED columns and decide CORE property columns to use
                // ******************************************************************
                $core_props = array();
                if ($conf['id_col'] && !in_array('id', $conf['columns'])) {
                    $app->enqueueMessage('CSV file lacks column <b>\'id\'</b> (Item ID)', 'error');
                    $app->redirect($link);
                } else {
                    if ($conf['id_col']) {
                        $core_props['id'] = 'Item ID';
                    }
                }
                if (!in_array('title', $conf['columns'])) {
                    $app->enqueueMessage('CSV file lacks column <b>\'title\'</b>', 'error');
                    $app->redirect($link);
                }
                $core_props['title'] = 'Title (core)';
                $core_props['text'] = 'Description (core)';
                $core_props['alias'] = 'Alias (core)';
                if (!$conf['language'] && !in_array('language', $conf['columns'])) {
                    $app->enqueueMessage('CSV file lacks column <b>\'language\'</b>', 'error');
                    $app->redirect($link);
                } else {
                    if (!$conf['language']) {
                        $core_props['language'] = 'Language';
                    }
                }
                if (!strlen($conf['state']) && !in_array('state', $conf['columns'])) {
                    $app->enqueueMessage('CSV file lacks column <b>\'state\'</b>', 'error');
                    $app->redirect($link);
                } else {
                    if (!strlen($conf['state'])) {
                        $core_props['state'] = 'State';
                    }
                }
                if ($conf['access'] === 0 && !in_array('access', $conf['columns'])) {
                    $app->enqueueMessage('CSV file lacks column <b>\'access\'</b>', 'error');
                    $app->redirect($link);
                } else {
                    if ($conf['access'] === 0) {
                        $core_props['access'] = 'Access';
                    }
                }
                if ($conf['maincat_col'] && !in_array('catid', $conf['columns'])) {
                    $app->enqueueMessage('CSV file lacks column <b>\'catid\'</b> (Primary category)', 'error');
                    $app->redirect($link);
                } else {
                    if ($conf['maincat_col']) {
                        $core_props['catid'] = 'Primary category';
                    }
                }
                if ($conf['seccats_col'] && !in_array('cid', $conf['columns'])) {
                    $app->enqueueMessage('CSV file lacks column <b>\'cid\'</b> (Secondary categories)', 'error');
                    $app->redirect($link);
                } else {
                    if ($conf['seccats_col']) {
                        $core_props['cid'] = 'Secondary categories';
                    }
                }
                if ($conf['created_col'] && !in_array('created', $conf['columns'])) {
                    $app->enqueueMessage('CSV file lacks column <b>\'created\'</b> (Creation date)', 'error');
                    $app->redirect($link);
                } else {
                    if ($conf['created_col']) {
                        $core_props['created'] = 'Creation Date';
                    }
                }
                if ($conf['created_by_col'] && !in_array('created_by', $conf['columns'])) {
                    $app->enqueueMessage('CSV file lacks column <b>\'created_by\'</b> (Creator - Author)', 'error');
                    $app->redirect($link);
                } else {
                    if ($conf['created_by_col']) {
                        $core_props['created_by'] = 'Creator (Author)';
                    }
                }
                if ($conf['modified_col'] && !in_array('modified', $conf['columns'])) {
                    $app->enqueueMessage('CSV file lacks column <b>\'modified\'</b> (Modification date)', 'error');
                    $app->redirect($link);
                } else {
                    if ($conf['modified_col']) {
                        $core_props['modified'] = 'Modification Date';
                    }
                }
                if ($conf['modified_by_col'] && !in_array('modified_by', $conf['columns'])) {
                    $app->enqueueMessage('CSV file lacks column <b>\'modified_by\'</b> (Last modifier)', 'error');
                    $app->redirect($link);
                } else {
                    if ($conf['modified_by_col']) {
                        $core_props['modified_by'] = 'Last modifier';
                    }
                }
                if ($conf['metadesc_col'] && !in_array('metadesc', $conf['columns'])) {
                    $app->enqueueMessage('CSV file lacks column <b>\'metadesc\'</b> (META Description)', 'error');
                    $app->redirect($link);
                } else {
                    if ($conf['metadesc_col']) {
                        $core_props['metadesc'] = 'META Description';
                    }
                }
                if ($conf['metakey_col'] && !in_array('metakey', $conf['columns'])) {
                    $app->enqueueMessage('CSV file lacks column <b>\'metakey\'</b> (META Keywords)', 'error');
                    $app->redirect($link);
                } else {
                    if ($conf['metakey_col']) {
                        $core_props['metakey'] = 'META Keywords';
                    }
                }
                if ($conf['publish_up_col'] && !in_array('publish_up', $conf['columns'])) {
                    $app->enqueueMessage('CSV file lacks column <b>\'publish_up\'</b> (Start publication date)', 'error');
                    $app->redirect($link);
                } else {
                    if ($conf['publish_up_col']) {
                        $core_props['publish_up'] = 'Start publication date';
                    }
                }
                if ($conf['publish_down_col'] && !in_array('publish_down', $conf['columns'])) {
                    $app->enqueueMessage('CSV file lacks column <b>\'publish_down\'</b> (End publication Date)', 'error');
                    $app->redirect($link);
                } else {
                    if ($conf['publish_down_col']) {
                        $core_props['publish_down'] = 'End publication Date';
                    }
                }
                if ($conf['tags_col'] == 1 && !in_array('tags_names', $conf['columns'])) {
                    $app->enqueueMessage('CSV file lacks column <b>\'tags_names\'</b> (Comma separated list of tag names)', 'error');
                    $app->redirect($link);
                } else {
                    if ($conf['tags_col'] == 1) {
                        $core_props['tags_names'] = 'Tag names';
                        $tags_model = $this->getModel('tags');
                    }
                }
                if ($conf['tags_col'] == 2 && !in_array('tags_raw', $conf['columns'])) {
                    $app->enqueueMessage('CSV file lacks column <b>\'tags_raw\'</b> (Comma separated list of tag ids)', 'error');
                    $app->redirect($link);
                } else {
                    if ($conf['tags_col'] == 2) {
                        $core_props['tags_raw'] = 'Tags';
                        $tags_model = $this->getModel('tags');
                    }
                }
                $conf['core_props'] =& $core_props;
                // *********************************************************
                // Verify that all non core property columns are field names
                // *********************************************************
                $unused_columns = array();
                foreach ($conf['columns'] as $colname) {
                    if (!isset($conf['core_props'][$colname]) && !isset($conf['thefields'][$colname])) {
                        $unused_columns[] = $colname;
                        if ($conf['ignore_unused_cols']) {
                            JError::raiseNotice(500, "Column '" . $colname . "' : &nbsp; field name NOT FOUND (column will be ignored)");
                        }
                    }
                }
                if (count($unused_columns) && !$conf['ignore_unused_cols']) {
                    $app->enqueueMessage('
					File has unused ' . count($unused_columns) . ' columns: <b>' . implode(', ', $unused_columns) . '</b>' . ' <br/>these field names are not assigned to choosen <b>content type</b>' . ' <br/><br/>please enable option: <b>\'Ignore unused columns\'</b>', 'error');
                    $app->redirect($link);
                }
                // **********************************************************
                // Verify that custom specified item ids do not already exist
                // **********************************************************
                if ($conf['id_col']) {
                    // Get 'id' column no
                    $id_col_no = 0;
                    foreach ($conf['columns'] as $col_no => $column) {
                        if ($conf['columns'][$col_no] == 'id') {
                            $id_col_no = $col_no;
                            break;
                        }
                    }
                    // Get custom IDs in csv file
                    $custom_id_arr = array();
                    foreach ($contents as $fields) {
                        $custom_id_arr[] = $fields[$id_col_no];
                    }
                    $custom_id_list = "'" . implode("','", $custom_id_arr) . "'";
                    // Cross check them if they already exist in the DB
                    $q = "SELECT id FROM #__content WHERE id IN (" . $custom_id_list . ")";
                    $db->setQuery($q);
                    $existing_ids = FLEXI_J16GE ? $db->loadColumn() : $db->loadResultArray();
                    if ($existing_ids && count($existing_ids)) {
                        $app->enqueueMessage('File has ' . count($existing_ids) . ' item IDs that already exist: \'' . implode("\\' , \\'", $existing_ids) . '\', please fix or set to ignore \'id\' column', 'error');
                        $app->redirect($link);
                    }
                }
                // Trim item's data
                foreach ($contents as $fields) {
                    $fields = flexicontent_html::arrayTrim($fields);
                }
                // Set csvfile contens and columns information
                $conf['contents'] =& $contents;
                // ***************************************************************
                // Verify that imported files exist in the media/documents folders
                // ***************************************************************
                // Get fields that use files
                $conf['media_folder'] = JRequest::getVar('media_folder');
                $conf['docs_folder'] = JRequest::getVar('docs_folder');
                $this->checkfiles($conf, $parse_log, $task);
                $this->parsevalues($conf, $parse_log, $task);
                if ($task == 'initcsv') {
                    // Set import configuration and file data into session
                    $session->set('csvimport_config', $has_zlib ? base64_encode(zlib_encode(serialize($conf), -15)) : base64_encode(serialize($conf)), 'flexicontent');
                    $session->set('csvimport_lineno', 0, 'flexicontent');
                    // Set a message that import task was prepared and redirect
                    $app->enqueueMessage('Import task prepared. <br/>' . 'File has ' . count($conf['contents_parsed']) . ' records (content items)' . ' and ' . count($conf['columns']) . ' columns (fields)', 'message');
                    $this->setRedirect($link);
                    return;
                } else {
                    // task == 'testcsv'
                    $conf['debug_records'] = $conf['debug_records'] ? $conf['debug_records'] : 2;
                }
                break;
                // ************************
                // UNKNWOWN task, terminate
                // ************************
            // ************************
            // UNKNWOWN task, terminate
            // ************************
            default:
                // Set an error message about unknown task and redirect
                $app->enqueueMessage('Unknown task: ' . $task, 'error');
                $this->setRedirect($link);
                return;
                break;
        }
        // *********************************************************************************
        // Handle each row (item) using store() method of the item model to create the items
        // *********************************************************************************
        if ($conf['tags_col']) {
            $tags_model = $this->getModel('tags');
        }
        $colcount = count($conf['columns']);
        $itemcount = count($conf['contents_parsed']);
        $items_per_call = JRequest::getInt('items_per_call', 0);
        JRequest::setVar('import_media_folder', $conf['media_folder']);
        JRequest::setVar('import_docs_folder', $conf['docs_folder']);
        $lineno = $task == 'testcsv' ? 1 : $lineno + 1;
        $linelim = $items_per_call ? $lineno + $items_per_call - 1 : $itemcount;
        $linelim = $linelim > $itemcount ? $itemcount : $linelim;
        //echo "lineno: $lineno -- linelim: $linelim<br/>";
        for (; $lineno <= $linelim; $lineno++) {
            $_d =& $conf['contents_parsed'][$lineno];
            $data = array();
            $data['type_id'] = $conf['type_id'];
            $data['language'] = $conf['language'];
            $data['catid'] = $conf['maincat'];
            // Default value maybe overriden by column
            $data['cid'] = $conf['seccats'];
            // Default value maybe overriden by column
            $data['vstate'] = 2;
            $data['state'] = $conf['state'];
            $data['access'] = $conf['access'];
            // Prepare request variable used by the item's Model
            if ($task != 'testcsv') {
                foreach ($_d as $fieldname => $field_values) {
                    if ($fieldname == 'tags_names') {
                        if ($conf['tags_col'] == 1) {
                            // Get tag names from comma separated list, filtering out bad characters
                            $remove = array("\n", "\r\n", "\r");
                            $tns_list = str_replace($remove, ' ', $field_values);
                            $tns_list = strip_tags($tns_list);
                            $tns_list = preg_replace("/[\"\\\\]/u", "", $tns_list);
                            //  "/[\"'\\\]/u"
                            $tns = array_unique(preg_split("/\\s*,\\s*/u", $tns_list));
                            $tns_quoted = array();
                            foreach ($tns as $tindex => $tname) {
                                if ($tname) {
                                    $tns_quoted[] = $db->Quote($tname);
                                }
                            }
                            if (count($tns_quoted)) {
                                $tns_list_quoted = implode(",", $tns_quoted);
                                $q = "SELECT name FROM #__flexicontent_tags WHERE name IN (" . $tns_list_quoted . ")";
                                $db->setQuery($q);
                                $tns_e = FLEXI_J16GE ? $db->loadColumn() : $db->loadResultArray();
                                $tns_m = array_diff($tns, $tns_e);
                                if (count($tns_m)) {
                                    // Create a newline separated list of tag names and then import missing tags,
                                    // thus making sure they are inserted into the tags DB table if not already present
                                    $tns_list_m = implode("\n", $tns_m);
                                    $tags_model->importList($tns_list_m);
                                }
                                // Get tag ids
                                $q = "SELECT id FROM #__flexicontent_tags WHERE name IN (" . $tns_list_quoted . ")";
                                $db->setQuery($q);
                                $data['tag'] = FLEXI_J16GE ? $db->loadColumn() : $db->loadResultArray();
                            }
                        }
                    } else {
                        if ($fieldname == 'tags_raw') {
                            if ($conf['tags_col'] == 2) {
                                // Get tag ids from comma separated list, filtering out bad characters
                                $_tis_list = preg_replace("/[\"'\\\\]/u", "", $field_values);
                                $_tis = array_unique(array_map('intval', $_tis));
                                $_tis = array_flip($_tis);
                                // Check to use only existing tag ids
                                $_tis_list = implode(",", array_keys($_tis));
                                $q = "SELECT id FROM #__flexicontent_tags WHERE id IN (" . $_tis_list . ")";
                                $db->setQuery($q);
                                $data['tag'] = FLEXI_J16GE ? $db->loadColumn() : $db->loadResultArray();
                            }
                        } else {
                            if (isset($conf['core_props'][$fieldname])) {
                                $data[$fieldname] = $field_values;
                            } else {
                                if (FLEXI_J16GE) {
                                    $data['custom'][$fieldname] = $field_values;
                                }
                            }
                        }
                    }
                }
            }
            // Set/Force id to zero to indicate creation of new item, in case item 'id' column is being used
            $c_item_id = @$data['id'];
            $data['id'] = 0;
            $session->set('csvimport_lineno', $lineno, 'flexicontent');
            // If testing format then output some information
            if ($task == 'testcsv') {
                if ($lineno == 1) {
                    $parse_log .= '
						<span class="fc-mssg fc-info">
						Testing file format <br/>
						COLUMNS: ' . implode(', ', $conf['columns']) . '<br/>
						</span><hr/>
					';
                }
                foreach ($_d as $i => $flddata) {
                    if (is_string($_d[$i])) {
                        if (mb_strlen($_d[$i], 'UTF-8') > 80) {
                            $_d[$i] = mb_substr(strip_tags($_d[$i]), 0, 80, 'UTF-8') . ' ... ';
                        }
                    }
                }
                if ($lineno <= $conf['debug_records']) {
                    $parse_log .= "<pre><b>Item no {$lineno}:</b>\n" . print_r($_d, true) . "</pre><hr/>";
                } else {
                    $parse_log .= "<b>Item no {$lineno}:</b> <br/>" . "<u>TITLE</u>: " . $_d['title'] . "<br/>" . "<u>TEXT</u>: " . $_d['text'] . "<hr/>";
                }
            } else {
                if (!$itemmodel->store($data)) {
                    $conf['failure_count']++;
                    $msg = 'Failed item no: ' . $lineno . ". titled as: '" . $data['title'] . "' : " . $itemmodel->getError();
                    JLog::add($msg);
                    echo $msg . "<br/>";
                } else {
                    $conf['success_count']++;
                    $msg = 'Imported item no: ' . $lineno . ". titled as: '" . $data['title'] . "'";
                    JLog::add($msg);
                    echo $msg . "<br/>";
                    // Try to rename entry if id column is being used
                    if ($conf['id_col'] && $c_item_id) {
                        $item_id = $itemmodel->getId();
                        $q = "UPDATE #__content SET id='" . $c_item_id . "' WHERE id='" . $item_id . "'";
                        $db->setQuery($q);
                        $db->execute();
                        $q = "UPDATE #__flexicontent_items_ext SET item_id='" . $c_item_id . "' WHERE item_id='" . $item_id . "'";
                        $db->setQuery($q);
                        $db->execute();
                        $q = "UPDATE #__flexicontent_items_tmp SET id='" . $c_item_id . "' WHERE id='" . $item_id . "'";
                        $db->setQuery($q);
                        $db->execute();
                        $q = "UPDATE #__flexicontent_tags_item_relations SET itemid='" . $c_item_id . "' WHERE itemid='" . $item_id . "'";
                        $db->setQuery($q);
                        $db->execute();
                        $q = "UPDATE #__flexicontent_cats_item_relations SET itemid='" . $c_item_id . "' WHERE itemid='" . $item_id . "'";
                        $db->setQuery($q);
                        $db->execute();
                        $q = "UPDATE #__flexicontent_fields_item_relations SET item_id='" . $c_item_id . "' WHERE item_id='" . $item_id . "'";
                        $db->setQuery($q);
                        $db->execute();
                        $q = "UPDATE #__flexicontent_items_versions SET item_id='" . $c_item_id . "' WHERE item_id='" . $item_id . "'";
                        $db->setQuery($q);
                        $db->execute();
                        $q = "UPDATE #__flexicontent_versions SET item_id='" . $c_item_id . "' WHERE item_id='" . $item_id . "'";
                        $db->setQuery($q);
                        $db->execute();
                        $q = "UPDATE #__flexicontent_favourites SET itemid='" . $c_item_id . "' WHERE itemid='" . $item_id . "'";
                        $db->setQuery($q);
                        $db->execute();
                        if (FLEXI_J16GE) {
                            $q = "UPDATE #__assets SET id='" . $c_item_id . "' WHERE id='" . $item_id . "'";
                        } else {
                            $q = "UPDATE #__flexiaccess_acl SET axo='" . $c_item_id . "'" . " WHERE acosection = " . $db->Quote('com_content') . " AND axosection = " . $db->Quote('item') . " AND axo='" . $item_id . "'";
                        }
                        $db->setQuery($q);
                        $db->execute();
                    }
                }
            }
        }
        //fclose($fp);
        // Done nothing more to do
        if ($task == 'testcsv') {
            echo $parse_log;
            echo "\n\n\n" . '<b>please click</b> <a href="' . $link . '">here</a> to return previous page' . "\n\n\n";
            jexit();
        }
        if ($lineno == $itemcount) {
            // Clean item's cache
            $cache = FLEXIUtilities::getCache($group = '', 0);
            $cache->clean('com_flexicontent_items');
            $cache->clean('com_flexicontent_filters');
            $cache = FLEXIUtilities::getCache($group = '', 1);
            $cache->clean('com_flexicontent_items');
            $cache->clean('com_flexicontent_filters');
            // Set a total results message and redirect
            $msg = 'Imported items: ' . $conf['success_count'] . ' , failed items: ' . $conf['failure_count'] . ', please review (in the logs folder) the import log file: ' . $log_filename;
            //$app->enqueueMessage($msg, ($conf['failure_count']==0 && $conf['success_count']>0) ? 'message' : 'warning');
            //$this->setRedirect($link);  // commented out this via AJAX call now
        }
        jexit();
    }
 /**
  * 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);
     }
 }
	/**
	 * @param int       $id
	 * @param UserTable $user
	 */
	private function deletePreparaty( $id, $user )
	{
		global $_CB_framework;
                $db = JFactory::getDBO();
                require_once ( $_CB_framework->getCfg( 'absolute_path' ) . '/components/com_flexicontent/classes/flexicontent.helper.php' );
                //require_once (JPATH_COMPONENT_SITE.DS.'classes'.DS.'flexicontent.helper.php');
                $state = -2;
		$app  = JFactory::getApplication();
		$user = JFactory::getUser();
		$dispatcher = JDispatcher::getInstance();
		JRequest::setVar("isflexicontent", "yes");
		static $event_failed_notice_added = false;
		
                $query = 'SELECT id FROM #__content'
				. ' WHERE id = '.(int)$id.
                        " AND created_by = " . (int) $user->get( 'id' );
                $db->setQuery( $query );
			
                if(!$db->loadResult()){
                    $profileUrl				=	$_CB_framework->userProfileUrl( $user->get( 'id' ) , false, '' );

                    cbRedirect( $profileUrl, CBTxt::T( 'You can\'t deleted this drug!' ) );
                }
                
		if ( $id )
		{
			$v = FLEXIUtilities::getCurrentVersions((int)$id);
			
			$query = 'UPDATE #__content'
				. ' SET state = ' . (int)$state
				. ' WHERE id = '.(int)$id
				//. ' AND ( checked_out = 0 OR ( checked_out = ' . (int) $user->get('id'). ' ) )'
			;
			$db->setQuery( $query );
			$db->query();
			if ( $db->getErrorNum() )  if (FLEXI_J16GE) throw new Exception($db->getErrorMsg(), 500); else JError::raiseError(500, $db->getErrorMsg());
			
			$query = 'UPDATE #__flexicontent_items_tmp'
				. ' SET state = ' . (int)$state
				. ' WHERE id = '.(int)$id
				//. ' AND ( checked_out = 0 OR ( checked_out = ' . (int) $user->get('id'). ' ) )'
			;
			$db->setQuery( $query );
			$db->query();
			if ( $db->getErrorNum() )  if (FLEXI_J16GE) throw new Exception($db->getErrorMsg(), 500); else JError::raiseError(500, $db->getErrorMsg());
			
			$query = 'UPDATE #__flexicontent_items_versions'
				. ' SET value = ' . (int)$state
				. ' WHERE item_id = '.(int)$id
				. ' AND valueorder = 1'
				. ' AND field_id = 10'
				. ' AND version = ' .(int)$v['version']
				;
			$db->setQuery( $query );
			$db->query();
			if ( $db->getErrorNum() )  if (FLEXI_J16GE) throw new Exception($db->getErrorMsg(), 500); else JError::raiseError(500, $db->getErrorMsg());
		}
		
		
		// ****************************************************************
		// Trigger Event 'onContentChangeState' of Joomla's Content plugins
		// ****************************************************************
		if (FLEXI_J16GE) {
			// Make sure we import flexicontent AND content plugins since we will be triggering their events
			JPluginHelper::importPlugin('content');
			
			// PREPARE FOR TRIGGERING content events
			// We need to fake joomla's states ... when triggering events
			$fc_state = $state;
			if ( in_array($fc_state, array(1,-5)) ) $jm_state = 1;           // published states
			else if ( in_array($fc_state, array(0,-3,-4)) ) $jm_state = 0;   // unpublished states
			else $jm_state = $fc_state;                                      // trashed & archive states
			$fc_itemview = $app->isSite() ? FLEXI_ITEMVIEW : 'item';
			
			$item = new stdClass();
			
			// Compatibility steps (including Joomla compatible state),
			// so that 3rd party plugins using the change state event work properly
		  JRequest::setVar('view', 'article');	  JRequest::setVar('option', 'com_content');
			$item->state = $jm_state;
			
			$result = $dispatcher->trigger($this->event_change_state, array('com_content.article', (array) $id, $jm_state));
			
			// Revert compatibilty steps ... the $item->state is not used further regardless if it was changed,
			// besides the event_change_state using plugin should have updated DB state value anyway
			JRequest::setVar('view', $fc_itemview);	  JRequest::setVar('option', 'com_flexicontent');
			if ($item->state == $jm_state) $item->state = $fc_state;  // this check is redundant, item->state is not used further ...
			
			if (in_array(false, $result, true) && !$event_failed_notice_added) {
				JError::raiseNotice(10, JText::_('One of plugin event handler for onContentChangeState failed') );
				$event_failed_notice_added = true;
				return false;
			}
		}
		$profileUrl				=	$_CB_framework->userProfileUrl( $user->get( 'id' ) , false, '' );

		cbRedirect( $profileUrl, CBTxt::T( 'Drug deleted successfully!' ) );
	}
    /**
     * Creates the HTML of various form fields used in the item edit form
     *
     * @since 1.0
     */
    function _buildEditLists(&$perms, &$params, &$authorparams)
    {
        $db = JFactory::getDBO();
        $user = JFactory::getUser();
        // get current user
        $item = $this->get('Item');
        // get the item from the model
        $document = JFactory::getDocument();
        $session = JFactory::getSession();
        global $globalcats;
        $categories = $globalcats;
        // get the categories tree
        $types = $this->get('Typeslist');
        $typesselected = $this->get('Typesselected');
        $subscribers = $this->get('SubscribersCount');
        $isnew = !$item->id;
        // *******************************
        // 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) {
                $selectedcats = array($maincat);
                $item->catid = $maincat;
            } else {
                $selectedcats = array();
            }
            if ($params->get('cid_default')) {
                $selectedcats = $params->get('cid_default');
            }
            if ($params->get('catid_default')) {
                $item->catid = $params->get('catid_default');
            }
        } else {
            // NOTE: This will normally return the already set versioned value of categories ($item->categories)
            $selectedcats = $this->get('Catsselected');
        }
        // *********************************************************************************************
        // 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);
        flexicontent_html::loadFramework('select2');
        $prettycheckable_added = flexicontent_html::loadFramework('prettyCheckable');
        $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', '');
        }
        $class = 'use_select2_lib';
        $attribs = 'class="' . $class . '"';
        $lists['state'] = JHTML::_('select.genericlist', $state, 'jform[state]', $attribs, 'value', 'text', $item->state, 'jform_state');
        if (!FLEXI_J16GE) {
            $lists['state'] = str_replace('<optgroup label="">', '</optgroup>', $lists['state']);
        }
        // *** BOF: J2.5 SPECIFIC SELECT LISTS
        if (FLEXI_J16GE) {
        }
        // *** 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>';
                }
            }
        }
        // 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) . '"];
			max_cat_overlimit_msg_fc = "' . JText::_('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 ($params->get('cid_allowed_parent')) {
                $cid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $params->get('cid_allowed_parent'), $depth_limit = 0);
                $disabled_cats = $params->get('cid_allowed_parent_disable', 1) ? array($params->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) . '"];
				max_cat_overlimit_msg_fc = "' . JText::_('FLEXI_TOO_MANY_ITEM_CATEGORIES', true) . '";
			');
            $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 && !$params->get('catid_default') || !$isnew && empty($item->catid) || $perms['canchange_cat'];
        if ($params->get('catid_allowed_parent')) {
            $catid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $params->get('catid_allowed_parent'), $depth_limit = 0);
            $disabled_cats = $params->get('catid_allowed_parent_disable', 1) ? array($params->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, $empty_errmsg = JText::_('FLEXI_FORM_NO_MAIN_CAT_ALLOWED'));
        } 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 version approval list
        if ($params->get('allowdisablingcomments_fe')) {
            // Set to zero if disabled or to "" (aka use default) for any other value.  THIS WILL FORCE comment field use default Global/Category/Content Type setting or disable it,
            // thus a per item commenting system cannot be selected. This is OK because it makes sense to have a different commenting system per CONTENT TYPE by not per Content Item
            $isdisabled = !$params->get('comments') && strlen($params->get('comments'));
            $fieldvalue = $isdisabled ? 0 : "";
            $fieldname = 'jform[attribs][comments]';
            $elementid = 'jform_attribs_comments';
            /*
            $options = array();
            $options[] = JHTML::_('select.option', "",  JText::_( 'FLEXI_DEFAULT_BEHAVIOR' ) );
            $options[] = JHTML::_('select.option', 0, JText::_( 'FLEXI_DISABLE' ) );
            $attribs = FLEXI_J16GE ? ' style ="float:none!important;" ' : '';
            $lists['disable_comments'] = JHTML::_('select.radiolist', $options, $fieldname, $attribs, 'value', 'text', $fieldvalue, $elementid);
            */
            $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
            $attribs = ' class="' . $classes . '" ';
            $i = 1;
            $options = array("" => JText::_('FLEXI_DEFAULT_BEHAVIOR'), 0 => JText::_('FLEXI_DISABLE'));
            $lists['disable_comments'] = '';
            foreach ($options as $option_id => $option_label) {
                $checked = $option_id === $fieldvalue ? ' checked="checked"' : '';
                $elementid_no = $elementid . '_' . $i;
                if (!$prettycheckable_added) {
                    $lists['disable_comments'] .= '<label class="fccheckradio_lbl" for="' . $elementid_no . '">';
                }
                $extra_params = !$prettycheckable_added ? '' : ' data-labeltext="' . JText::_($option_label) . '" data-labelPosition="right" data-customClass="fcradiocheck"';
                $lists['disable_comments'] .= ' <input type="radio" id="' . $elementid_no . '" data-element-grpid="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="' . $option_id . '" ' . $checked . $extra_params . ' />';
                if (!$prettycheckable_added) {
                    $lists['disable_comments'] .= '&nbsp;' . JText::_($option_label) . '</label>';
                }
                $i++;
            }
        }
        // find user's allowed languages
        $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;
        }
        // find globaly or per content type disabled languages
        $disable_langs = $params->get('disable_languages_fe', array());
        // Build languages list
        if (FLEXI_J16GE || FLEXI_FISH) {
            $item_lang = $item->language;
            // Model has already set default language according to parameters
            $langdisplay = $params->get('langdisplay_fe', 2);
            $langconf = array();
            $langconf['flags'] = $params->get('langdisplay_flags_fe', 1);
            $langconf['texts'] = $params->get('langdisplay_texts_fe', 1);
            $field_attribs = $langdisplay == 2 ? 'class="use_select2_lib"' : '';
            $lists['languages'] = flexicontent_html::buildlanguageslist('jform[language]', $field_attribs, $item->language, $langdisplay, $allowed_langs, $published_only = 1, $disable_langs, $add_all = true, $langconf);
        }
        return $lists;
    }
Example #25
0
    function onDisplayFieldValue(&$field, $item, $values = null, $prop = 'display')
    {
        if (!in_array($field->field_type, self::$field_types)) {
            return;
        }
        $field->label = JText::_($field->label);
        // Some variables
        $is_ingroup = !empty($field->ingroup);
        $use_ingroup = $field->parameters->get('use_ingroup', 0);
        $multiple = $use_ingroup || (int) $field->parameters->get('allow_multiple', 0);
        $image_source = $field->parameters->get('image_source', 0);
        // ***********************
        // One time initialization
        // ***********************
        static $initialized = null;
        static $app, $document, $option;
        static $isMobile, $isTablet, $useMobile;
        if ($initialized === null) {
            $app = JFactory::getApplication();
            $document = JFactory::getDocument();
            $option = JRequest::getVar('option');
            jimport('joomla.filesystem');
            // *****************************
            // Get isMobile / isTablet Flags
            // *****************************
            $cparams = JComponentHelper::getParams('com_flexicontent');
            $force_desktop_layout = $cparams->get('force_desktop_layout', 0);
            //$start_microtime = microtime(true);
            $mobileDetector = flexicontent_html::getMobileDetector();
            $isMobile = $mobileDetector->isMobile();
            $isTablet = $mobileDetector->isTablet();
            $useMobile = $force_desktop_layout ? $isMobile && !$isTablet : $isMobile;
            //$time_passed = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
            //printf('<br/>-- [Detect Mobile: %.3f s] ', $time_passed/1000000);
        }
        // **********************************************
        // Static FLAGS indicating if JS libs were loaded
        // **********************************************
        static $multiboxadded = false;
        static $fancyboxadded = false;
        static $gallerifficadded = false;
        static $elastislideadded = false;
        static $photoswipeadded = false;
        // *****************************
        // Current view variable / FLAGs
        // *****************************
        $realview = JRequest::getVar('view', FLEXI_ITEMVIEW);
        $view = JRequest::getVar('flexi_callview', $realview);
        $isFeedView = JRequest::getCmd('format', null) == 'feed';
        $isItemsManager = $app->isAdmin() && $realview == 'items' && $option == 'com_flexicontent';
        $isSite = $app->isSite();
        // *************************************************
        // TODO:  implement MODES >= 2, and remove this CODE
        // *************************************************
        if ($image_source > 1) {
            global $fc_folder_mode_err;
            if (empty($fc_folder_mode_err[$field->id])) {
                echo __FUNCTION__ . "(): folder-mode: " . $image_source . " not implemented please change image-source mode in image/gallery field with id: " . $field->id;
                $fc_folder_mode_err[$field->id] = 1;
                $image_source = 1;
            }
        }
        $all_media = $field->parameters->get('list_all_media_files', 0);
        $unique_thumb_method = $field->parameters->get('unique_thumb_method', 0);
        $dir = $field->parameters->get('dir');
        $dir_url = str_replace('\\', '/', $dir);
        // Check if using folder of original content being translated
        $of_usage = $field->untranslatable ? 1 : $field->parameters->get('of_usage', 0);
        $u_item_id = $of_usage && $item->lang_parent_id && $item->lang_parent_id != $item->id ? $item->lang_parent_id : $item->id;
        // FLAG to indicate if images are shared across fields, has the effect of adding field id to image thumbnails
        $multiple_image_usages = !$image_source && $all_media && $unique_thumb_method == 0;
        $extra_prefix = $multiple_image_usages ? 'fld' . $field->id . '_' : '';
        $usealt = $field->parameters->get('use_alt', 1);
        $alt_usage = $field->parameters->get('alt_usage', 0);
        $default_alt = $alt_usage == 2 ? $field->parameters->get('default_alt', '') : '';
        $usetitle = $field->parameters->get('use_title', 1);
        $title_usage = $field->parameters->get('title_usage', 0);
        $default_title = $title_usage == 2 ? JText::_($field->parameters->get('default_title', '')) : '';
        $usedesc = $field->parameters->get('use_desc', 1);
        $desc_usage = $field->parameters->get('desc_usage', 0);
        $default_desc = $desc_usage == 2 ? $field->parameters->get('default_desc', '') : '';
        $usecust1 = $field->parameters->get('use_cust1', 0);
        $cust1_usage = $field->parameters->get('cust1_usage', 0);
        $default_cust1 = $cust1_usage == 2 ? JText::_($field->parameters->get('default_cust1', '')) : '';
        $usecust2 = $field->parameters->get('use_cust2', 0);
        $cust2_usage = $field->parameters->get('cust2_usage', 0);
        $default_cust2 = $cust2_usage == 2 ? JText::_($field->parameters->get('default_cust2', '')) : '';
        // Separators / enclosing characters
        $remove_space = $field->parameters->get('remove_space', 0);
        $pretext = FlexicontentFields::replaceFieldValue($field, $item, $field->parameters->get('pretext', ''), 'pretext');
        $posttext = FlexicontentFields::replaceFieldValue($field, $item, $field->parameters->get('posttext', ''), 'posttext');
        $separatorf = $field->parameters->get('separatorf', 0);
        $opentag = FlexicontentFields::replaceFieldValue($field, $item, $field->parameters->get('opentag', ''), 'opentag');
        $closetag = FlexicontentFields::replaceFieldValue($field, $item, $field->parameters->get('closetag', ''), 'closetag');
        if ($pretext) {
            $pretext = $remove_space ? $pretext : $pretext . ' ';
        }
        if ($posttext) {
            $posttext = $remove_space ? $posttext : ' ' . $posttext;
        }
        switch ($separatorf) {
            case 0:
                $separatorf = '&nbsp;';
                break;
            case 1:
                $separatorf = '<br />';
                break;
            case 2:
                $separatorf = '&nbsp;|&nbsp;';
                break;
            case 3:
                $separatorf = ',&nbsp;';
                break;
            case 4:
                $separatorf = $closetag . $opentag;
                break;
            case 5:
                $separatorf = '';
                break;
            default:
                $separatorf = '&nbsp;';
                break;
        }
        // **************************************************
        // SETUP VALUES: retrieve, verify, load defaults, etc
        // **************************************************
        $values = $values ? $values : $field->value;
        // Intro-full mode get their values from item's parameters
        if ($image_source == -1) {
            $values = array();
            $_image_name = $view == 'item' ? 'fulltext' : 'intro';
            if ($item->images) {
                if (!is_object($item->images)) {
                    $item->images = new JRegistry($item->images);
                }
                //echo "<pre>"; print_r($item->images); echo "</pre>";
                $_image_path = $item->images->get('image_' . $_image_name, '');
                $image_by_params = array();
                // field attributes (mode-specific)
                $image_by_params['image_size'] = $_image_name;
                $image_by_params['image_path'] = $_image_path;
                // field attributes (value)
                $image_by_params['originalname'] = basename($_image_path);
                $image_by_params['alt'] = $item->images->get('image_' . $_image_name . '_alt', '');
                $image_by_params['title'] = $item->images->get('image_' . $_image_name . '_alt', '');
                $image_by_params['desc'] = $item->images->get('image_' . $_image_name . '_caption', '');
                $image_by_params['cust1'] = '';
                $image_by_params['cust2'] = '';
                $image_by_params['urllink'] = '';
                $values = array(serialize($image_by_params));
                //echo "<pre>"; print_r($image_by_params); echo "</pre>"; exit;
            }
        }
        // Check for deleted image files or image files that cannot be thumbnailed,
        // rebuilding thumbnails as needed, and then assigning checked values to a new array
        $usable_values = array();
        if ($values) {
            foreach ($values as $index => $value) {
                $value = unserialize($value);
                if (plgFlexicontent_fieldsImage::rebuildThumbs($field, $value, $item)) {
                    $usable_values[] = $values[$index];
                }
            }
        }
        $values =& $usable_values;
        // Allow for thumbnailing of the default image
        $field->using_default_value = false;
        if (!count($values)) {
            // Create default image to be used if  (a) no image assigned  OR  (b) images assigned have been deleted
            $default_image = $field->parameters->get('default_image', '');
            if ($default_image) {
                $default_image_val = array();
                // field attributes (default value specific)
                $default_image_val['default_image'] = $default_image;
                // holds complete relative path and indicates that it is default image for field
                // field attributes (value)
                $default_image_val['originalname'] = basename($default_image);
                $default_image_val['alt'] = $default_alt;
                $default_image_val['title'] = $default_title;
                $default_image_val['desc'] = $default_desc;
                $default_image_val['cust1'] = $default_cust1;
                $default_image_val['cust2'] = $default_cust2;
                $default_image_val['urllink'] = '';
                // Create thumbnails for default image
                if (plgFlexicontent_fieldsImage::rebuildThumbs($field, $default_image_val, $item)) {
                    $values = array(serialize($default_image_val));
                }
                // Also default image can (possibly) be used across multiple fields, so set flag to add field id to filenames of thumbnails
                $multiple_image_usages = true;
                $extra_prefix = 'fld' . $field->id . '_';
                $field->using_default_value = true;
            }
        }
        // *********************************************
        // Check for no values, and return empty display
        // *********************************************
        if (!count($values)) {
            $field->{$prop} = $is_ingroup ? array() : '';
            return;
        }
        // Assign (possibly) altered value array to back to the field
        $field->value = $values;
        // This is not done for onDisplayFieldValue, TODO check if this is needed
        // **************************************
        // Default display method depends on view
        // **************************************
        if ($prop == 'display' && ($view == FLEXI_ITEMVIEW || $view == 'category')) {
            $_method = $view == FLEXI_ITEMVIEW ? $field->parameters->get('default_method_item', 'display') : $field->parameters->get('default_method_cat', 'display_single_total');
        } else {
            $_method = $prop;
        }
        $cat_link_single_to = $field->parameters->get('cat_link_single_to', 1);
        // Calculate some flags, SINGLE image display and Link-to-Item FLAG
        $isSingle = isset(self::$single_displays[$_method]);
        $linkToItem = $_method == 'display_link' || $_method == 'display_single_link' || $_method == 'display_single_total_link' || $view != 'item' && $cat_link_single_to && $isSingle;
        // ************************
        // JS gallery configuration
        // ************************
        $usepopup = (int) $field->parameters->get('usepopup', 1);
        // use JS gallery
        $popuptype = (int) $field->parameters->get('popuptype', 1);
        // JS gallery type
        // Different for mobile clients
        $popuptype_mobile = (int) $field->parameters->get('popuptype_mobile', $popuptype);
        // this defaults to desktop when empty
        $popuptype = $useMobile ? $popuptype_mobile : $popuptype;
        // Enable/Disable GALLERY JS according to current view and according to other parameters
        $popupinview = $field->parameters->get('popupinview', array(FLEXI_ITEMVIEW, 'category', 'backend'));
        $popupinview = FLEXIUtilities::paramToArray($popupinview);
        if ($view == FLEXI_ITEMVIEW && !in_array(FLEXI_ITEMVIEW, $popupinview)) {
            $usepopup = 0;
        }
        if ($view == 'category' && !in_array('category', $popupinview)) {
            $usepopup = 0;
        }
        if ($view == 'module' && !in_array('module', $popupinview)) {
            $usepopup = 0;
        }
        if ($isItemsManager && !in_array('backend', $popupinview)) {
            $usepopup = 0;
        }
        // Enable/Disable GALLERY JS if linking to item view
        if ($linkToItem) {
            $usepopup = 0;
        }
        // Only allow multibox and fancybox in items manager, in other cases force fancybox
        if ($isItemsManager && !in_array($popuptype, array(1, 4))) {
            $popuptype = 4;
        }
        // Displays that need special container are not allowed when field in a group, force fancybox
        $no_container_needed = array(1, 2, 3, 4, 6);
        if ($is_ingroup && !in_array($popuptype, $no_container_needed)) {
            $popuptype = 4;
        }
        // Optionally group images from all image fields of current item ... or of all items in view too
        $grouptype = $field->parameters->get('grouptype', 1);
        $grouptype = $multiple ? 0 : $grouptype;
        // Field in gallery mode: Force grouping of images per field (current item)
        // Needed by some js galleries
        $thumb_w_s = $field->parameters->get('w_s', 120);
        $thumb_h_s = $field->parameters->get('h_s', 90);
        // ******************************
        // Hovering ToolTip configuration
        // ******************************
        $uselegend = $field->parameters->get('uselegend', 1);
        $tip_class = FLEXI_J30GE ? ' hasTooltip' : ' hasTip';
        // Enable/disable according to current view
        $legendinview = $field->parameters->get('legendinview', array(FLEXI_ITEMVIEW, 'category'));
        $legendinview = FLEXIUtilities::paramToArray($legendinview);
        if ($view == FLEXI_ITEMVIEW && !in_array(FLEXI_ITEMVIEW, $legendinview)) {
            $uselegend = 0;
        }
        if ($view == 'category' && !in_array('category', $legendinview)) {
            $uselegend = 0;
        }
        if ($isItemsManager && !in_array('backend', $legendinview)) {
            $uselegend = 0;
        }
        // load the tooltip library if required
        if ($uselegend && !FLEXI_J30GE) {
            JHTML::_('behavior.tooltip');
        }
        // **************************************
        // Title/Description in inline thumbnails
        // **************************************
        $showtitle = $field->parameters->get('showtitle', 0);
        $showdesc = $field->parameters->get('showdesc', 0);
        // *************************
        // Link to URL configuration
        // *************************
        $linkto_url = $field->parameters->get('linkto_url', 0);
        $url_target = $field->parameters->get('url_target', '_self');
        $isLinkToPopup = $linkto_url && ($url_target == 'multibox' || $url_target == 'fancybox');
        // Force opening in new window in backend, if URL target is _self
        if ($isItemsManager && $url_target == '_self') {
            $url_target = "_blank";
        }
        // Only allow multibox (and TODO: add fancybox) when linking to URL, in other cases force fancybox
        if ($isLinkToPopup && $url_target == 'multibox') {
            $popuptype = 1;
        }
        if ($isLinkToPopup && $url_target == 'fancybox') {
            $popuptype = 4;
        } else {
            if ($linkto_url) {
                $usepopup = 0;
            }
        }
        // ************************************
        // Social website sharing configuration
        // ************************************
        $useogp = $field->parameters->get('useogp', 0);
        $ogpinview = $field->parameters->get('ogpinview', array());
        $ogpinview = FLEXIUtilities::paramToArray($ogpinview);
        $ogpthumbsize = $field->parameters->get('ogpthumbsize', 2);
        // **********************************************
        // Load the configured (or the forced) JS gallery
        // **********************************************
        // Do not load JS, for value only displays
        if (!isset(self::$value_only_displays[$prop])) {
            // MultiBox maybe added in extra cases besides popup
            // (a) in Item manager, (b) When linking to URL in popup target
            $view_allows_mb = $isItemsManager || $isSite && !$isFeedView;
            $config_needs_mb = $isLinkToPopup || $usepopup && $popuptype == 1;
            if ($view_allows_mb && $config_needs_mb) {
                if (!$multiboxadded) {
                    flexicontent_html::loadFramework('jmultibox');
                    //echo $field->name.": multiboxadded";
                    $js = "\n\t\t\t\t\twindow.addEvent('domready', function(){\n\t\t\t\t\t\tjQuery('a.mb').jmultibox({\n\t\t\t\t\t\t\tinitialWidth: 250,  //(number) the width of the box when it first opens while loading the item. Default: 250\n\t\t\t\t\t\t\tinitialHeight: 250, //(number) the width of the box when it first opens while loading the item. Default: 250\n\t\t\t\t\t\t\tcontainer: document.body, //(element) the element that the box will take it coordinates from. Default: document.body\n\t\t\t\t\t\t\tcontentColor: '#000', //(string) the color of the content area inside the box. Default: #000\n\t\t\t\t\t\t\tshowNumbers: " . ($isItemsManager ? 'false' : 'true') . ",    //(boolean) show the number of the item e.g. 2/10. Default: true\n\t\t\t\t\t\t\tshowControls: " . ($isItemsManager ? 'false' : 'true') . ",   //(boolean) show the navigation controls. Default: true\n\t\t\t\t\t\t\tdescClassName: 'multiBoxDesc',  //(string) the classname of the divs that contain the description for the item. Default: false\n\t\t\t\t\t\t\tdescMinWidth: 400,     //(number) the min width of the description text, useful when the item is small. Default: 400\n\t\t\t\t\t\t\tdescMaxWidth: 600,     //(number) the max width of the description text, so it can wrap to multiple lines instead of being on a long single line. Useful when the item is large. Default: 600\n\t\t\t\t\t\t\tmovieWidth: 576,    //(number) the default width of the box that contains content of a movie type. Default: 576\n\t\t\t\t\t\t\tmovieHeight: 324,   //(number) the default height of the box that contains content of a movie type. Default: 324\n\t\t\t\t\t\t\toffset: {x: 0, y: 0},  //(object) containing x & y coords that adjust the positioning of the box. Default: {x:0, y:0}\n\t\t\t\t\t\t\tfixedTop: false,       //(number) gives the box a fixed top position relative to the container. Default: false\n\t\t\t\t\t\t\tpath: '',            //(string) location of the resources files, e.g. flv player, etc. Default: ''\n\t\t\t\t\t\t\topenFromLink: true,  //(boolean) opens the box relative to the link location. Default: true\n\t\t\t\t\t\t\topac:0.7,            //(decimal) overlay opacity Default: 0.7\n\t\t\t\t\t\t\tuseOverlay:false,    //(boolean) use a semi-transparent background. Default: false\n\t\t\t\t\t\t\toverlaybg:'01.png',  //(string) overlay image in 'overlays' folder. Default: '01.png'\n\t\t\t\t\t\t\tonOpen:function(){},   //(object) a function to call when the box opens. Default: function(){} \n\t\t\t\t\t\t\tonClose:function(){},  //(object) a function to call when the box closes. Default: function(){} \n\t\t\t\t\t\t\teasing:'swing',        //(string) effect of jQuery Default: 'swing'\n\t\t\t\t\t\t\tuseratio:false,        //(boolean) windows size follows ratio. (iframe or Youtube) Default: false\n\t\t\t\t\t\t\tratio:'90'             //(number) window ratio Default: '90'\n\t\t\t\t\t\t});\n\t\t\t\t\t})";
                    $document->addScriptDeclaration($js);
                    $multiboxadded = true;
                }
            }
            // Regardless if above has added multibox , we will add a different JS gallery if so configured because it maybe needed
            if (!$isSite || $isFeedView) {
                // Is backend OR it is a feed view, do not add any JS library
            } else {
                if ($usepopup) {
                    switch ($popuptype) {
                        // Add Fancybox image popup
                        case 4:
                            if (!$fancyboxadded) {
                                $fancyboxadded = true;
                                flexicontent_html::loadFramework('fancybox');
                            }
                            break;
                            // Add Galleriffic inline slideshow gallery
                        // Add Galleriffic inline slideshow gallery
                        case 5:
                            $inline_gallery = 1;
                            // unused
                            if (!$gallerifficadded) {
                                flexicontent_html::loadFramework('galleriffic');
                                $gallerifficadded = true;
                                $js = "\n\t\t\t\t\t\t//document.write('<style>.noscript { display: none; }</style>');\n\t\t\t\t\t\tjQuery(document).ready(function() {\n\t\t\t\t\t\t\t// We only want these styles applied when javascript is enabled\n\t\t\t\t\t\t\tjQuery('div.navigation').css({'width' : '150px', 'float' : 'left'});\n\t\t\t\t\t\t\tjQuery('div.content').css({'display' : 'inline-block', 'float' : 'none'});\n\t\t\t\n\t\t\t\t\t\t\t// Initially set opacity on thumbs and add\n\t\t\t\t\t\t\t// additional styling for hover effect on thumbs\n\t\t\t\t\t\t\tvar onMouseOutOpacity = 0.67;\n\t\t\t\t\t\t\tjQuery('#gf_thumbs ul.thumbs li').opacityrollover({\n\t\t\t\t\t\t\t\tmouseOutOpacity:   onMouseOutOpacity,\n\t\t\t\t\t\t\t\tmouseOverOpacity:  1.0,\n\t\t\t\t\t\t\t\tfadeSpeed:         'fast',\n\t\t\t\t\t\t\t\texemptionSelector: '.selected'\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// Initialize Advanced Galleriffic Gallery\n\t\t\t\t\t\t\tjQuery('#gf_thumbs').galleriffic({\n\t\t\t\t\t\t\t\t/*enableFancybox: true,*/\n\t\t\t\t\t\t\t\tdelay:                     2500,\n\t\t\t\t\t\t\t\tnumThumbs:                 4,\n\t\t\t\t\t\t\t\tpreloadAhead:              10,\n\t\t\t\t\t\t\t\tenableTopPager:            true,\n\t\t\t\t\t\t\t\tenableBottomPager:         true,\n\t\t\t\t\t\t\t\tmaxPagesToShow:            20,\n\t\t\t\t\t\t\t\timageContainerSel:         '#gf_slideshow',\n\t\t\t\t\t\t\t\tcontrolsContainerSel:      '#gf_controls',\n\t\t\t\t\t\t\t\tcaptionContainerSel:       '#gf_caption',\n\t\t\t\t\t\t\t\tloadingContainerSel:       '#gf_loading',\n\t\t\t\t\t\t\t\trenderSSControls:          true,\n\t\t\t\t\t\t\t\trenderNavControls:         true,\n\t\t\t\t\t\t\t\tplayLinkText:              'Play Slideshow',\n\t\t\t\t\t\t\t\tpauseLinkText:             'Pause Slideshow',\n\t\t\t\t\t\t\t\tprevLinkText:              '&lsaquo; Previous Photo',\n\t\t\t\t\t\t\t\tnextLinkText:              'Next Photo &rsaquo;',\n\t\t\t\t\t\t\t\tnextPageLinkText:          'Next &rsaquo;',\n\t\t\t\t\t\t\t\tprevPageLinkText:          '&lsaquo; Prev',\n\t\t\t\t\t\t\t\tenableHistory:             false,\n\t\t\t\t\t\t\t\tautoStart:                 false,\n\t\t\t\t\t\t\t\tsyncTransitions:           true,\n\t\t\t\t\t\t\t\tdefaultTransitionDuration: 900,\n\t\t\t\t\t\t\t\tonSlideChange:             function(prevIndex, nextIndex) {\n\t\t\t\t\t\t\t\t\t// 'this' refers to the gallery, which is an extension of jQuery('#gf_thumbs')\n\t\t\t\t\t\t\t\t\tthis.find('ul.thumbs').children()\n\t\t\t\t\t\t\t\t\t\t.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()\n\t\t\t\t\t\t\t\t\t\t.eq(nextIndex).fadeTo('fast', 1.0);\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tonPageTransitionOut:       function(callback) {\n\t\t\t\t\t\t\t\t\tthis.fadeTo('fast', 0.0, callback);\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tonPageTransitionIn:        function() {\n\t\t\t\t\t\t\t\t\tthis.fadeTo('fast', 1.0);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t});\n\t\t\t\t\t\t\t";
                                $document->addScriptDeclaration($js);
                            }
                            break;
                            // Add Elastislide inline carousel gallery (Responsive image gallery with togglable thumbnail-strip, plus previewer and description)
                        // Add Elastislide inline carousel gallery (Responsive image gallery with togglable thumbnail-strip, plus previewer and description)
                        case 7:
                            if (!$elastislideadded) {
                                flexicontent_html::loadFramework('elastislide');
                                $elastislideadded = true;
                            }
                            $uid = 'es_' . $field->name . "_fcitem" . $item->id;
                            $js = file_get_contents(JPATH_SITE . DS . 'components' . DS . 'com_flexicontent' . DS . 'librairies' . DS . 'elastislide' . DS . 'js' . DS . 'gallery_tmpl.js');
                            $js = str_replace('unique_gal_id', $uid, $js);
                            $js = str_replace('__thumb_width__', $field->parameters->get('w_s', 120), $js);
                            $document->addScriptDeclaration($js);
                            $document->addCustomTag('
					<script id="img-wrapper-tmpl_' . $uid . '" type="text/x-jquery-tmpl">	
						<div class="rg-image-wrapper">
							{{if itemsCount > 1}}
								<div class="rg-image-nav">
									<a href="#" class="rg-image-nav-prev">' . JText::_('FLEXI_PREVIOUS') . '</a>
									<a href="#" class="rg-image-nav-next">' . JText::_('FLEXI_NEXT') . '</a>
								</div>
							{{/if}}
							<div class="rg-image"></div>
							<div class="rg-loading"></div>
							<div class="rg-caption-wrapper">
								<div class="rg-caption" style="display:none;">
									<p></p>
								</div>
							</div>
						</div>
					</script>
					');
                            break;
                            // Add PhotoSwipe popup carousel gallery
                        // Add PhotoSwipe popup carousel gallery
                        case 8:
                            if (!$photoswipeadded) {
                                flexicontent_html::loadFramework('photoswipe');
                                $photoswipeadded = true;
                            }
                            break;
                    }
                }
            }
        }
        // *******************************
        // Prepare for value handling loop
        // *******************************
        // Extra thumbnails sub-folder for various
        if ($field->using_default_value) {
            $extra_folder = '';
            // default value
        } else {
            if ($image_source == -1) {
                $extra_folder = 'intro_full';
                // intro-full images mode
            } else {
                if ($image_source > 0) {
                    $extra_folder = 'item_' . $u_item_id . '_field_' . $field->id;
                    // folder-mode 1
                    if ($image_source > 1) {
                    }
                    // TODO
                } else {
                    $extra_folder = '';
                    // db-mode
                }
            }
        }
        // Create thumbs/image Folder and URL paths
        $thumb_folder = JPATH_SITE . DS . JPath::clean($dir . ($extra_folder ? DS . $extra_folder : ''));
        $thumb_urlpath = $dir_url . ($extra_folder ? '/' . $extra_folder : '');
        if ($field->using_default_value) {
            // default image of this field, these are relative paths up to site root
            $orig_urlpath = str_replace('\\', '/', dirname($default_image_val['default_image']));
        } else {
            if ($image_source == -1) {
                // intro-full image values, these are relative paths up to the site root, must be calculated later !!
                $orig_urlpath = str_replace('\\', '/', dirname($image_by_params['image_path']));
            } else {
                if ($image_source > 0) {
                    // various folder-mode(s)
                    $orig_urlpath = $thumb_urlpath . '/original';
                } else {
                    // db-mode
                    $cparams = JComponentHelper::getParams('com_flexicontent');
                    $orig_urlpath = str_replace('\\', '/', JPath::clean($cparams->get('file_path', 'components/com_flexicontent/uploads')));
                }
            }
        }
        // Initialize value handling arrays and loop's common variables
        $i = -1;
        $field->{$prop} = array();
        $field->thumbs_src['backend'] = array();
        $field->thumbs_src['small'] = array();
        $field->thumbs_src['medium'] = array();
        $field->thumbs_src['large'] = array();
        $field->thumbs_src['original'] = array();
        $field->{"display_backend_src"} = array();
        $field->{"display_small_src"} = array();
        $field->{"display_medium_src"} = array();
        $field->{"display_large_src"} = array();
        $field->{"display_original_src"} = array();
        $cust1_label = JText::_('FLEXI_FIELD_IMG_CUST1');
        $cust2_label = JText::_('FLEXI_FIELD_IMG_CUST2');
        // Decide thumbnail to use
        $thumb_size = 0;
        if ($isItemsManager) {
            $thumb_size = -1;
        } else {
            if ($view == 'category') {
                $thumb_size = $field->parameters->get('thumbincatview', 1);
            } else {
                if ($view == FLEXI_ITEMVIEW) {
                    $thumb_size = $field->parameters->get('thumbinitemview', 2);
                }
            }
        }
        // ***************
        // The values loop
        // ***************
        foreach ($values as $val) {
            // Unserialize value's properties and check for empty original name property
            $value = unserialize($val);
            $image_name = trim(@$value['originalname']);
            if (!strlen($image_name)) {
                if ($is_ingroup) {
                    $field->{$prop}[] = '';
                }
                // add empty position to the display array
                continue;
            }
            $i++;
            // Create thumbnails urls, note thumbnails have already been verified above
            $wl = $field->parameters->get('w_l', 800);
            $hl = $field->parameters->get('h_l', 600);
            // Optional properties
            $title = $usetitle && @$value['title'] ? $value['title'] : '';
            $alt = $usealt && @$value['alt'] ? $value['alt'] : flexicontent_html::striptagsandcut($item->title, 60);
            $desc = $usedesc && @$value['desc'] ? $value['desc'] : '';
            // Optional custom properties
            $cust1 = $usecust1 && @$value['cust1'] ? $value['cust1'] : '';
            $desc .= $cust1 ? $cust1_label . ': ' . $cust1 : '';
            // ... Append custom properties to description
            $cust2 = $usecust2 && @$value['cust2'] ? $value['cust2'] : '';
            $desc .= $cust2 ? $cust2_label . ': ' . $cust2 : '';
            // ... Append custom properties to description
            // HTML encode output
            $title = htmlspecialchars($title, ENT_COMPAT, 'UTF-8');
            $alt = htmlspecialchars($alt, ENT_COMPAT, 'UTF-8');
            $desc = htmlspecialchars($desc, ENT_COMPAT, 'UTF-8');
            $srcb = $thumb_urlpath . '/b_' . $extra_prefix . $image_name;
            // backend
            $srcs = $thumb_urlpath . '/s_' . $extra_prefix . $image_name;
            // small
            $srcm = $thumb_urlpath . '/m_' . $extra_prefix . $image_name;
            // medium
            $srcl = $thumb_urlpath . '/l_' . $extra_prefix . $image_name;
            // large
            $srco = $orig_urlpath . '/' . $image_name;
            // original image
            // Create a popup url link
            $urllink = @$value['urllink'] ? $value['urllink'] : '';
            if ($urllink && false === strpos($urllink, '://')) {
                $urllink = 'http://' . $urllink;
            }
            // Create a popup tooltip (legend)
            $class = 'fc_field_image';
            if ($uselegend && (!empty($title) || !empty($desc))) {
                $class .= $tip_class;
                $legend = ' title="' . flexicontent_html::getToolTip($title, $desc, 0, 1) . '"';
            } else {
                $legend = '';
            }
            // Handle single image display, with/without total, TODO: verify all JS handle & ignore display none on the img TAG
            $style = $i != 0 && $isSingle ? 'display:none;' : '';
            // Create a unique id for the link tags, and a class name for image tags
            $uniqueid = $item->id . '_' . $field->id . '_' . $i;
            switch ($thumb_size) {
                case -1:
                    $src = $srcb;
                    break;
                case 1:
                    $src = $srcs;
                    break;
                case 2:
                    $src = $srcm;
                    break;
                case 3:
                    $src = $srcl;
                    break;
                    // this makes little sense, since both thumbnail and popup image are size 'large'
                // this makes little sense, since both thumbnail and popup image are size 'large'
                case 4:
                    $src = $srco;
                    break;
                default:
                    $src = $srcs;
                    break;
            }
            // Create a grouping name
            switch ($grouptype) {
                case 0:
                    $group_name = 'fcview_' . $view . '_fcitem_' . $item->id . '_fcfield_' . $field->id;
                    break;
                case 1:
                    $group_name = 'fcview_' . $view . '_fcitem_' . $item->id;
                    break;
                case 2:
                    $group_name = 'fcview_' . $view;
                    break;
                default:
                    $group_name = '';
                    break;
            }
            // ADD some extra (display) properties that point to all sizes, currently SINGLE IMAGE only
            if ($is_ingroup) {
                // In case of field displayed via in fieldgroup, this is an array
                $field->{"display_backend_src"}[] = JURI::root(true) . '/' . $srcb;
                $field->{"display_small_src"}[] = JURI::root(true) . '/' . $srcs;
                $field->{"display_medium_src"}[] = JURI::root(true) . '/' . $srcm;
                $field->{"display_large_src"}[] = JURI::root(true) . '/' . $srcl;
                $field->{"display_original_src"}[] = JURI::root(true) . '/' . $srco;
            } else {
                if ($i == 0) {
                    // Field displayed not via fieldgroup return only the 1st value
                    $field->{"display_backend_src"} = JURI::root(true) . '/' . $srcb;
                    $field->{"display_small_src"} = JURI::root(true) . '/' . $srcs;
                    $field->{"display_medium_src"} = JURI::root(true) . '/' . $srcm;
                    $field->{"display_large_src"} = JURI::root(true) . '/' . $srcl;
                    $field->{"display_original_src"} = JURI::root(true) . '/' . $srco;
                }
            }
            $field->thumbs_src['backend'][] = JURI::root(true) . '/' . $srcb;
            $field->thumbs_src['small'][] = JURI::root(true) . '/' . $srcs;
            $field->thumbs_src['medium'][] = JURI::root(true) . '/' . $srcm;
            $field->thumbs_src['large'][] = JURI::root(true) . '/' . $srcl;
            $field->thumbs_src['original'][] = JURI::root(true) . '/' . $srco;
            $field->thumbs_path['backend'][] = JPATH_SITE . DS . $srcb;
            $field->thumbs_path['small'][] = JPATH_SITE . DS . $srcs;
            $field->thumbs_path['medium'][] = JPATH_SITE . DS . $srcm;
            $field->thumbs_path['large'][] = JPATH_SITE . DS . $srcl;
            $field->thumbs_path['original'][] = JPATH_SITE . DS . $srco;
            // Suggest image for external use, e.g. for Facebook etc
            if ($isSite && !$isFeedView && $useogp) {
                if (in_array($view, $ogpinview)) {
                    switch ($ogpthumbsize) {
                        case 1:
                            $ogp_src = $field->thumbs_src['small'][$i];
                            break;
                            // this maybe problematic, since it maybe too small or not accepted by social website
                        // this maybe problematic, since it maybe too small or not accepted by social website
                        case 2:
                            $ogp_src = $field->thumbs_src['medium'][$i];
                            break;
                        case 3:
                            $ogp_src = $field->thumbs_src['large'][$i];
                            break;
                        case 4:
                            $ogp_src = $field->thumbs_src['original'][$i];
                            break;
                        default:
                            $ogp_src = $field->thumbs_src['medium'][$i];
                            break;
                    }
                    $document->addCustomTag('<link rel="image_src" href="' . $ogp_src . '" />');
                    $document->addCustomTag('<meta property="og:image" content="' . $ogp_src . '" />');
                }
            }
            // ****************************************************************
            // CHECK if we were asked for value only display (e.g. image source)
            // if so we will not be creating the HTML code for Image / Gallery
            // ****************************************************************
            if (isset(self::$value_only_displays[$prop])) {
                continue;
            }
            // *********************************************************
            // Create image tags (according to configuration parameters)
            // that will be used for the requested 'display' variable
            // *********************************************************
            switch ($prop) {
                case 'display_backend':
                    $img_legend = '<img src="' . JURI::root(true) . '/' . $srcb . '" alt="' . $alt . '"' . $legend . ' class="' . $class . '" itemprop="image"/>';
                    $img_nolegend = '<img src="' . JURI::root(true) . '/' . $srcb . '" alt="' . $alt . '" class="' . $class . '" itemprop="image"/>';
                    break;
                case 'display_small':
                    $img_legend = '<img src="' . JURI::root(true) . '/' . $srcs . '" alt="' . $alt . '"' . $legend . ' class="' . $class . '" itemprop="image"/>';
                    $img_nolegend = '<img src="' . JURI::root(true) . '/' . $srcs . '" alt="' . $alt . '" class="' . $class . '" itemprop="image"/>';
                    break;
                case 'display_medium':
                    $img_legend = '<img src="' . JURI::root(true) . '/' . $srcm . '" alt="' . $alt . '"' . $legend . ' class="' . $class . '" itemprop="image"/>';
                    $img_nolegend = '<img src="' . JURI::root(true) . '/' . $srcm . '" alt="' . $alt . '" class="' . $class . '" itemprop="image"/>';
                    break;
                case 'display_large':
                    $img_legend = '<img src="' . JURI::root(true) . '/' . $srcl . '" alt="' . $alt . '"' . $legend . ' class="' . $class . '" itemprop="image"/>';
                    $img_nolegend = '<img src="' . JURI::root(true) . '/' . $srcl . '" alt="' . $alt . '" class="' . $class . '" itemprop="image"/>';
                    break;
                case 'display_original':
                    $img_legend = '<img src="' . JURI::root(true) . '/' . $srco . '" alt="' . $alt . '"' . $legend . ' class="' . $class . '" itemprop="image"/>';
                    $img_nolegend = '<img src="' . JURI::root(true) . '/' . $srco . '" alt="' . $alt . '" class="' . $class . '" itemprop="image"/>';
                    break;
                case 'display':
                default:
                    $img_legend = '<img src="' . JURI::root(true) . '/' . $src . '" alt="' . $alt . '"' . $legend . ' class="' . $class . '" itemprop="image"/>';
                    $img_nolegend = '<img src="' . JURI::root(true) . '/' . $src . '" alt="' . $alt . '" class="' . $class . '" itemprop="image"/>';
                    break;
            }
            // *************************************************
            // Create thumbnail appending text (not linked text)
            // *************************************************
            // For galleries that are not inline/special, we can have inline text ??
            $inline_info = '';
            if ($linkto_url || ($prop == 'display_large' || $prop == 'display_original') || !$usepopup || $popuptype != 5 && $popuptype != 7) {
                // Add inline display of title/desc
                if ($showtitle && $title || $showdesc && $desc) {
                    $inline_info = '<div class="fc_img_tooltip_data alert alert-info" style="' . $style . '" >';
                }
                if ($showtitle && $title) {
                    $inline_info .= '<div class="fc_img_tooltip_title" style="line-height:1em; font-weight:bold;">' . $title . '</div>';
                }
                if ($showdesc && $desc) {
                    $inline_info .= '<div class="fc_img_tooltip_desc" style="line-height:1em;">' . $desc . '</div>';
                }
                if ($showtitle && $title || $showdesc && $desc) {
                    $inline_info .= '</div>';
                }
            }
            // *********************************************
            // FINALLY CREATE the field display variable ...
            // *********************************************
            if ($linkToItem) {
                // CASE 0: Add single image display information (e.g. image count)
                $item_link = JRoute::_(FlexicontentHelperRoute::getItemRoute($item->slug, $item->categoryslug, 0, $item));
                $field->{$prop}[] = '<span style="display: inline-block; text-align:center; ">
					<a href="' . $item_link . '" style="display: inline-block;">
					' . $img_nolegend . '
					</a><br/>' . ($_method == 'display_single_total' || $_method == 'display_single_total_link' ? '
					<span class="fc_img_total_data badge badge-info" style="display: inline-block;" >
						' . count($values) . ' ' . JText::_('FLEXI_IMAGES') . '
					</span>' : '') . '
				</span>';
                // If single display and not in field group then do not add more images
                if (!$is_ingroup && $isSingle) {
                    break;
                }
            } else {
                if ($linkto_url) {
                    // CASE 1: Handle linking to a URL instead of image zooming popup
                    if (!$urllink) {
                        // CASE: Just image thumbnail since url link is empty
                        $field->{$prop}[] = $pretext . '<div class="fc_img_container">' . $img_legend . $inline_info . '</div>' . $posttext;
                    } else {
                        if ($url_target == 'multibox') {
                            // CASE: Link to URL that opens inside a popup via multibox
                            $field->{$prop}[] = $pretext . '
					<script>document.write(\'<a style="' . $style . '" href="' . $urllink . '" id="mb' . $uniqueid . '" class="mb" rel="width:\'+(jQuery(window).width()-150)+\',height:\'+(jQuery(window).height()-150)+\'">\')</script>
						' . $img_legend . '
					<script>document.write(\'</a>\')</script>
					<div class="multiBoxDesc mbox_img_url mb' . $uniqueid . '">' . ($desc ? $desc : $title) . '</div>
					' . $inline_info . $posttext;
                        } else {
                            if ($url_target == 'fancybox') {
                                // CASE: Link to URL that opens inside a popup via fancybox
                                $field->{$prop}[] = $pretext . '
					<span class="fc_image_thumb" style="' . $style . '; cursor: pointer;" ' . 'onclick="jQuery.fancybox.open([{ type: \'iframe\', href: \'' . $urllink . '\', topRatio: 0.9, leftRatio: 0.9, title: \'' . ($desc ? $title . ': ' . $desc : $title) . '\' }], { padding : 0});"
					>
						' . $img_legend . '
					</span>
					' . $inline_info . $posttext;
                            } else {
                                // CASE: Just link to URL without popup
                                $field->{$prop}[] = $pretext . '
					<a href="' . $urllink . '" target="' . $url_target . '">
						' . $img_legend . '
					</a>
					' . $inline_info . $posttext;
                            }
                        }
                    }
                } else {
                    if (!$usepopup || ($prop == 'display_large' || $prop == 'display_original')) {
                        // CASE 2: // No gallery code ... just apply pretext/posttext
                        $field->{$prop}[] = $pretext . $img_legend . $inline_info . $posttext;
                    } else {
                        if ($popuptype == 5 || $popuptype == 7) {
                            // CASE 3: Inline/special galleries OR --> GALLERIES THAT NEED SPECIAL ENCLOSERS
                            // !!! ... pretext/posttext/inline_info/etc not meaningful or not supported or not needed
                            switch ($popuptype) {
                                case 5:
                                    // Galleriffic inline slideshow gallery
                                    $group_str = '';
                                    // image grouping: not needed / not applicatble
                                    $field->{$prop}[] = '<a href="' . $srcl . '" class="fc_image_thumb thumb" name="drop">
							' . $img_legend . '
						</a>
						<div class="caption">
							<b>' . $title . '</b>
							<br/>' . $desc . '
						</div>';
                                    break;
                                case 7:
                                    // Elastislide inline carousel gallery (Responsive image gallery with togglable thumbnail-strip, plus previewer and description)
                                    // *** NEEDS: thumbnail list must be created with large size thubmnails, these will be then thumbnailed by the JS gallery code
                                    $title_attr = $desc ? $desc : $title;
                                    $img_legend_custom = '
						 <img src="' . JURI::root(true) . '/' . $src . '" alt ="' . $alt . '"' . $legend . ' class="' . $class . '"
						 	data-large="' . JURI::root(true) . '/' . $srcl . '" data-description="' . $title_attr . '" itemprop="image"/>
					';
                                    $group_str = $group_name ? 'rel="[' . $group_name . ']"' : '';
                                    $field->{$prop}[] = '
						<li><a href="javascript:;" class="fc_image_thumb">
							' . $img_legend_custom . '
						</a></li>';
                                    break;
                                default:
                                    // ERROR unhandled INLINE GALLERY case
                                    $field->{$prop}[] = ' Unhandled INLINE GALLERY case in image with field name: {$field->name} ';
                                    break;
                            }
                        } else {
                            // CASE 4: Popup galleries
                            switch ($popuptype) {
                                case 1:
                                    // Multibox image popup
                                    $group_str = $group_name ? 'rel="[' . $group_name . ']"' : '';
                                    $field->{$prop}[] = $pretext . '<a style="' . $style . '" href="' . $srcl . '" id="mb' . $uniqueid . '" class="fc_image_thumb mb" ' . $group_str . ' >
							' . $img_legend . '
						</a>
						<div class="multiBoxDesc mb' . $uniqueid . '">' . ($desc ? '<span class="badge">' . $title . '</span> ' . $desc : $title) . '</div>' . $inline_info . $posttext;
                                    break;
                                case 2:
                                    // Rokbox image popup
                                    $title_attr = $desc ? $desc : $title;
                                    $group_str = '';
                                    // no support for image grouping
                                    $field->{$prop}[] = $pretext . '<a style="' . $style . '" href="' . $srcl . '" rel="rokbox[' . $wl . ' ' . $hl . ']" ' . $group_str . ' title="' . $title_attr . '" class="fc_image_thumb" data-rokbox data-rokbox-caption="' . $title_attr . '">
							' . $img_legend . '
						</a>' . $inline_info . $posttext;
                                    break;
                                case 3:
                                    // JCE popup image popup
                                    $title_attr = $desc ? $title . ': ' . $desc : $title;
                                    // does not support HTML
                                    $group_str = $group_name ? 'rel="group[' . $group_name . ']"' : '';
                                    $field->{$prop}[] = $pretext . '<a style="' . $style . '" href="' . $srcl . '"  class="fc_image_thumb jcepopup" ' . $group_str . ' title="' . $title_attr . '">
							' . $img_nolegend . '
						</a>' . $inline_info . $posttext;
                                    break;
                                case 4:
                                    // Fancybox image popup
                                    $title_attr = $desc ? '<span class=\'badge\'>' . $title . '</span> ' . $desc : $title;
                                    $group_str = $group_name ? 'data-fancybox-group="' . $group_name . '"' : '';
                                    $field->{$prop}[] = $pretext . '<a style="' . $style . '" href="' . $srcl . '"  class="fc_image_thumb fancybox" ' . $group_str . ' title="' . $title_attr . '">
							' . $img_legend . '
						</a>' . $inline_info . $posttext;
                                    break;
                                case 6:
                                    // (Widgetkit) SPOTlight image popup
                                    $title_attr = $desc ? $desc : $title;
                                    $group_str = $group_name ? 'data-spotlight-group="' . $group_name . '"' : '';
                                    $field->{$prop}[] = $pretext . '<a style="' . $style . '" href="' . $srcl . '" class="fc_image_thumb" data-lightbox="on" data-spotlight="effect:bottom" ' . $group_str . ' title="' . $title_attr . '">
							' . $img_legend . '
							<div class="overlay">
								' . '<b>' . $title . '</b>: ' . $desc . '
							</div>
						</a>' . $inline_info . $posttext;
                                    break;
                                case 8:
                                    // PhotoSwipe popup carousel gallery
                                    $group_str = $group_name ? 'rel="[' . $group_name . ']"' : '';
                                    $field->{$prop}[] = $pretext . '<a style="' . $style . '" href="' . $srcl . '" ' . $group_str . ' class="fc_image_thumb">
							' . $img_legend . '
						</a>' . $inline_info . $posttext;
                                    break;
                                default:
                                    // Unknown / Other Gallery Type, just add thumbails ... maybe pretext/posttext/separator/opentag/closetag will add a gallery
                                    $field->{$prop}[] = $pretext . $img_legend . $inline_info . $posttext;
                                    break;
                            }
                        }
                    }
                }
            }
        }
        // **************************************************************
        // Apply separator and open/close tags and handle SPECIAL CASEs:
        // by adding (container) HTML required by some JS image libraries
        // **************************************************************
        // Using in field group, return array
        if ($is_ingroup) {
            return;
        }
        // Check for value only displays and return
        if (isset(self::$value_only_displays[$prop])) {
            return;
        }
        // Check for no values found
        if (!count($field->{$prop})) {
            $field->{$prop} = '';
            return;
        }
        // Galleriffic inline slideshow gallery
        if ($usepopup && $popuptype == 5) {
            $field->{$prop} = '
			<div id="gf_container">
				<div id="gallery" class="content">
					<div id="gf_controls" class="controls"></div>
					<div class="slideshow-container">
						<div id="gf_loading" class="loader"></div>
						<div id="gf_slideshow" class="slideshow"></div>
					</div>
					<div id="gf_caption" class="caption-container"></div>
				</div>
				<div id="gf_thumbs" class="navigation">
					<ul class="thumbs noscript">
						<li>
						' . implode("</li>\n<li>", $field->{$prop}) . '
						</li>
					</ul>
				</div>
				<div style="clear: both;"></div>
			</div>
			';
        } else {
            if ($usepopup && $popuptype == 7) {
                //$max_width = $field->parameters->get( 'w_l', 800 );
                // this should be size of previewer aka size of large image thumbnail
                $uid = 'es_' . $field->name . "_fcitem" . $item->id;
                $field->{$prop} = '
			<div id="rg-gallery_' . $uid . '" class="rg-gallery" >
				<div class="rg-thumbs">
					<!-- Elastislide Carousel Thumbnail Viewer -->
					<div class="es-carousel-wrapper">
						<div class="es-nav">
							<span class="es-nav-prev">' . JText::_('FLEXI_PREVIOUS') . '</span>
							<span class="es-nav-next">' . JText::_('FLEXI_NEXT') . '</span>
						</div>
						<div class="es-carousel">
							<ul>
								' . implode('', $field->{$prop}) . '
							</ul>
						</div>
					</div>
					<!-- End Elastislide Carousel Thumbnail Viewer -->
				</div><!-- rg-thumbs -->
			</div><!-- rg-gallery -->
			';
            } else {
                if ($usepopup && $popuptype == 8) {
                    $field->{$prop} = '
			<span class="photoswipe_fccontainer" >
				' . implode($separatorf, $field->{$prop}) . '
			</span>
			';
                } else {
                    $field->{$prop} = implode($separatorf, $field->{$prop});
                }
            }
        }
        // Apply open/close tags
        $field->{$prop} = $opentag . $field->{$prop} . $closetag;
    }
Example #26
0
    function onDisplayCoreFieldValue(&$_field, &$_item, &$params, $_tags = null, $_categories = null, $_favourites = null, $_favoured = null, $_vote = null, $values = null, $prop = 'display')
    {
        // this function is a mess and need complete refactoring
        // execute the code only if the field type match the plugin type
        $view = JRequest::setVar('view', JRequest::getVar('view', FLEXI_ITEMVIEW));
        static $cat_links = array();
        static $tag_links = array();
        if (!is_array($_item)) {
            $items = array(&$_item);
        } else {
            $items =& $_item;
        }
        // Prefix - Suffix - Separator parameters
        // these parameters should be common so we will retrieve them from the first item instead of inside the loop
        $item = reset($items);
        if (is_object($_field)) {
            $field = $_field;
        } else {
            $field = $item->fields[$_field];
        }
        $remove_space = $field->parameters->get('remove_space', 0);
        $_pretext = $field->parameters->get('pretext', '');
        $_posttext = $field->parameters->get('posttext', '');
        $separatorf = $field->parameters->get('separatorf', 3);
        $_opentag = $field->parameters->get('opentag', '');
        $_closetag = $field->parameters->get('closetag', '');
        $pretext_cacheable = $posttext_cacheable = $opentag_cacheable = $closetag_cacheable = false;
        foreach ($items as $item) {
            //if (!is_object($_field)) echo $item->id." - ".$_field ."<br/>";
            if (is_object($_field)) {
                $field = $_field;
            } else {
                $field = $item->fields[$_field];
            }
            if ($field->iscore != 1) {
                continue;
            }
            $field->item_id = $item->id;
            // Replace item properties or values of other fields
            if (!$pretext_cacheable) {
                $pretext = FlexicontentFields::replaceFieldValue($field, $item, $_pretext, 'pretext', $pretext_cacheable);
                if ($pretext && !$remove_space) {
                    $pretext = $pretext . ' ';
                }
            }
            if (!$posttext_cacheable) {
                $posttext = FlexicontentFields::replaceFieldValue($field, $item, $_posttext, 'posttext', $posttext_cacheable);
                if ($posttext && !$remove_space) {
                    $posttext = ' ' . $posttext;
                }
            }
            if (!$opentag_cacheable) {
                $opentag = FlexicontentFields::replaceFieldValue($field, $item, $_opentag, 'opentag', $opentag_cacheable);
            }
            // used by some fields
            if (!$closetag_cacheable) {
                $closetag = FlexicontentFields::replaceFieldValue($field, $item, $_closetag, 'closetag', $closetag_cacheable);
            }
            // used by some fields
            switch ($separatorf) {
                case 0:
                    $separatorf = ' ';
                    break;
                case 1:
                    $separatorf = '<br />';
                    break;
                case 2:
                    $separatorf = ' | ';
                    break;
                case 3:
                    $separatorf = ', ';
                    break;
                case 4:
                    $separatorf = $closetag . $opentag;
                    break;
                case 5:
                    $separatorf = '';
                    break;
                default:
                    $separatorf = '&nbsp;';
                    break;
            }
            $field->value = array();
            switch ($field->field_type) {
                case 'created':
                    // created
                    $field->value[] = $item->created;
                    $dateformat = $field->parameters->get('date_format', '');
                    $customdate = $field->parameters->get('custom_date', '');
                    $dateformat = $dateformat ? $dateformat : $customdate;
                    $field->display = $pretext . JHTML::_('date', $item->created, JText::_($dateformat)) . $posttext;
                    break;
                case 'createdby':
                    // created by
                    $field->value[] = $item->created_by;
                    $field->display = $pretext . ($field->parameters->get('name_username', 1) == 2 ? $item->cuname : $item->creator) . $posttext;
                    break;
                case 'modified':
                    // modified
                    $field->value[] = $item->modified;
                    $dateformat = $field->parameters->get('date_format', '');
                    $customdate = $field->parameters->get('custom_date', '');
                    $dateformat = $dateformat ? $dateformat : $customdate;
                    $field->display = $pretext . JHTML::_('date', $item->modified, JText::_($dateformat)) . $posttext;
                    break;
                case 'modifiedby':
                    // modified by
                    $field->value[] = $item->modified_by;
                    $field->display = $pretext . ($field->parameters->get('name_username', 1) == 2 ? $item->muname : $item->modifier) . $posttext;
                    break;
                case 'title':
                    // title
                    $field->value[] = $item->title;
                    $field->display = $pretext . $item->title . $posttext;
                    // Get ogp configuration
                    $useogp = $field->parameters->get('useogp', 1);
                    $ogpinview = $field->parameters->get('ogpinview', array());
                    $ogpinview = FLEXIUtilities::paramToArray($ogpinview);
                    $ogpmaxlen = $field->parameters->get('ogpmaxlen', 300);
                    if ($useogp && $field->{$prop}) {
                        if (in_array($view, $ogpinview)) {
                            $content_val = flexicontent_html::striptagsandcut($field->display, $ogpmaxlen);
                            JFactory::getDocument()->addCustomTag('<meta property="og:title" content="' . $content_val . '" />');
                        }
                    }
                    break;
                case 'hits':
                    // hits
                    $field->value[] = $item->hits;
                    $field->display = $pretext . $item->hits . $posttext;
                    break;
                case 'type':
                    // document type
                    $field->value[] = $item->type_id;
                    $field->display = $pretext . JText::_($item->typename) . $posttext;
                    break;
                case 'version':
                    // version
                    $field->value[] = $item->version;
                    $field->display = $pretext . $item->version . $posttext;
                    break;
                case 'state':
                    // state
                    $field->value[] = $item->state;
                    $field->display = $pretext . flexicontent_html::stateicon($item->state, $field->parameters) . $posttext;
                    break;
                case 'voting':
                    // voting button
                    if ($_vote === false) {
                        $vote =& $item->vote;
                    } else {
                        $vote =& $_vote;
                    }
                    $field->value[] = 'button';
                    // dummy value to force display
                    $field->display = $pretext . flexicontent_html::ItemVote($field, 'all', $vote) . $posttext;
                    break;
                case 'favourites':
                    // favourites button
                    if ($_favourites === false) {
                        $favourites =& $item->favs;
                    } else {
                        $favourites =& $_favourites;
                    }
                    if ($_favoured === false) {
                        $favoured =& $item->fav;
                    } else {
                        $favoured =& $_favoured;
                    }
                    $field->value[] = 'button';
                    // dummy value to force display
                    $favs = flexicontent_html::favoured_userlist($field, $item, $favourites);
                    $field->display = $pretext . '
					<span class="fav-block">
						' . flexicontent_html::favicon($field, $favoured, $item) . '
						<span id="fcfav-reponse_' . $field->item_id . '" class="fcfav-reponse">
							<small>' . $favs . '</small>
						</span>
					</span>
						' . $posttext;
                    break;
                case 'categories':
                    // assigned categories
                    $field->display = '';
                    if ($_categories === false) {
                        $categories =& $item->cats;
                    } else {
                        $categories =& $_categories;
                    }
                    if ($categories) {
                        // Get categories that should be excluded from linking
                        global $globalnoroute;
                        if (!is_array($globalnoroute)) {
                            $globalnoroute = array();
                        }
                        // Create list of category links, excluding the "noroute" categories
                        $field->display = array();
                        foreach ($categories as $category) {
                            $cat_id = $category->id;
                            if (in_array($cat_id, @$globalnoroute)) {
                                continue;
                            }
                            if (!isset($cat_links[$cat_id])) {
                                $cat_links[$cat_id] = JRoute::_(FlexicontentHelperRoute::getCategoryRoute($category->slug));
                            }
                            $cat_link = $cat_links[$cat_id];
                            $display = '<a class="fc_categories fc_category_' . $cat_id . ' link_' . $field->name . '" href="' . $cat_link . '">' . $category->title . '</a>';
                            $field->display[] = $pretext . $display . $posttext;
                            $field->value[] = $category->title;
                        }
                        $field->display = implode($separatorf, $field->display);
                        $field->display = $opentag . $field->display . $closetag;
                    }
                    break;
                case 'tags':
                    // assigned tags
                    $field->display = '';
                    if ($_tags === false) {
                        $tags =& $item->tags;
                    } else {
                        $tags =& $_tags;
                    }
                    if ($tags) {
                        // Create list of tag links
                        $field->display = array();
                        foreach ($tags as $tag) {
                            $tag_id = $tag->id;
                            if (!isset($tag_links[$tag_id])) {
                                $tag_links[$tag_id] = JRoute::_(FlexicontentHelperRoute::getTagRoute($tag->slug));
                            }
                            $tag_link = $tag_links[$tag_id];
                            $display = '<a class="fc_tags fc_tag_' . $tag->id . ' link_' . $field->name . '" href="' . $tag_link . '">' . $tag->name . '</a>';
                            $field->display[] = $pretext . $display . $posttext;
                            $field->value[] = $tag->name;
                        }
                        $field->display = implode($separatorf, $field->display);
                        $field->display = $opentag . $field->display . $closetag;
                    }
                    break;
                case 'maintext':
                    // main text
                    // Special display variables
                    if ($prop != 'display') {
                        switch ($prop) {
                            case 'display_if':
                                $field->{$prop} = $item->introtext . chr(13) . chr(13) . $item->fulltext;
                                break;
                            case 'display_i':
                                $field->{$prop} = $item->introtext;
                                break;
                            case 'display_f':
                                $field->{$prop} = $item->fulltext;
                                break;
                        }
                    } else {
                        if (!$item->fulltext) {
                            $field->display = $item->introtext;
                        } else {
                            if ($view != FLEXI_ITEMVIEW) {
                                if ($item->parameters->get('force_full', 0)) {
                                    $field->display = $item->introtext . chr(13) . chr(13) . $item->fulltext;
                                } else {
                                    $field->display = $item->introtext;
                                }
                            } else {
                                if ($item->parameters->get('show_intro', 1)) {
                                    $field->display = $item->introtext . chr(13) . chr(13) . $item->fulltext;
                                } else {
                                    $field->display = $item->fulltext;
                                }
                            }
                        }
                    }
                    // Get ogp configuration
                    $useogp = $field->parameters->get('useogp', 1);
                    $ogpinview = $field->parameters->get('ogpinview', array());
                    $ogpinview = FLEXIUtilities::paramToArray($ogpinview);
                    $ogpmaxlen = $field->parameters->get('ogpmaxlen', 300);
                    if ($useogp && $field->{$prop}) {
                        if (in_array($view, $ogpinview)) {
                            if ($item->metadesc) {
                                JFactory::getDocument()->addCustomTag('<meta property="og:description" content="' . $item->metadesc . '" />');
                            } else {
                                $content_val = flexicontent_html::striptagsandcut($field->display, $ogpmaxlen);
                                JFactory::getDocument()->addCustomTag('<meta property="og:description" content="' . $content_val . '" />');
                            }
                        }
                    }
                    break;
            }
        }
    }
Example #27
0
 function initialPermission()
 {
     $component_name = JRequest::getCmd('option');
     $db = JFactory::getDBO();
     $asset = JTable::getInstance('asset');
     // Create an asset object
     /*** Component assets ***/
     if (!$asset->loadByName($component_name)) {
         // The assets entry does not exist: We will create initial rules for all component's actions
         // Get root asset
         $root = JTable::getInstance('asset');
         $root->loadByName('root.1');
         // Initialize component asset
         $asset->name = $component_name;
         $asset->title = $component_name;
         $asset->setLocation($root->id, 'last-child');
         // father of compontent asset it the root asset
         // Create initial component rules and set them into the asset
         $initial_rules = $this->_createComponentRules($component_name);
         $component_rules = new JAccessRules(json_encode($initial_rules));
         $asset->rules = $component_rules->__toString();
         // Save the asset into the DB
         if (!$asset->check() || !$asset->store()) {
             echo $asset->getError();
             $this->setError($asset->getError());
             return false;
         }
     } else {
         // The assets entry already exists: We will check if it has exactly the actions specified in component's access.xml file
         // Get existing DB rules and component's actions from the access.xml file
         $existing_rules = new JAccessRules($asset->rules);
         $rules_data = $existing_rules->getData();
         $component_actions = JAccess::getActions('com_flexicontent', 'component');
         // Find any deleted / added actions ...
         $db_action_names = array();
         foreach ($rules_data as $action_name => $data) {
             $db_action_names[] = $action_name;
         }
         foreach ($component_actions as $action) {
             $file_action_names[] = $action->name;
         }
         $deleted_actions = array_diff($db_action_names, $file_action_names);
         $added_actions = array_diff($file_action_names, $db_action_names);
         if (count($deleted_actions) || count($added_actions)) {
             // We have changes in the component actions
             // First merge the existing component (db) rules into the initial rules
             $initial_rules = $this->_createComponentRules($component_name);
             $component_rules = new JAccessRules(json_encode($initial_rules));
             $component_rules->merge($existing_rules);
             // Second, check if obsolete rules are contained in the existing component (db) rules, if so create a new rules object without the obsolete rules
             if ($deleted_actions) {
                 $rules_data = $component_rules->getData();
                 foreach ($deleted_actions as $action_name) {
                     unset($rules_data[$action_name]);
                 }
                 $component_rules = new JAccessRules($rules_data);
             }
             // Set asset rules
             $asset->rules = $component_rules->__toString();
             // Save the asset
             if (!$asset->check() || !$asset->store()) {
                 echo $asset->getError();
                 $this->setError($asset->getError());
                 return false;
             }
         }
     }
     // Load component asset
     $component_asset = JTable::getInstance('asset');
     $component_asset->loadByName($component_name);
     /*** CATEGORY assets ***/
     // Get a list com_content categories that do not have assets (or have wrong asset names)
     $query = $db->getQuery(true)->select('c.id, c.parent_id, c.title, c.asset_id')->from('#__assets AS se')->join('RIGHT', '#__categories AS c ON se.id=c.asset_id AND se.name=concat("com_content.category.",c.id)')->where('(se.id is NULL OR (c.parent_id=1 AND se.parent_id!=' . (int) $asset->id . ') )')->where('c.extension = ' . $db->quote('com_content'))->order('c.level ASC');
     // IMPORTANT create categories asset using increasing depth level, so that get parent assetid will not fail
     $db->setQuery($query);
     $results = $db->loadObjectList();
     if ($db->getErrorNum()) {
         echo $db->getErrorMsg();
     }
     // Add an asset to every category that doesnot have one
     if (count($results) > 0) {
         foreach ($results as $category) {
             $parentId = $this->_getAssetParentId(null, $category);
             $name = "com_content.category.{$category->id}";
             // Try to load asset for the current CATEGORY ID
             $asset_found = $asset->loadByName($name);
             if (!$asset_found) {
                 if ($category->asset_id) {
                     // asset name not found but category has an asset id set ?, we could delete it here
                     // but it maybe dangerous to do so ... it might be a legitimate asset_id for something else
                 }
                 // Set id to null since we will be creating a new asset on store
                 $asset->id = null;
                 // Set asset rules to empty, (DO NOT set any ACTIONS, just let them inherit ... from parent)
                 $asset->rules = new JAccessRules();
                 /*if ($parentId == $component_asset->id) {				
                 			$actions	= JAccess::getActions($component_name, 'category');
                 			$rules 		= json_decode($component_asset->rules);		
                 			foreach ($actions as $action) {
                 				$catrules[$action->name] = $rules->{$action->name};
                 			}
                 			$rules = new JAccessRules(json_encode($catrules));
                 			$asset->rules = $rules->__toString();
                 		} else {
                 			$parent = JTable::getInstance('asset');
                 			$parent->load($parentId);
                 			$asset->rules = $parent->rules;
                 		}*/
             } else {
                 // do not change (a) the id OR (b) the rules, of the asset
             }
             // Initialize appropriate asset properties
             $asset->name = $name;
             $asset->title = $category->title;
             $asset->setLocation($parentId, 'last-child');
             // Permissions of categories are inherited by parent category, or from component if no parent category exists
             // Save the category asset (create or update it)
             if (!$asset->check() || !$asset->store(false)) {
                 echo $asset->getError();
                 echo " Problem for asset with id: " . $asset->id;
                 echo " Problem for category with id: " . $category->id . "(" . $category->title . ")";
                 $this->setError($asset->getError());
                 return false;
             }
             // Assign the asset to the category, if it is not already assigned
             $query = $db->getQuery(true)->update('#__categories')->set('asset_id = ' . (int) $asset->id)->where('id = ' . (int) $category->id);
             $db->setQuery($query);
             if (!$db->query()) {
                 echo JText::sprintf('JLIB_DATABASE_ERROR_STORE_FAILED', get_class($this), $db->getErrorMsg());
                 $this->setError(JText::sprintf('JLIB_DATABASE_ERROR_STORE_FAILED', get_class($this), $db->getErrorMsg()));
                 return false;
             }
         }
     }
     /*** ITEM assets ***/
     /*
     // Get a list com_content items that do not have assets (or have wrong asset names)
     $query = $db->getQuery(true)
     	->select('c.id, c.catid as parent_id, c.title, c.asset_id')
     	->from('#__assets AS se')->join('RIGHT', '#__content AS c ON se.id=c.asset_id AND se.name=concat("com_content.article.",c.id)')
     	->where('se.id is NULL');//->where('c.extension = ' . $db->quote('com_content'));
     $db->setQuery($query);
     $results = $db->loadObjectList();					if ($db->getErrorNum()) echo $db->getErrorMsg();
     
     // Add an asset to every item that doesnot have one
     if(count($results)>0) {
     	foreach($results as $item) {
     		$parentId = $this->_getAssetParentId(null, $item);
     		$name = "com_content.article.{$item->id}";
     		
     		// Try to load asset for the current CATEGORY ID
     		$asset_found = $asset->loadByName($name);
     		
     		if ( !$asset_found ) {
     			if ($item->asset_id) {
     				// asset name not found but item has an asset id set ?, we could delete it here
     				// but it maybe dangerous to do so ... it might be a legitimate asset_id for something else
     			}
     			
     			// Set id to null since we will be creating a new asset on store
     			$asset->id 		= null;
     			
     			// Set asset rules to empty, (DO NOT set any ACTIONS, just let them inherit ... from parent)
     			$asset->rules = new JAccessRules();
     			
     			//if ($parentId == $component_asset->id) {				
     			//	$actions	= JAccess::getActions($component_name, 'article');
     			//	$rules 		= json_decode($component_asset->rules);		
     			//	foreach ($actions as $action) {
     			//		$catrules[$action->name] = $rules->{$action->name};
     			//	}
     			//	$rules = new JAccessRules(json_encode($catrules));
     			//	$asset->rules = $rules->__toString();
     			//} else {
     			//	$parent = JTable::getInstance('asset');
     			//	$parent->load($parentId);
     			//	$asset->rules = $parent->rules;
     			//}
     		} else {
     			// do not change (a) the id OR (b) the rules, of the asset
     		}
     		
     		// Initialize appropriate asset properties
     		$asset->name	= $name;
     		$asset->title	= $item->title;
     		$asset->setLocation($parentId, 'last-child');     // Permissions of items are inherited from their main category
     		
     		// Save the item asset (create or update it)
     		if (!$asset->check() || !$asset->store(false)) {
     			echo $asset->getError();
     			$this->setError($asset->getError());
     			return false;
     		}
     		
     		// Assign the asset to the item, if it is not already assigned
     		$query = $db->getQuery(true)
     			->update('#__content')
     			->set('asset_id = ' . (int)$asset->id)
     			->where('id = ' . (int)$item->id);
     		$db->setQuery($query);
     		
     		if (!$db->query()) {
     			echo JText::sprintf('JLIB_DATABASE_ERROR_STORE_FAILED', get_class($this), $db->getErrorMsg());
     			$this->setError(JText::sprintf('JLIB_DATABASE_ERROR_STORE_FAILED', get_class($this), $db->getErrorMsg()));
     			return false;
     		}
     	}
     }
     */
     /*** FLEXIcontent FIELDS assets ***/
     // Get a list flexicontent fields that do not have assets
     $query = $db->getQuery(true)->select('ff.id, ff.name, ff.asset_id')->from('#__assets AS se')->join('RIGHT', '#__flexicontent_fields AS ff ON se.id=ff.asset_id AND se.name=concat("com_flexicontent.field.",ff.id)')->where('se.id is NULL');
     $db->setQuery($query);
     $results = $db->loadObjectList();
     if ($db->getErrorNum()) {
         echo $db->getErrorMsg();
     }
     // Add an asset to every field that doesnot have one
     if (count($results) > 0) {
         foreach ($results as $field) {
             $name = "com_flexicontent.field.{$field->id}";
             // Test if an asset for the current FIELD ID already exists and load it instead of creating a new asset
             if (!$asset->loadByName($name)) {
                 if ($field->asset_id) {
                     // asset name not found but field has an asset id set ?, we could delete it here
                     // but it maybe dangerous to do so ... it might be a legitimate asset_id for something else
                 }
                 // Initialize field asset
                 $asset->id = null;
                 $asset->name = $name;
                 $asset->title = $field->name;
                 $asset->setLocation($component_asset->id, 'last-child');
                 // Permissions of fields are directly inheritted by component
                 // Set asset rules to empty, (DO NOT set any ACTIONS, just let them inherit ... from parent)
                 $asset->rules = new JAccessRules();
                 /*
                 $actions	= JAccess::getActions($component_name, 'field');
                 $rules 		= json_decode($component_asset->rules);		
                 foreach ($actions as $action) {
                 	$fieldrules[$action->name] = $rules->{$action->name};
                 }
                 $rules = new JAccessRules(json_encode($fieldrules));
                 $asset->rules = $rules->__toString();
                 */
                 // Save the asset
                 if (!$asset->check() || !$asset->store(false)) {
                     echo $asset->getError();
                     $this->setError($asset->getError());
                     return false;
                 }
             }
             // Assign the asset to the field
             $query = $db->getQuery(true)->update('#__flexicontent_fields')->set('asset_id = ' . (int) $asset->id)->where('id = ' . (int) $field->id);
             $db->setQuery($query);
             if (!$db->query()) {
                 echo JText::sprintf('JLIB_DATABASE_ERROR_STORE_FAILED', get_class($this), $db->getErrorMsg());
                 $this->setError(JText::sprintf('JLIB_DATABASE_ERROR_STORE_FAILED', get_class($this), $db->getErrorMsg()));
                 return false;
             }
         }
     }
     /*** FLEXIcontent TYPES assets ***/
     // Get a list flexicontent types that do not have assets
     $query = $db->getQuery(true)->select('ff.id, ff.name, ff.asset_id')->from('#__assets AS se')->join('RIGHT', '#__flexicontent_types AS ff ON se.id=ff.asset_id AND se.name=concat("com_flexicontent.type.",ff.id)')->where('se.id is NULL');
     $db->setQuery($query);
     $results = $db->loadObjectList();
     if ($db->getErrorNum()) {
         echo $db->getErrorMsg();
     }
     // Add an asset to every type that doesnot have one
     if (count($results) > 0) {
         foreach ($results as $type) {
             $name = "com_flexicontent.type.{$type->id}";
             // Test if an asset for the current TYPE ID already exists and load it instead of creating a new asset
             if (!$asset->loadByName($name)) {
                 if ($type->asset_id) {
                     // asset name not found but type has an asset id set ?, we could delete it here
                     // but it maybe dangerous to do so ... it might be a legitimate asset_id for something else
                 }
                 // Initialize type asset
                 $asset->id = null;
                 $asset->name = $name;
                 $asset->title = $type->name;
                 $asset->setLocation($component_asset->id, 'last-child');
                 // Permissions of types are directly inheritted by component
                 // Set asset rules to empty, (DO NOT set any ACTIONS, just let them inherit ... from parent)
                 $asset->rules = new JAccessRules();
                 /*
                 $actions	= JAccess::getActions($component_name, 'type');
                 $rules 		= json_decode($component_asset->rules);		
                 foreach ($actions as $action) {
                 	$typerules[$action->name] = $rules->{$action->name};
                 }
                 $rules = new JAccessRules(json_encode($typerules));
                 $asset->rules = $rules->__toString();
                 */
                 // Save the asset
                 if (!$asset->check() || !$asset->store(false)) {
                     echo $asset->getError();
                     $this->setError($asset->getError());
                     return false;
                 }
             }
             // Assign the asset to the type
             $query = $db->getQuery(true)->update('#__flexicontent_types')->set('asset_id = ' . (int) $asset->id)->where('id = ' . (int) $type->id);
             $db->setQuery($query);
             if (!$db->query()) {
                 echo JText::sprintf('JLIB_DATABASE_ERROR_STORE_FAILED', get_class($this), $db->getErrorMsg());
                 $this->setError(JText::sprintf('JLIB_DATABASE_ERROR_STORE_FAILED', get_class($this), $db->getErrorMsg()));
                 return false;
             }
         }
     }
     // Clear cache so that per user permissions objects are recalculated
     $cache = FLEXIUtilities::getCache($group = '', 0);
     $cache->clean('com_flexicontent_cats');
     $cache = FLEXIUtilities::getCache($group = '', 1);
     $cache->clean('com_flexicontent_cats');
     return true;
 }
Example #28
0
 function onBeforeSaveField(&$field, &$post, &$file, &$item)
 {
     if ($field->iscore != 1) {
         return;
     }
     if (!is_array($post) && !strlen($post)) {
         return;
     }
     if ($field->field_type == 'maintext') {
         // field_type is not changed textarea so that field can handle this field type
         FLEXIUtilities::call_FC_Field_Func('textarea', 'onBeforeSaveField', array(&$field, &$post, &$file, &$item));
     }
 }
 /**
  * Method to creat the HTML of filters
  * 
  * @access public
  * @return object
  * @since 1.5
  */
 static function renderFilters(&$params, &$filters, $form_name)
 {
     // Make the filter compatible with Joomla standard cache
     $cache = JFactory::getCache('com_flexicontent');
     $cache->clean();
     $filter_prefix = ($form_name == 'item_form' ? 'iform_' : '') . 'filter_';
     $display_label_filter_override = (int) $params->get('show_filter_labels', 0);
     foreach ($filters as $filter_name => $filter) {
         $filtervalue = JRequest::getVar($filter_prefix . $filter->id, '', 'default');
         //print_r($filtervalue);
         // make sure filter HTML is cleared, and create it
         $display_label_filter_saved = $filter->parameters->get('display_label_filter');
         if ($display_label_filter_override) {
             $filter->parameters->set('display_label_filter', $display_label_filter_override);
         }
         // suppress labels inside filter's HTML (hide or show all labels externally)
         // else ... filter default label behavior
         $filter->html = '';
         // make sure filter HTML display is cleared
         $field_type = $filter->iscore ? 'core' : $filter->field_type;
         //$results 	= $dispatcher->trigger('onDisplayFilter', array( &$filter, $filtervalue ));
         FLEXIUtilities::call_FC_Field_Func($field_type, 'onDisplayFilter', array(&$filter, $filtervalue, $form_name));
         $filter->parameters->set('display_label_filter', $display_label_filter_saved);
     }
 }
Example #30
0
    /**
     * Creates the Filemanagerview
     *
     * @since 1.0
     */
    function display($tpl = null)
    {
        // Check for request forgeries
        JRequest::checkToken('request') or jexit('Invalid Token');
        flexicontent_html::loadJQuery();
        flexicontent_html::loadFramework('select2');
        JHTML::_('behavior.tooltip');
        // Load the form validation behavior
        JHTML::_('behavior.formvalidation');
        //initialise variables
        $app = JFactory::getApplication();
        $option = JRequest::getVar('option');
        $document = JFactory::getDocument();
        $db = JFactory::getDBO();
        $user = JFactory::getUser();
        $params = JComponentHelper::getParams('com_flexicontent');
        //$authorparams = flexicontent_db::getUserConfig($user->id);
        $langs = FLEXIUtilities::getLanguages('code');
        $fieldid = JRequest::getVar('field', null, 'request', 'int');
        $client = $app->isAdmin() ? '../' : '';
        //get vars
        $filter_order = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.filter_order', 'filter_order', 'f.filename', 'cmd');
        $filter_order_Dir = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.filter_order_Dir', 'filter_order_Dir', '', 'word');
        $filter = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.filter', 'filter', 1, 'int');
        $filter_lang = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.filter_lang', 'filter_lang', '', 'string');
        $filter_uploader = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.filter_uploader', 'filter_uploader', 0, 'int');
        $filter_url = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.filter_url', 'filter_url', '', 'word');
        $filter_secure = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.filter_secure', 'filter_secure', '', 'word');
        $filter_ext = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.filter_ext', 'filter_ext', '', 'alnum');
        $search = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.search', 'search', '', 'string');
        $filter_item = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.item_id', 'item_id', '', 'int');
        $u_item_id = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.u_item_id', 'u_item_id', 0, 'string');
        $autoselect = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.autoselect', 'autoselect', 0, 'int');
        $autoassign = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.autoassign', 'autoassign', 0, 'int');
        $folder_mode = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.folder_mode', 'folder_mode', 0, 'int');
        $folder_param = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.folder_param', 'folder_param', 'dir', 'string');
        $append_item = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.append_item', 'append_item', 1, 'int');
        $append_field = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.append_field', 'append_field', 1, 'int');
        $targetid = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.targetid', 'targetid', '', 'string');
        $thumb_w = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.thumb_w', 'thumb_w', 120, 'int');
        $thumb_h = $app->getUserStateFromRequest($option . '.fileselement' . $fieldid . '.thumb_h', 'thumb_h', 90, 'int');
        $search = FLEXI_J16GE ? $db->escape(trim(JString::strtolower($search))) : $db->getEscaped(trim(JString::strtolower($search)));
        $newfileid = JRequest::getInt('newfileid');
        $newfilename = base64_decode(JRequest::getVar('newfilename', ''));
        $delfilename = base64_decode(JRequest::getVar('delfilename', ''));
        //add css and submenu to document
        if ($app->isSite()) {
            $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/flexicontent.css');
            $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/flexi_shared.css');
            // NOTE: this is imported by main Frontend CSS file
        } else {
            $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/flexicontentbackend.css');
        }
        if (FLEXI_J30GE) {
            $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/j3x.css');
        } else {
            if (FLEXI_J16GE) {
                $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/j25.css');
            } else {
                $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/j15.css');
            }
        }
        $document->addStyleSheet(JURI::root() . 'administrator/templates/system/css/system.css');
        // include backend CSS template CSS file , access to backend folder may not be allowed but ...
        if ($app->isSite()) {
            $template = !FLEXI_J16GE ? 'khepri' : (FLEXI_J30GE ? 'hathor' : 'bluestork');
            $document->addStyleSheet(JURI::root() . 'administrator/templates/' . $template . (FLEXI_J16GE ? '/css/template.css' : '/css/general.css'));
        }
        //a trick to avoid loosing general style in modal window
        $css = 'body, td, th { font-size: 11px; }
		a.striketext {
			text-decoration: line-through;
			color:red;
			font-style:italic;
		}
		';
        $document->addStyleDeclaration($css);
        // Get User's Global Permissions
        $perms = FlexicontentHelperPerm::getPerm();
        // ***********************
        // Get data from the model
        // ***********************
        $model = $this->getModel();
        if (!$folder_mode) {
            $rows = $this->get('Data');
            $img_folder = '';
        } else {
            $rows = $model->getFilesFromPath($u_item_id, $fieldid, $append_item, $append_field, $folder_param);
            $img_folder = $model->getFieldFolderPath($u_item_id, $fieldid, $append_item, $append_field, $folder_param);
            $img_path = str_replace('\\', '/', $img_folder . DS . $newfilename);
            $thumb = JURI::root() . 'components/com_flexicontent/librairies/phpthumb/phpThumb.php?src=' . $img_path . '&w=' . $thumb_w . '&h=' . $thumb_h;
        }
        $upload_path_var = 'fc_upload_path_' . $fieldid . '_' . $u_item_id;
        $app->setUserState($upload_path_var, $img_folder);
        //echo $upload_path_var . "<br>";
        //echo $app->getUserState( $upload_path_var, 'noset' );
        $pagination = $this->get('Pagination');
        //$users = $this->get('Users');
        // Get item using at least one file (-of- the currently listed files)
        /*$items_single	= $model->getItemsSingleprop( array('file','minigallery') );
        		$items_multi	= $model->getItemsMultiprop ( $field_props=array('image'=>'originalname'), $value_props=array('image'=>'filename') );
        		$items = array();
        		foreach ($items_single as $item_id => $_item) $items[$item_id] = $_item;
        		foreach ($items_multi  as $item_id => $_item) $items[$item_id] = $_item;
        		ksort($items);*/
        $fname = $model->getFieldName($fieldid);
        $files_selected = $model->getItemFiles($u_item_id);
        $formfieldname = FLEXI_J16GE ? 'custom[' . $fname . '][]' : $fname . '[]';
        //add js to document
        if ($folder_mode) {
            $js = "\n\t\t\t\n\t\t\twindow.addEvent('domready', function() {\n\n\t\t    function closest (obj, el) {\n\t\t        var find = obj.getElement(el);\n\t\t        var self = obj;\n\t\t        \n\t\t        while (self && !find) {\n\t\t            self = self.getParent();\n\t\t            find = self ? self.getElement(el) : null;\n\t\t        }\n\t\t        return find;\n\t\t    }\n\n\t\t\t\tvar delfilename = '" . $delfilename . "';\n\t\t\t\tvar remove_existing_files_from_list = 0;\n\t\t\t\tvar remove_new_files_from_list = 0;\n\t\t\t\toriginal_objs = \$(window.parent.document.body).getElement('#container_fcfield_" . $fieldid . "').getElements('.originalname');\n\t\t\t\texisting_objs = \$(window.parent.document.body).getElement('#container_fcfield_" . $fieldid . "').getElements('.existingname');\n\t\t\t\t\n\t\t\t\tvar imgobjs = Array();\n\t\t\t\tfor(i=0,n=original_objs.length; i<n; i++)  {\n\t\t\t\t\tif (original_objs[i].value) imgobjs.push(original_objs[i].value);\n\t\t\t\t\tif ( delfilename!='' && original_objs[i].value == delfilename)\n\t\t\t\t\t{\n\t\t\t\t\t\twindow.parent.deleteField" . $fieldid . "( original_objs[i].getParent() );\n\t\t\t\t\t\tremove_existing_files_from_list = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor(i=0,n=existing_objs.length; i<n; i++) {\n\t\t\t\t\tif ( existing_objs[i].value) imgobjs.push(existing_objs[i].value);\n\t\t\t\t\tif ( delfilename!='' && existing_objs[i].value == delfilename)\n\t\t\t\t\t{\n\t\t\t\t\t\twindow.parent.deleteField" . $fieldid . "(\n\t\t\t\t\t\t\t(MooTools.version>='1.2.4')  ?  existing_objs[i].getParent('.img_value_props')  :  closest (existing_objs[i] , '.img_value_props')\n\t\t\t\t\t\t);\n\t\t\t\t\t\tremove_new_files_from_list = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif ( remove_existing_files_from_list || remove_new_files_from_list ) {\n\t\t\t\t\tmssg = '" . JText::_('FLEXI_DELETE_FILE_IN_LIST_WINDOW_MUST_CLOSE') . "';\n\t\t\t\t\tmssg = mssg + '\\n' + (remove_existing_files_from_list ? '" . JText::_('FLEXI_EXISTING_FILE_REMOVED_SAVE_RECOMMENEDED', true) . "' : '');\n\t\t\t\t\talert( mssg );\n\t\t\t\t\t(MooTools.version>='1.2.4') ?  window.parent.SqueezeBox.close()  :  window.parent.document.getElementById('sbox-window').close();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tfor(i=0,n=imgobjs.length; i<n; i++) {\n\t\t\t\t\tvar rows = \$(document.body).getElements('a[rel='+ imgobjs[i] +']');\n\t\t\t\t\trows.addClass('striketext');\n\t\t\t\t\t\n\t\t\t\t\t//if( (typeof rows) != 'undefined' && rows != null) {\n\t\t\t\t\t\t//alert(rows[0]);\n\t\t\t\t\t\t//row.className = 'striketext';\n\t\t\t\t\t//}\n\t\t\t\t}\n\t\t\t\t" . ($autoassign && $newfilename ? "window.parent.qmAssignFile" . $fieldid . "('" . $targetid . "', '" . $newfilename . "', '" . $thumb . "');" : "") . "\n\t\t\t});\n\t\t\t";
        } else {
            $js = "\n\t\t\tfunction qffileselementadd(obj, id, file) {\n\t\t\t\tvar result = window.parent.qfSelectFile" . $fieldid . "(id, file);\n\t\t\t\tif ((typeof result) != 'undefined' && result == 'cancel') return;\n\t\t\t\tobj.className = 'striketext';\n\t\t\t\tdocument.adminForm.file.value=id;\n\t\t\t}\n\t\t\twindow.addEvent('domready', function() {\n\t\t\t\tfileobjs = window.parent.document.getElementsByName('{$formfieldname}');\n\t\t\t\tfor(i=0,n=fileobjs.length; i<n; i++) {\n\t\t\t\t\trow = document.getElementById('file'+fileobjs[i].value);\n\t\t\t\t\tif( (typeof row) != 'undefined' && row != null) {\n\t\t\t\t\t\trow.className = 'striketext';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t" . ($autoselect && $newfileid ? "qffileselementadd( document.getElementById('file" . $newfileid . "'), '" . $newfileid . "', '" . $newfilename . "');" : "") . "\n\t\t\t});\n\t\t\t";
        }
        $document->addScriptDeclaration($js);
        if ($autoselect && $newfileid) {
            $app->enqueueMessage(JText::_('FLEXI_UPLOADED_FILE_WAS_SELECTED'), 'message');
        }
        /*****************
         ** BUILD LISTS **
         *****************/
        $lists = array();
        // ** FILE UPLOAD FORM **
        // Build languages list
        //$allowed_langs = !$authorparams ? null : $authorparams->get('langs_allowed',null);
        //$allowed_langs = !$allowed_langs ? null : FLEXIUtilities::paramToArray($allowed_langs);
        $display_file_lang_as = $params->get('display_file_lang_as', 3);
        $allowed_langs = null;
        if (FLEXI_FISH || FLEXI_J16GE) {
            $lists['file-lang'] = flexicontent_html::buildlanguageslist('file-lang', '', '*', $display_file_lang_as, $allowed_langs, $published_only = false);
        } else {
            $lists['file-lang'] = flexicontent_html::getSiteDefaultLang() . '<input type="hidden" name="file-lang" value="' . flexicontent_html::getSiteDefaultLang() . '" />';
        }
        /*************
         ** FILTERS **
         *************/
        // language filter
        $lists['language'] = flexicontent_html::buildlanguageslist('filter_lang', 'class="use_select2_lib" onchange="submitform();" size="1" ', $filter_lang, 2);
        // search
        $lists['search'] = $search;
        //search filter
        $filters = array();
        $filters[] = JHTML::_('select.option', '1', JText::_('FLEXI_FILENAME'));
        $filters[] = JHTML::_('select.option', '2', JText::_('FLEXI_FILE_TITLE'));
        $lists['filter'] = JHTML::_('select.genericlist', $filters, 'filter', 'size="1" class="use_select2_lib"', 'value', 'text', $filter);
        //build url/file filterlist
        $url = array();
        $url[] = JHTML::_('select.option', '', '- ' . JText::_('FLEXI_ALL_FILES') . ' -');
        $url[] = JHTML::_('select.option', 'F', JText::_('FLEXI_FILE'));
        $url[] = JHTML::_('select.option', 'U', JText::_('FLEXI_URL'));
        $lists['url'] = JHTML::_('select.genericlist', $url, 'filter_url', 'class="use_select2_lib" size="1" onchange="submitform( );"', 'value', 'text', $filter_url);
        //item lists
        /*$items_list = array();
        		$items_list[] = JHTML::_('select.option', '', '- '. JText::_( 'FLEXI_FILTER_BY_ITEM' ) .' -' );
        		foreach($items as $item) {
        			$items_list[] = JHTML::_('select.option', $item->id, JText::_( $item->title ) . ' (#' . $item->id . ')' );
        		}
        		$lists['item_id'] = JHTML::_('select.genericlist', $items_list, 'item_id', 'size="1" class="use_select2_lib" onchange="submitform( );"', 'value', 'text', $filter_item );*/
        $lists['item_id'] = '<input type="text" name="item_id" size="1" class="inputbox" onchange="submitform( );" value="' . $filter_item . '" />';
        //build secure/media filterlist
        $secure = array();
        $secure[] = JHTML::_('select.option', '', '- ' . JText::_('FLEXI_ALL_DIRECTORIES') . ' -');
        $secure[] = JHTML::_('select.option', 'S', JText::_('FLEXI_SECURE_DIR'));
        $secure[] = JHTML::_('select.option', 'M', JText::_('FLEXI_MEDIA_DIR'));
        $lists['secure'] = JHTML::_('select.genericlist', $secure, 'filter_secure', 'class="use_select2_lib" size="1" onchange="submitform( );"', 'value', 'text', $filter_secure);
        //build ext filterlist
        $lists['ext'] = flexicontent_html::buildfilesextlist('filter_ext', 'class="use_select2_lib" size="1" onchange="submitform( );"', $filter_ext);
        //build uploader filterlist
        $lists['uploader'] = flexicontent_html::builduploaderlist('filter_uploader', 'class="use_select2_lib" size="1" onchange="submitform( );"', $filter_uploader);
        // table ordering
        $lists['order_Dir'] = $filter_order_Dir;
        $lists['order'] = $filter_order;
        // removed files
        $filelist = JRequest::getString('files');
        $file = JRequest::getInt('file');
        $filelist = explode(',', $filelist);
        $files = array();
        foreach ($filelist as $fileid) {
            if ($fileid && $fileid != $file) {
                $files[] = (int) $fileid;
            }
        }
        $files = implode(',', $files);
        if (strlen($files) > 0) {
            $files .= ',';
        }
        $files .= $file;
        //assign data to template
        $this->assignRef('params', $params);
        $this->assignRef('client', $client);
        //Load pane behavior
        if (!FLEXI_J16GE) {
            jimport('joomla.html.pane');
            $pane = JPane::getInstance('Tabs');
            $this->assignRef('pane', $pane);
        }
        $this->assignRef('lists', $lists);
        $this->assignRef('rows', $rows);
        $this->assignRef('folder_mode', $folder_mode);
        $this->assignRef('img_folder', $img_folder);
        $this->assignRef('thumb_w', $thumb_w);
        $this->assignRef('thumb_h', $thumb_h);
        $this->assignRef('pagination', $pagination);
        $this->assignRef('files', $files);
        $this->assignRef('fieldid', $fieldid);
        $this->assignRef('u_item_id', $u_item_id);
        $this->assignRef('targetid', $targetid);
        $this->assignRef('CanFiles', $perms->CanFiles);
        $this->assignRef('CanUpload', $perms->CanUpload);
        $this->assignRef('CanViewAllFiles', $perms->CanViewAllFiles);
        $this->assignRef('files_selected', $files_selected);
        $this->assignRef('langs', $langs);
        parent::display($tpl);
    }