/**
  * Method to get data of filters
  * 
  * @access public
  * @return object
  * @since 1.5
  */
 static function &getFilters($filt_param = 'filters', $usage_param = 'use_filters', &$params = null, $check_access = true)
 {
     // Parameter that controls using these filters
     $filters = array();
     if ($usage_param != '__ALL_FILTERS__' && $params && !$params->get($usage_param, 0)) {
         return $filters;
     }
     // Get Filter IDs, false means do retrieve any filter
     $filter_ids = $params ? $params->get($filt_param, array()) : array();
     if ($filter_ids === false) {
         return $filters;
     }
     // Check if array or comma separated list
     if (!is_array($filter_ids)) {
         $filter_ids = preg_split("/\\s*,\\s*/u", $filter_ids);
         if (empty($filter_ids[0])) {
             unset($filter_ids[0]);
         }
     }
     // Sanitize the given filter_ids ... just in case
     $filter_ids = array_filter($filter_ids, 'is_numeric');
     // array_flip to get unique filter ids as KEYS (due to flipping) ... and then array_keys to get filter_ids in 0,1,2, ... array
     $filter_ids = array_keys(array_flip($filter_ids));
     $user = JFactory::getUser();
     $db = JFactory::getDBO();
     // None selected filters means ALL
     $and_scope = $usage_param != '__ALL_FILTERS__' && count($filter_ids) ? ' AND fi.id IN (' . implode(',', $filter_ids) . ')' : '';
     // Use ACCESS Level, usually this is only for shown filters
     $and_access = '';
     if ($check_access) {
         if (FLEXI_J16GE) {
             $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
             $aid_list = implode(",", $aid_arr);
             $and_access = ' AND fi.access IN (0,' . $aid_list . ') ';
         } else {
             $aid = (int) $user->get('aid');
             if (FLEXI_ACCESS) {
                 $readperms = FAccess::checkUserElementsAccess($user->gmid, 'read');
                 if (isset($readperms['field']) && count($readperms['field'])) {
                     $and_access = ' AND ( fi.access <= ' . $aid . ' OR fi.id IN (' . implode(",", $readperms['field']) . ') )';
                 } else {
                     $and_access = ' AND fi.access <= ' . $aid;
                 }
             } else {
                 $and_access = ' AND fi.access <= ' . $aid;
             }
         }
     }
     // Create and execute SQL query for retrieving filters
     $query = 'SELECT fi.*' . ' FROM #__flexicontent_fields AS fi' . ' WHERE fi.published = 1' . ' AND fi.isfilter = 1' . $and_access . $and_scope . ' ORDER BY fi.ordering, fi.name';
     $db->setQuery($query);
     $filters = $db->loadObjectList('id');
     if (!$filters) {
         $filters = array();
         // need to do this because we return reference, but false here will also mean an error
         return $filters;
     }
     // Order filters according to given order
     $filters_tmp = array();
     if ($params->get('filters_order', 0) && !empty($filter_ids) && $usage_param != '__ALL_FILTERS__') {
         foreach ($filter_ids as $filter_id) {
             if (empty($filters[$filter_id])) {
                 continue;
             }
             $filter = $filters[$filter_id];
             $filters_tmp[$filter->name] = $filter;
         }
     } else {
         foreach ($filters as $filter) {
             $filters_tmp[$filter->name] = $filter;
         }
     }
     $filters = $filters_tmp;
     // Create filter parameters, language filter label, etc
     foreach ($filters as $filter) {
         $filter->parameters = FLEXI_J16GE ? new JRegistry($filter->attribs) : new JParameter($filter->attribs);
         $filter->label = JText::_($filter->label);
     }
     // Return found filters
     return $filters;
 }
Esempio n. 2
0
 static function getTags(&$params, &$module)
 {
     $mainframe = JFactory::getApplication();
     // Initialize
     $db = JFactory::getDBO();
     $user = JFactory::getUser();
     $nullDate = $db->getNullDate();
     $now = FLEXI_J16GE ? JFactory::getDate()->toSql() : JFactory::getDate()->toMySQL();
     $fparams = $mainframe->getParams('com_flexicontent');
     $show_noauth = $fparams->get('show_noauth', 0);
     // Get parameters
     $minsize = (int) $params->get('min_size', '1');
     $maxsize = (int) $params->get('max_size', '10');
     $limit = (int) $params->get('count', '25');
     $method = (int) $params->get('method', '1');
     $scope = $params->get('categories');
     $scope = is_array($scope) ? implode(',', $scope) : $scope;
     $tagitemid = (int) $params->get('force_itemid', 0);
     $where = !FLEXI_J16GE ? ' WHERE i.sectionid = ' . FLEXI_SECTION : ' WHERE 1 ';
     $where .= ' AND i.state IN ( 1, -5 )';
     $where .= ' AND ( i.publish_up = ' . $db->Quote($nullDate) . ' OR i.publish_up <= ' . $db->Quote($now) . ' )';
     $where .= ' AND ( i.publish_down = ' . $db->Quote($nullDate) . ' OR i.publish_down >= ' . $db->Quote($now) . ' )';
     $where .= ' AND c.published = 1';
     $where .= ' AND tag.published = 1';
     // filter by permissions
     if (!$show_noauth) {
         if (FLEXI_J16GE) {
             $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
             $aid_list = implode(",", $aid_arr);
             $where .= ' AND i.access IN (' . $aid_list . ')';
         } else {
             $aid = (int) $user->get('aid');
             if (FLEXI_ACCESS) {
                 $readperms = FAccess::checkUserElementsAccess($user->gmid, 'read');
             }
             if (!empty($readperms['item'])) {
                 $where .= ' AND ( i.access <= ' . $aid . ' OR i.id IN (' . implode(",", $readperms['item']) . ') )';
             } else {
                 $where .= ' AND i.access <= ' . $aid;
             }
         }
     }
     // category scope
     if ($method == 2) {
         // include method
         $where .= ' AND c.id NOT IN (' . $scope . ')';
     } else {
         if ($method == 3) {
             // exclude method
             $where .= ' AND c.id IN (' . $scope . ')';
         }
     }
     // count Tags
     $result = array();
     $query = 'SELECT COUNT( t.tid ) AS no' . ' FROM #__flexicontent_tags_item_relations AS t' . ' LEFT JOIN #__content AS i ON i.id = t.itemid' . ' LEFT JOIN #__categories AS c ON c.id = i.catid' . ' LEFT JOIN #__flexicontent_tags as tag ON tag.id = t.tid' . $where . ' GROUP BY t.tid' . ' ORDER BY no DESC';
     $db->setQuery($query, 0, $limit);
     $result = FLEXI_J30GE ? $db->loadColumn() : $db->loadResultArray();
     //Do we have any tags?
     if (!$result) {
         return $result;
     }
     $max = (int) $result[0];
     $min = (int) $result[sizeof($result) - 1];
     $query = 'SELECT tag.id, tag.name, count( rel.tid ) AS no,' . ' CASE WHEN CHAR_LENGTH(tag.alias) THEN CONCAT_WS(\':\', tag.id, tag.alias) ELSE tag.id END as slug' . ' FROM #__flexicontent_tags AS tag' . ' LEFT JOIN #__flexicontent_tags_item_relations AS rel ON rel.tid = tag.id' . ' LEFT JOIN #__content AS i ON i.id = rel.itemid' . ' LEFT JOIN #__categories AS c ON c.id = i.catid' . $where . ' GROUP BY tag.id' . ' HAVING no >= ' . $min . ' ORDER BY tag.name';
     $db->setQuery($query, 0, $limit);
     $rows = $db->loadObjectList();
     $i = 0;
     $lists = array();
     foreach ($rows as $row) {
         $lists[$i] = new stdClass();
         $lists[$i]->size = modFlexiTagCloudHelper::sizer($min, $max, $row->no, $minsize, $maxsize);
         $lists[$i]->name = $row->name;
         $lists[$i]->screenreader = JText::sprintf('FLEXI_NR_ITEMS_TAGGED', $row->no);
         if ($tagitemid) {
             $lists[$i]->link = FlexicontentHelperRoute::getTagRoute($row->slug, $tagitemid);
         } else {
             $lists[$i]->link = FlexicontentHelperRoute::getTagRoute($row->slug);
         }
         $lists[$i]->link = JRoute::_($lists[$i]->link . '&module=' . $module->id);
         $i++;
     }
     return $lists;
 }
Esempio n. 3
0
 function getItemList(&$field, &$item, &$ids = null, $cid = null, &$cparams = null)
 {
     // Global parameters
     $gparams = JFactory::getApplication()->getParams('com_flexicontent');
     $filtercat = $gparams->get('filtercat', 0);
     // If language filtering is enabled in category view
     $db = JFactory::getDBO();
     $user = JFactory::getUser();
     $date = JFactory::getDate();
     $nowDate = FLEXI_J16GE ? $date->toSql() : $date->toMySQL();
     $nullDate = $db->getNullDate();
     if ($ids === null) {
         $select = 'SELECT a.id';
         $join = '' . ' LEFT JOIN #__flexicontent_items_ext AS ie on ie.item_id = a.id' . ' JOIN #__flexicontent_cats_item_relations AS rel ON rel.itemid = a.id ';
         // Get the site default language in case no language is set in the url
         $cntLang = substr(JFactory::getLanguage()->getTag(), 0, 2);
         // Current Content language (Can be natively switched in J2.5)
         $urlLang = JRequest::getWord('lang', '');
         // Language from URL (Can be switched via Joomfish in J1.5)
         $lang = FLEXI_J16GE || empty($urlLang) ? $cntLang : $urlLang;
         // parameters shortcuts
         $types_to_exclude = $field->parameters->get('type_to_exclude', '');
         // filter depending on permissions
         if (FLEXI_J16GE) {
             $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
             $aid_list = implode(",", $aid_arr);
             $andaccess = ' AND a.access IN (' . $aid_list . ')';
         } else {
             $aid = (int) $user->get('aid');
             if (FLEXI_ACCESS) {
                 $readperms = FAccess::checkUserElementsAccess($user->gmid, 'read');
                 if (isset($readperms['item']) && count($readperms['item'])) {
                     $andaccess = ' AND ( ( a.access <= ' . $aid . ' OR a.id IN (' . implode(",", $readperms['item']) . ') OR a.created_by = ' . $user->id . ' OR ( a.modified_by = ' . $user->id . ' AND a.modified_by != 0 ) ) )';
                 } else {
                     $andaccess = ' AND ( a.access <= ' . $aid . ' OR a.created_by = ' . $user->id . ' OR ( a.modified_by = ' . $user->id . ' AND a.modified_by != 0 ) )';
                 }
             } else {
                 $andaccess = ' AND ( a.access <= ' . $aid . ' OR a.created_by = ' . $user->id . ' OR ( a.modified_by = ' . $user->id . ' AND a.modified_by != 0 ) )';
             }
         }
         // Determine sort order
         $order = $cparams->get('orderby', '');
         // TODO: finish using category ORDERING, now we ignore: commented, rated
         $orderby = '';
         $orderby_join = '';
         if ((int) $cparams->get('orderbycustomfieldid', 0) != 0) {
             if ($cparams->get('orderbycustomfieldint', 0) != 0) {
                 $int = ' + 0';
             } else {
                 $int = '';
             }
             $orderby = 'f.value' . $int . ' ' . $cparams->get('orderbycustomfielddir', 'ASC');
             $orderby_join = ' LEFT JOIN #__flexicontent_fields_item_relations AS f ON f.item_id = a.id AND f.field_id = ' . (int) $cparams->get('orderbycustomfieldid', 0);
         } else {
             switch ($order) {
                 case 'date':
                     $orderby = 'a.created';
                     break;
                 case 'rdate':
                     $orderby = 'a.created DESC';
                     break;
                 case 'modified':
                     $orderby = 'a.modified DESC';
                     break;
                 case 'alpha':
                     $orderby = 'a.title';
                     break;
                 case 'ralpha':
                     $orderby = 'a.title DESC';
                     break;
                 case 'author':
                     $orderby = 'u.name';
                     break;
                 case 'rauthor':
                     $orderby = 'u.name DESC';
                     break;
                 case 'hits':
                     $orderby = 'a.hits';
                     break;
                 case 'rhits':
                     $orderby = 'a.hits DESC';
                     break;
                 case 'order':
                     $orderby = 'rel.ordering';
                     break;
             }
             // Create JOIN for ordering items by a most rated
             if ($order == 'author' || $order == 'rauthor') {
                 $orderby_join = ' LEFT JOIN #__users AS u ON u.id = a.created_by';
             }
         }
         $orderby = $orderby ? $orderby . ', a.title' : 'a.title';
         $orderby = ' ORDER BY ' . $orderby;
         $types = is_array($types_to_exclude) ? implode(',', $types_to_exclude) : $types_to_exclude;
         $where = ' WHERE rel.catid = ' . $cid;
         $where .= ' AND ( a.state = 1 OR a.state = -5 )' . ' AND ( publish_up = ' . $db->Quote($nullDate) . ' OR publish_up <= ' . $db->Quote($nowDate) . ' )' . ' AND ( publish_down = ' . $db->Quote($nullDate) . ' OR publish_down >= ' . $db->Quote($nowDate) . ' )' . ($types_to_exclude ? ' AND ie.type_id NOT IN (' . $types . ')' : '');
         if ((FLEXI_FISH || FLEXI_J16GE) && $filtercat) {
             $where .= ' AND ( ie.language LIKE ' . $db->Quote($lang . '%') . (FLEXI_J16GE ? ' OR ie.language="*" ' : '') . ' ) ';
         }
     } else {
         $select = 'SELECT a.*, ie.*,' . ' CASE WHEN CHAR_LENGTH(a.alias) THEN CONCAT_WS(":", a.id, a.alias) ELSE a.id END as slug,' . ' CASE WHEN CHAR_LENGTH(cc.alias) THEN CONCAT_WS(":", cc.id, cc.alias) ELSE cc.id END as categoryslug';
         $join = ' LEFT JOIN #__flexicontent_items_ext AS ie on ie.item_id = a.id' . ' JOIN #__categories AS cc ON cc.id = ' . $cid;
         $orderby = '';
         $orderby_join = '';
         $where = ' WHERE a.id IN (' . implode(',', $ids) . ')';
         $andaccess = '';
     }
     // array of articles in same category correctly ordered
     $query = $select . ' FROM #__content AS a' . $join . $orderby_join . $where . $andaccess . $orderby;
     $db->setQuery($query);
     $list = $db->loadObjectList('id');
     if ($db->getErrorNum()) {
         JError::raiseWarning($db->getErrorNum(), $db->getErrorMsg() . "<br />" . $query . "<br />");
     }
     // this check needed if incorrect Itemid is given resulting in an incorrect result
     if (!is_array($list)) {
         $list = array();
     }
     return $list;
 }
	/**
	 * Creates the add button
	 *
	 * @param array $params
	 * @since 1.0
	 */
	static function addbutton(&$params, &$submit_cat = null, $menu_itemid = 0, $submit_text = '', $auto_relations = false, $ignore_unauthorized = false)
	{
		if ( !$params->get('show_addbutton', 1) || JRequest::getCmd('print') ) return;
		
		// Currently add button will appear to logged users only
		// ... unless unauthorized users are allowed
		$user	= JFactory::getUser();
		if ( !$user->id && $ignore_unauthorized < 2 ) return '';
		
		
		// IF not auto-relation given ... then check if current view / layout can use ADD button
		$view = JRequest::getVar('view');
		$layout = JRequest::getVar('layout', 'default');
		if ( !$auto_relations ) {
			if ( $view!='category' || $layout == 'author' ) return '';
		}
		
		
		// *********************************************************************
		// Check if user can ADD to (a) given category or to (b) at any category
		// *********************************************************************
		
		// (a) Given category
		if ( $submit_cat && $submit_cat->id )
		{
			if (FLEXI_J16GE) {
				$canAdd = $user->authorise('core.create', 'com_content.category.' . $submit_cat->id);
			} else if (FLEXI_ACCESS) {
				$canAdd = ($user->gid < 25) ? FAccess::checkAllContentAccess('com_content','submit','users', $user->gmid, 'category', $submit_cat->id) : 1;
			} else {
				$canAdd	= $user->authorize('com_content', 'add', 'content', 'all');
				//$canAdd = ($user->gid >= 19);  // At least J1.5 Author
			}
		}
		
		// (b) Any category (or to the CATEGORY IDS of given CATEGORY VIEW OBJECT)
		else
		{
			// Given CATEGORY VIEW OBJECT may limit to specific category ids
			if (FLEXI_J16GE) {
				$canAdd = $user->authorise('core.create', 'com_flexicontent');
			} else if ($user->gid >= 25) {
				$canAdd = 1;
			} else if (FLEXI_ACCESS) {
				$canAdd = FAccess::checkUserElementsAccess($user->gmid, 'submit');
				$canAdd = @$canAdd['content'] || @$canAdd['category'];
			} else {
				$canAdd	= $user->authorize('com_content', 'add', 'content', 'all');
			}
			
			if ($canAdd === NULL && $user->id) {
				// Perfomance concern (NULL for $canAdd) means SOFT DENY, also check for logged user
				// thus to avoid checking some/ALL categories for "create" privelege for unlogged users
				$specific_catids = $submit_cat ? @ $submit_cat->ids  :  false;
				if ($specific_catids && count($specific_catids) > 3) $specific_catids = false;
				$allowedcats = FlexicontentHelperPerm::getAllowedCats( $user, $actions_allowed=array('core.create'), $require_all=true, $check_published = true, $specific_catids, $find_first = true );
				$canAdd = count($allowedcats);
			}
		}
		
		if ( !$canAdd && !$ignore_unauthorized ) return '';
		
		
		// ******************************
		// Create submit button/icon text
		// ******************************
		
		if ($submit_text) {
			$submit_lbl = JText::_($submit_text);
		} else {
			$submit_lbl = JText::_( $submit_cat && $submit_cat->id  ?  'FLEXI_ADD_NEW_CONTENT_TO_CURR_CAT'  :  'FLEXI_ADD_NEW_CONTENT_TO_LIST' );
		}		
		
		
		// ***********
		// Create link
		// ***********
		
		// Add Itemid (if given) and do SEF URL routing it --before-- appending more variables, so that
		// ... menu item URL variables from given menu item ID will be appended if SEF URLs are OFF
		$link  = 'index.php?option=com_flexicontent';
		$link .= $menu_itemid  ? '&Itemid='.$menu_itemid  :  '&view='.FLEXI_ITEMVIEW.'&task=add';
		$link  = JRoute::_($link);
		
		// Add main category ID (if given)
		$link .= ($submit_cat && $submit_cat->id)  ?  '&maincat='.$submit_cat->id  :  '';
		
		// Append autorelate information to the URL (if given)
		if ($auto_relations) foreach ( $auto_relations as $auto_relation ) {
			$link .= '&autorelation_'.$auto_relation->fieldid.'='.$auto_relation->itemid;
		}
		
		
		// ***************************************
		// Finally create the submit icon / button
		// ***************************************
		
		$overlib = $submit_lbl;
		$text = JText::_( 'FLEXI_ADD' );
		
		$show_icons = 2; //$params->get('show_icons');
		if ( $show_icons && !$auto_relations ) {
			$attribs = '';
			$image = FLEXI_J16GE ?
				JHTML::image('components/com_flexicontent/assets/images/'.'plus-button.png', $submit_lbl, $attribs) :
				JHTML::_('image.site', 'plus-button.png', 'components/com_flexicontent/assets/images/', NULL, NULL, $submit_lbl, $attribs) ;
		} else {
			$image = '';
		}
		
		$tooltip_class = 'fc_addbutton';
		if ( $show_icons==1 && !$auto_relations ) {
			$caption = '';
			$tooltip_class .= ' editlinktip';
		} else {
			$caption = $text;
			$tooltip_class .=
				(FLEXI_J30GE ? ' btn btn-small' : ' fc_button fcsimple fcsmall')
				.($auto_relations ? ' btn-success' : '');
		}
		$tooltip_class .= FLEXI_J30GE ? ' hasTooltip' : ' hasTip';
		$tooltip_title = flexicontent_html::getToolTip($text, $overlib, 0);
		
		$output	= '<a href="'.$link.'" class="'.$tooltip_class.'" title="'.$tooltip_title.'">'.$image.$caption.'</a>';
		if (!$auto_relations) {
			$output	= JText::_( 'FLEXI_ICON_SEP' ) .$output. JText::_( 'FLEXI_ICON_SEP' );
		}
		
		return $output;
	}
Esempio n. 5
0
 function faccess_items_editable_where(&$where)
 {
     $canEdit = FAccess::checkUserElementsAccess($user->gmid, 'edit');
     $canEditOwn = FAccess::checkUserElementsAccess($user->gmid, 'editown');
     if (!@$canEdit['content']) {
         // first exclude the users allowed to edit all items
         if (@$canEditOwn['content']) {
             // custom rules for users allowed to edit all their own items
             $allown = array();
             $allown[] = ' i.created_by = ' . $user->id;
             if (isset($canEdit['category'])) {
                 if (count($canEdit['category'])) {
                     $allown[] = ' i.catid IN (' . implode(',', $canEdit['category']) . ')';
                 }
             }
             if (isset($canEdit['item'])) {
                 if (count($canEdit['item'])) {
                     $allown[] = ' i.id IN (' . implode(',', $canEdit['item']) . ')';
                 }
             }
             if (count($allown) > 0) {
                 $where[] = count($allown) > 1 ? ' (' . implode(' OR', $allown) . ')' : $allown[0];
             }
         } else {
             if (isset($canEditOwn['category']) && count($canEditOwn['category']) || isset($canEditOwn['item']) && count($canEditOwn['item'])) {
                 // standard rules for the other users
                 $allown = array();
                 if (isset($canEditOwn['category'])) {
                     if (count($canEditOwn['category'])) {
                         $allown[] = ' (i.catid IN (' . implode(',', $canEditOwn['category']) . ') AND i.created_by = ' . $user->id . ')';
                     }
                 }
                 if (isset($canEdit['category'])) {
                     if (count($canEdit['category'])) {
                         $allown[] = ' i.catid IN (' . implode(',', $canEdit['category']) . ')';
                     }
                 }
                 if (isset($canEdit['item'])) {
                     if (count($canEdit['item'])) {
                         $allown[] = ' i.id IN (' . implode(',', $canEdit['item']) . ')';
                     }
                 }
                 if (count($allown) > 0) {
                     $where[] = count($allown) > 1 ? ' (' . implode(' OR', $allown) . ')' : $allown[0];
                 }
             } else {
                 $jAp = JFactory::getApplication();
                 $jAp->enqueueMessage(JText::_('FLEXI_CANNOT_VIEW_EDIT_ANY_ITEMS'), 'notice');
                 $where[] = ' 0 ';
             }
         }
     }
 }
Esempio n. 6
0
	/**
	 * Logic to save an item
	 *
	 * @access public
	 * @return void
	 * @since 1.0
	 */
	function save()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );
		
		// Initialize variables
		$app     = JFactory::getApplication();
		$db      = JFactory::getDBO();
		$user    = JFactory::getUser();
		$menu    = $app->getMenu()->getActive();
		$config  = JFactory::getConfig();
		$session = JFactory::getSession();
		$task	   = JRequest::getVar('task');
		$model   = $this->getModel(FLEXI_ITEMVIEW);
		$isnew   = !$model->getId();
		$ctrl_task = FLEXI_J16GE ? 'task=items.' : 'controller=items&task=';
		
		$fc_params  = JComponentHelper::getParams( 'com_flexicontent' );
		$dolog      = $fc_params->get('print_logging_info');
		
		// Get the COMPONENT only parameters
		$comp_params = JComponentHelper::getComponent('com_flexicontent')->params;
		$params = FLEXI_J16GE ? clone ($comp_params) : new JParameter( $comp_params ); // clone( JComponentHelper::getParams('com_flexicontent') );
		
		// Merge the type parameters
		$tparams = $model->getTypeparams();
		$tparams = FLEXI_J16GE ? new JRegistry($tparams) : new JParameter($tparams);
		$params->merge($tparams);
		
		// Merge the menu parameters
		if ($menu) {
			$menu_params = FLEXI_J16GE ? $menu->params : new JParameter($menu->params);
			$params->merge($menu_params);
		}
		
		// Get needed parameters
		$submit_redirect_url_fe = $params->get('submit_redirect_url_fe', '');
		$allowunauthorize       = $params->get('allowunauthorize', 0);
		
		
		
		// *********************
		// Get data from request
		// *********************
		
		if (FLEXI_J16GE) {
			// Retrieve form data these are subject to basic filtering
			$data   = JRequest::getVar('jform', array(), 'post', 'array');   // Core Fields and and item Parameters
			$custom = JRequest::getVar('custom', array(), 'post', 'array');  // Custom Fields
			$jfdata = JRequest::getVar('jfdata', array(), 'post', 'array');  // Joomfish Data
			if ( ! @ $data['rules'] ) $data['rules'] = array();
		}
		
		else {
			// Retrieve form data these are subject to basic filtering
			$data = JRequest::get( 'post' );  // Core & Custom Fields and item Parameters
		}
		
		// Set data id into model in case not already set ?
		$model->setId((int) $data['id']);
		
		
		
		// *************************************
		// ENFORCE can change category ACL perms
		// *************************************
		
		$perms = FlexicontentHelperPerm::getPerm();
		// Per content type change category permissions
		if (FLEXI_J16GE) {
			$current_type_id  = ($isnew || !$model->get('type_id')) ? $data['type_id'] : $model->get('type_id');  // GET current (existing/old) item TYPE ID
			$CanChangeFeatCat = $user->authorise('flexicontent.change.cat.feat', 'com_flexicontent.type.' . $current_type_id);
			$CanChangeSecCat  = $user->authorise('flexicontent.change.cat.sec', 'com_flexicontent.type.' . $current_type_id);
			$CanChangeCat     = $user->authorise('flexicontent.change.cat', 'com_flexicontent.type.' . $current_type_id);
		} else {
			$CanChangeFeatCat = 1;
			$CanChangeSecCat  = 1;
			$CanChangeCat     = 1;
		}
		
		$featured_cats_parent = $params->get('featured_cats_parent', 0);
		$featured_cats = array();
		
		$enable_featured_cid_selector = $perms->MultiCat && $CanChangeFeatCat;
		$enable_cid_selector   = $perms->MultiCat && $CanChangeSecCat;
		$enable_catid_selector = ($isnew && !$tparams->get('catid_default')) || (!$isnew && !$model->get('catid')) || $CanChangeCat;
		
		// Enforce maintaining featured categories
		$featured_cats_parent = $params->get('featured_cats_parent', 0);
		$featured_cats = array();
		if ( $featured_cats_parent && !$enable_featured_cid_selector )
		{
			$featured_tree = flexicontent_cats::getCategoriesTree($published_only=1, $parent_id=$featured_cats_parent, $depth_limit=0);
			$featured_cid = array();
			if (!$isnew) {
				foreach($model->get('categories') as $item_cat) if (isset($featured_tree[$item_cat])) $featured_cid[] = $item_cat;
			}
			$data['featured_cid'] = $featured_cid;
		}
		
		// Enforce maintaining secondary categories
		if (!$enable_cid_selector) {
			if ($isnew) {
				$data['cid'] = $tparams->get('cid_default');
			} else if ( isset($featured_cid) ) {
				$featured_cid_arr = array_flip($featured_cid);
				$sec_cid = array();
				foreach($model->get('cats') as $item_cat) if (!isset($featured_cid_arr[$item_cat])) $sec_cid[] = $item_cat;
				$data['cid'] = $sec_cid;
			} else {
				$data['cid'] = $model->get('cats');
			}
		}
		
		if (!$enable_catid_selector) {
			if ($isnew && $tparams->get('catid_default'))
				$data['catid'] = $tparams->get('catid_default');
			else if ($model->get('catid'))
				$data['catid'] = $model->get('catid');
		}
		
		
		
		// **************************
		// Basic Form data validation
		// **************************
		
		if (FLEXI_J16GE)
		{
			// *** MANUALLY CHECK CAPTCHA ***
			$use_captcha    = $params->get('use_captcha', 1);     // 1 for guests, 2 for any user
			$captcha_formop = $params->get('captcha_formop', 0);  // 0 for submit, 1 for submit/edit (aka always)
			$is_submitop = ((int) $data['id']) == 0;
			$display_captcha = $use_captcha >= 2 || ( $use_captcha == 1 &&  $user->guest );
			$display_captcha = $display_captcha && ( $is_submitop || $captcha_formop);  // for submit operation we do not need to check 'captcha_formop' ...
			if ($display_captcha)
			{
				// Try to force the use of recaptcha plugin
				JFactory::getConfig()->set('captcha', 'recaptcha');
				
				if ( $app->getCfg('captcha') == 'recaptcha' && JPluginHelper::isEnabled('captcha', 'recaptcha') ) {
					JPluginHelper::importPlugin('captcha');
					$dispatcher = JDispatcher::getInstance();
					$result = $dispatcher->trigger('onCheckAnswer', JRequest::getString('recaptcha_response_field'));
					if (!$result[0]) {
						$errmsg  = JText::_('FLEXI_CAPTCHA_FAILED');
						$errmsg .= ' '.JText::_('FLEXI_MUST_REFILL_SOME_FIELDS');
						echo "<script>alert('".$errmsg."');";
						echo "window.history.back();";
						echo "</script>";
						jexit();
					}
				}
			}
			
			// Validate Form data for core fields and for parameters
			$form = $model->getForm();          // Do not pass any data we only want the form object in order to validate the data and not create a filled-in form
			$post = $model->validate($form, $data);
			
			// Check for validation error
			if (!$post) {
				// Get the validation messages.
				$errors	= $form->getErrors();
	
				// Push up to three validation messages out to the user.
				for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
					if ($errors[$i] instanceof Exception)
						$app->enqueueMessage($errors[$i]->getMessage(), 'notice');
					else
						$app->enqueueMessage($errors[$i], 'notice');
				}
	
				// Save the jform data in the session.
				$app->setUserState($form->option.'.edit.'.$form->context.'.data', $data);
				// Save the custom fields data in the session.
				$app->setUserState($form->option.'.edit.'.$form->context.'.custom', $custom);
				
				// Redirect back to the registration form.
				$this->setRedirect( $_SERVER['HTTP_REFERER'] );
				return false;
				//die('error');
			}
			
			/*if (!$post) {
				//JError::raiseWarning( 500, "Error while validating data: " . $model->getError() );
				echo "Error while validating data: " . $model->getError();
				echo '<span class="fc_return_msg">'.JText::sprintf('FLEXI_CLICK_HERE_TO_RETURN', '"JavaScript:window.history.back();"').'</span>';
				jexit();
			}*/
			
			// Some values need to be assigned after validation
			$post['attribs'] = @$data['attribs'];  // Workaround for item's template parameters being clear by validation since they are not present in item.xml
			$post['custom']  = & $custom;          // Assign array of custom field values, they are in the 'custom' form array instead of jform
			$post['jfdata']  = & $jfdata;          // Assign array of Joomfish field values, they are in the 'jfdata' form array instead of jform
			
			// Assign template parameters of the select ilayout as an sub-array (the DB model will handle the merging of parameters)
			$ilayout = @ $data['attribs']['ilayout'];  // normal not be set if frontend template editing is not shown
			if( $ilayout && !empty($data['layouts'][$ilayout]) )   $post['attribs']['layouts'] = $data['layouts'];
			//echo "<pre>"; print_r($post['attribs']); exit;
		}
		
		else {
			$post = $data;
			
			// Some values need to be assigned after validation
			$post['text'] = JRequest::getVar( 'text', '', 'post', 'string', JREQUEST_ALLOWRAW ); // Workaround for allowing raw text field
			
			// Assign template parameters of the select ilayout as an sub-array (the DB model will handle the merging of parameters)
			$ilayout = @ $post['params']['ilayout'];  // normal not be set if frontend template editing is not shown
			if( $ilayout && !empty($post['layouts'][$ilayout]) )  $post['params']['layouts'] = $post['layouts'];
			//echo "<pre>"; print_r($post['params']); exit;
			
		}
		
		// USEFULL FOR DEBUGING for J2.5 (do not remove commented code)
		//$diff_arr = array_diff_assoc ( $data, $post);
		//echo "<pre>"; print_r($diff_arr); jexit();
		
		
		// ********************************************************************************
		// PERFORM ACCESS CHECKS, NOTE: we need to check access again, despite having
		// checked them on edit form load, because user may have tampered with the form ... 
		// ********************************************************************************
		
		$type_id = (int) @ $post['type_id'];  // Typecast to int, (already done for J2.5 via validating)
		if ( !$isnew && $model->get('type_id') == $type_id ) {
			// Existing item with Type not being ALTERED, content type can be maintained regardless of privilege
			$canCreateType = true;
		} else {
			// New item or existing item with Type is being ALTERED, check privilege to create items of this type
			$canCreateType = $model->canCreateType( array($type_id), true, $types );
		}
		
		
		// ****************************************************************
		// Calculate user's privileges on current content item
		// ... canPublish IS RECALCULATED after saving, maybe comment out ?
		// ****************************************************************
		
		if (!$isnew) {
			
			if (FLEXI_J16GE) {
				$asset = 'com_content.article.' . $model->get('id');
				$canPublish = $user->authorise('core.edit.state', $asset) || ($user->authorise('core.edit.state.own', $asset) && $model->get('created_by') == $user->get('id'));
				$canEdit = $user->authorise('core.edit', $asset) || ($user->authorise('core.edit.own', $asset) && $model->get('created_by') == $user->get('id'));
				// ALTERNATIVE 1
				//$canEdit = $model->getItemAccess()->get('access-edit'); // includes privileges edit and edit-own
				// ALTERNATIVE 2
				//$rights = FlexicontentHelperPerm::checkAllItemAccess($user->get('id'), 'item', $model->get('id'));
				//$canEdit = in_array('edit', $rights) || (in_array('edit.own', $rights) && $model->get('created_by') == $user->get('id')) ;
			} else if ($user->gid >= 25) {
				$canPublish = true;
				$canEdit = true;
			} else if (FLEXI_ACCESS) {
				$rights 	= FAccess::checkAllItemAccess('com_content', 'users', $user->gmid, $model->get('id'), $model->get('catid'));
				$canPublish = in_array('publish', $rights) || (in_array('publishown', $rights) && $model->get('created_by') == $user->get('id')) ;
				$canEdit = in_array('edit', $rights) || (in_array('editown', $rights) && $model->get('created_by') == $user->get('id')) ;
			} else {
				$canPublish = $user->authorize('com_content', 'publish', 'content', 'all');
				$canEdit = $user->authorize('com_content', 'edit', 'content', 'all') || ($user->authorize('com_content', 'edit', 'content', 'own') && $model->get('created_by') == $user->get('id'));
				//$canPublish = ($user->gid >= 21);  // At least J1.5 Publisher
				//$canEdit = ($user->gid >= 20);  // At least J1.5 Editor
			}
			
			if ( !$canEdit ) {
				// No edit privilege, check if item is editable till logoff
				if ($session->has('rendered_uneditable', 'flexicontent')) {
					$rendered_uneditable = $session->get('rendered_uneditable', array(),'flexicontent');
					$canEdit = isset($rendered_uneditable[$model->get('id')]) && $rendered_uneditable[$model->get('id')];
				}
			}

		} else {
			
			if (FLEXI_J16GE) {
				$canAdd = $model->getItemAccess()->get('access-create'); // includes check of creating in at least one category
				$not_authorised = !$canAdd;
				
				$canPublish	= $user->authorise('core.edit.state', 'com_flexicontent') || $user->authorise('core.edit.state.own', 'com_flexicontent');
			} else if ($user->gid >= 25) {
				$canAdd = 1;
			} else if (FLEXI_ACCESS) {
				$canAdd = FAccess::checkUserElementsAccess($user->gmid, 'submit');
				$canAdd = @$canAdd['content'] || @$canAdd['category'];
				
				$canPublishAll 		= FAccess::checkAllContentAccess('com_content','publish','users',$user->gmid,'content','all');
				$canPublishOwnAll	= FAccess::checkAllContentAccess('com_content','publishown','users',$user->gmid,'content','all');
				$canPublish	= ($user->gid < 25) ? $canPublishAll || $canPublishOwnAll : 1;
			} else {
				$canAdd	= $user->authorize('com_content', 'add', 'content', 'all');
				//$canAdd = ($user->gid >= 19);  // At least J1.5 Author
				$not_authorised = ! $canAdd;
				$canPublish	= ($user->gid >= 21);
			}
			
			if ( $allowunauthorize ) {
				$canAdd = true;
				$canCreateType = true;
			}
		}
		
		// ... we use some strings from administrator part
		// load english language file for 'com_flexicontent' component then override with current language file
		JFactory::getLanguage()->load('com_flexicontent', JPATH_ADMINISTRATOR, 'en-GB', true);
		JFactory::getLanguage()->load('com_flexicontent', JPATH_ADMINISTRATOR, null, true);
		
		// Check for new content
		if ( ($isnew && !$canAdd) || (!$isnew && !$canEdit)) {
			$msg = JText::_( 'FLEXI_ALERTNOTAUTH' );
			if (FLEXI_J16GE) throw new Exception($msg, 403); else JError::raiseError(403, $msg);
		}
		
		if ( !$canCreateType ) {
			$msg = isset($types[$type_id]) ?
				JText::sprintf( 'FLEXI_NO_ACCESS_CREATE_CONTENT_OF_TYPE', JText::_($types[$type_id]->name) ) :
				' Content Type '.$type_id.' was not found OR is not published';
			if (FLEXI_J16GE) throw new Exception($msg, 403); else JError::raiseError(403, $msg);
			return;
		}
		
		// Get "BEFORE SAVE" categories for information mail
		$before_cats = array();
		if ( !$isnew )
		{
			$query 	= 'SELECT DISTINCT c.id, c.title FROM #__categories AS c'
				. ' JOIN #__flexicontent_cats_item_relations AS rel ON rel.catid = c.id'
				. ' WHERE rel.itemid = '.(int) $model->get('id');
			$db->setQuery( $query );
			$before_cats = $db->loadObjectList('id');
			$before_maincat = $model->get('catid');
			$original_item = $model->getItem($post['id'], $check_view_access=false, $no_cache=true, $force_version=0);
		}
		
		
		// ****************************************
		// Try to store the form data into the item
		// ****************************************
		if ( ! $model->store($post) )
		{
			// Set error message about saving failed, and also the reason (=model's error message)
			$msg = JText::_( 'FLEXI_ERROR_STORING_ITEM' );
			JError::raiseWarning( 500, $msg .": " . $model->getError() );

			// Since an error occured, check if (a) the item is new and (b) was not created
			if ($isnew && !$model->get('id')) {
				$msg = '';
				$link = 'index.php?option=com_flexicontent&'.$ctrl_task.'add&id=0&typeid='.$type_id.'&'. (FLEXI_J30GE ? JSession::getFormToken() : JUtility::getToken()) .'=1';
				$this->setRedirect($link, $msg);
			} else {
				$msg = '';
				$link = 'index.php?option=com_flexicontent&'.$ctrl_task.'edit&id='.$model->get('id').'&'. (FLEXI_J30GE ? JSession::getFormToken() : JUtility::getToken()) .'=1';
				$this->setRedirect($link, $msg);
			}
			
			// Saving has failed check-in and return, (above redirection will be used)
			$model->checkin();
			return;
		}
		
		
		// **************************************************
		// Check in model and get item id in case of new item
		// **************************************************
		$model->checkin();
		$post['id'] = $isnew ? (int) $model->get('id') : $post['id'];
		
		// Get items marked as newly submitted
		$newly_submitted = $session->get('newly_submitted', array(), 'flexicontent');
		if ($isnew) {
			// Mark item as newly submitted, to allow to a proper "THANKS" message after final save & close operation (since user may have clicked add instead of add & close)
			$newly_submitted[$model->get('id')] = 1;
			$session->set('newly_submitted', $newly_submitted, 'flexicontent');
		}
		$newly_submitted_item = @ $newly_submitted[$model->get('id')];
		
		
		// ***********************************************************************************************************
		// Get newly saved -latest- version (store task gets latest) of the item, and also calculate publish privelege
		// ***********************************************************************************************************
		$item = $model->getItem($post['id'], $check_view_access=false, $no_cache=true, $force_version=-1);
		$canPublish = $model->canEditState( $item, $check_cat_perm=true );
		
		
		// ********************************************************************************************
		// Use session to detect multiple item saves to avoid sending notification EMAIL multiple times
		// ********************************************************************************************
		$is_first_save = true;
		if ($session->has('saved_fcitems', 'flexicontent')) {
			$saved_fcitems = $session->get('saved_fcitems', array(), 'flexicontent');
			$is_first_save = $isnew ? true : !isset($saved_fcitems[$model->get('id')]);
		}
		// Add item to saved items of the corresponding session array
		$saved_fcitems[$model->get('id')] = $timestamp = time();  // Current time as seconds since Unix epoc;
		$session->set('saved_fcitems', $saved_fcitems, 'flexicontent');
		
		
		// ********************************************
		// Get categories added / removed from the item
		// ********************************************
		$query 	= 'SELECT DISTINCT c.id, c.title FROM #__categories AS c'
			. ' JOIN #__flexicontent_cats_item_relations AS rel ON rel.catid = c.id'
			. ' WHERE rel.itemid = '.(int) $model->get('id');
		$db->setQuery( $query );
		$after_cats = $db->loadObjectList('id');
		if ( !$isnew ) {
			$cats_added_ids = array_diff(array_keys($after_cats), array_keys($before_cats));
			foreach($cats_added_ids as $cats_added_id) {
				$cats_added_titles[] = $after_cats[$cats_added_id]->title;
			}
			
			$cats_removed_ids = array_diff(array_keys($before_cats), array_keys($after_cats));
			foreach($cats_removed_ids as $cats_removed_id) {
				$cats_removed_titles[] = $before_cats[$cats_removed_id]->title;
			}
			$cats_altered = count($cats_added_ids) + count($cats_removed_ids);
			$after_maincat = $model->get('catid');
		}
		
		
		// *******************************************************************************************************************
		// We need to get emails to notify, from Global/item's Content Type parameters -AND- from item's categories parameters
		// *******************************************************************************************************************
		$notify_emails = array();
		if ( $is_first_save || $cats_altered || $params->get('nf_enable_debug',0) )
		{
			// Get needed flags regarding the saved items
			$approve_version = 2;
			$pending_approval_state = -3;
			$draft_state = -4;
			
			$current_version = FLEXIUtilities::getCurrentVersions($item->id, true); // Get current item version
			$last_version    = FLEXIUtilities::getLastVersions($item->id, true);    // Get last version (=latest one saved, highest version id),
			
			// $post variables vstate & state may have been (a) tampered in the form, and/or (b) altered by save procedure so better not use them
			$needs_version_reviewal     = !$isnew && ($last_version > $current_version) && !$canPublish;
			$needs_publication_approval =  $isnew && ($item->state == $pending_approval_state) && !$canPublish;
			
			$draft_from_non_publisher = $item->state==$draft_state && !$canPublish;
			
			if ($draft_from_non_publisher) {
				// Suppress notifications for draft-state items (new or existing ones), for these each author will publication approval manually via a button
				$nConf = false;
			} else {
				// Get notifications configuration and select appropriate emails for current saving case
				$nConf = $model->getNotificationsConf($params);  //echo "<pre>"; print_r($nConf); "</pre>";
			}
			
			if ($nConf)
			{
				$states_notify_new = $params->get('states_notify_new', array(1,0,(FLEXI_J16GE ? 2:-1),-3,-4,-5));
				if ( empty($states_notify_new) )						$states_notify_new = array();
				else if ( ! is_array($states_notify_new) )	$states_notify_new = !FLEXI_J16GE ? array($states_notify_new) : explode("|", $states_notify_new);
				
				$states_notify_existing = $params->get('states_notify_existing', array(1,0,(FLEXI_J16GE ? 2:-1),-3,-4,-5));
				if ( empty($states_notify_existing) )						$states_notify_existing = array();
				else if ( ! is_array($states_notify_existing) )	$states_notify_existing = !FLEXI_J16GE ? array($states_notify_existing) : explode("|", $states_notify_existing);

				$n_state_ok = in_array($item->state, $states_notify_new);
				$e_state_ok = in_array($item->state, $states_notify_existing);
				
				if ($needs_publication_approval)   $notify_emails = $nConf->emails->notify_new_pending;
				else if ($isnew && $n_state_ok)    $notify_emails = $nConf->emails->notify_new;
				else if ($isnew)                   $notify_emails = array();
				else if ($needs_version_reviewal)  $notify_emails = $nConf->emails->notify_existing_reviewal;
				else if (!$isnew && $e_state_ok)   $notify_emails = $nConf->emails->notify_existing;
				else if (!$isnew)                  $notify_emails = array();
				
				if ($needs_publication_approval)   $notify_text = $params->get('text_notify_new_pending');
				else if ($isnew)                   $notify_text = $params->get('text_notify_new');
				else if ($needs_version_reviewal)  $notify_text = $params->get('text_notify_existing_reviewal');
				else if (!$isnew)                  $notify_text = $params->get('text_notify_existing');
				//print_r($notify_emails); jexit();
			}
		}
		
		
		// *********************************************************************************************************************
		// If there are emails to notify for current saving case, then send the notifications emails, but 
		// *********************************************************************************************************************
		if ( !empty($notify_emails) && count($notify_emails) ) {
			$notify_vars = new stdClass();
			$notify_vars->needs_version_reviewal     = $needs_version_reviewal;
			$notify_vars->needs_publication_approval = $needs_publication_approval;
			$notify_vars->isnew         = $isnew;
			$notify_vars->notify_emails = $notify_emails;
			$notify_vars->notify_text   = $notify_text;
			$notify_vars->before_cats   = $before_cats;
			$notify_vars->after_cats    = $after_cats;
			$notify_vars->original_item = @ $original_item;
			
			$model->sendNotificationEmails($notify_vars, $params, $manual_approval_request=0);
		}
		
		
		// ***************************************************
		// CLEAN THE CACHE so that our changes appear realtime
		// ***************************************************
		if (FLEXI_J16GE) {
			$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');
		} else {
			$itemcache = JFactory::getCache('com_flexicontent_items');
			$itemcache->clean();
			$filtercache = JFactory::getCache('com_flexicontent_filters');
			$filtercache->clean();
		}
		
		
		// ****************************************************************************************************************************
		// Recalculate EDIT PRIVILEGE of new item. Reason for needing to do this is because we can have create permission in a category
		// and thus being able to set this category as item's main category, but then have no edit/editown permission for this category
		// ****************************************************************************************************************************
		if (FLEXI_J16GE) {
			$asset = 'com_content.article.' . $model->get('id');
			$canEdit = $user->authorise('core.edit', $asset) || ($user->authorise('core.edit.own', $asset) && $model->get('created_by') == $user->get('id'));
			// ALTERNATIVE 1
			//$canEdit = $model->getItemAccess()->get('access-edit'); // includes privileges edit and edit-own
			// ALTERNATIVE 2
			//$rights = FlexicontentHelperPerm::checkAllItemAccess($user->get('id'), 'item', $model->get('id'));
			//$canEdit = in_array('edit', $rights) || (in_array('edit.own', $rights) && $model->get('created_by') == $user->get('id')) ;
		} else if (FLEXI_ACCESS && $user->gid < 25) {
			$rights 	= FAccess::checkAllItemAccess('com_content', 'users', $user->gmid, $model->get('id'), $model->get('catid'));
			$canEdit = in_array('edit', $rights) || (in_array('editown', $rights) && $model->get('created_by') == $user->get('id')) ;
		} else {
			// This is meaningful when executed in frontend, since all backend users (managers and above) can edit items
			$canEdit = $user->authorize('com_content', 'edit', 'content', 'all') || ($user->authorize('com_content', 'edit', 'content', 'own') && $model->get('created_by') == $user->get('id'));
		}
		
		
		// *******************************************************************************************************
		// Check if user can not edit item further (due to changed main category, without edit/editown permission)
		// *******************************************************************************************************
		if (!$canEdit)
		{
			if ($task=='apply') {
				// APPLY TASK: Temporarily set item to be editable till closing it
				$rendered_uneditable = $session->get('rendered_uneditable', array(),'flexicontent');
				$rendered_uneditable[$model->get('id')]  = 1;
				$session->set('rendered_uneditable', $rendered_uneditable, 'flexicontent');
				$canEdit = 1;
			}
			
			else if ( $newly_submitted_item ) {
				// NEW ITEM: Do not use editable till logoff behaviour
				// ALSO: Clear editable FLAG set in the case that 'apply' button was used during new item creation
				if ( !$params->get('items_session_editable', 0) ) {
					$rendered_uneditable = $session->get('rendered_uneditable', array(),'flexicontent');
					if ( isset($rendered_uneditable[$model->get('id')]) ) {
						unset( $rendered_uneditable[$model->get('id')] );
						$session->set('rendered_uneditable', $rendered_uneditable, 'flexicontent');
					}
				}
			}
			
			else {
				// EXISTING ITEM: (if enabled) Use the editable till logoff behaviour
				if ( $params->get('items_session_editable', 0) ) {
					
					// Set notice for existing item being editable till logoff 
					JError::raiseNotice( 403, JText::_( 'FLEXI_CANNOT_EDIT_AFTER_LOGOFF' ) );
					
					// Allow item to be editable till logoff
					$rendered_uneditable = $session->get('rendered_uneditable', array(),'flexicontent');
					$rendered_uneditable[$model->get('id')]  = 1;
					$session->set('rendered_uneditable', $rendered_uneditable, 'flexicontent');
					$canEdit = 1;
				}
			}
			
			// Set notice about saving an item that cannot be changed further
			if ( !$canEdit ) {
				$app->enqueueMessage(JText::_( 'FLEXI_CANNOT_MAKE_FURTHER_CHANGES_TO_CONTENT' ), 'message' );
			}
		}
		
		
		// ****************************************************************
		// Check for new Content Item is being closed, and clear some flags
		// ****************************************************************
		
		if ($task!='apply' && $newly_submitted_item )
		{
			// Clear item from being marked as newly submitted
			unset($newly_submitted[$model->get('id')]);
			$session->set('newly_submitted', $newly_submitted, 'flexicontent');
			
			// The 'apply' task may set 'editable till logoff' FLAG ...
			// CLEAR IT, since NEW content this is meant to be used temporarily
			if ( !$params->get('items_session_editable', 0) ) {
				$rendered_uneditable = $session->get('rendered_uneditable', array(),'flexicontent');
				if ( isset($rendered_uneditable[$model->get('id')]) ) {
					unset( $rendered_uneditable[$model->get('id')] );
					$session->set('rendered_uneditable', $rendered_uneditable, 'flexicontent');
				}
			}
		}
		
		
		// ****************************************
		// Saving is done, decide where to redirect
		// ****************************************
		
		// REDIRECT CASE FOR APPLYING: Save and reload the item edit form
		if ($task=='apply') {
			$msg = JText::_( 'FLEXI_ITEM_SAVED' );
			
			// Create the URL
			global $globalcats;
			$Itemid = JRequest::getInt('Itemid', 0);  // maintain current menu item if this was given
			$item_url = JRoute::_(FlexicontentHelperRoute::getItemRoute($item->id.':'.$item->alias, $globalcats[$item->catid]->slug, $Itemid));
			$link = $item_url
				.(strstr($item_url, '?') ? '&' : '?').'task=edit'
				;
			
			// Important pass referer back to avoid making the form itself the referer
			// but also check that referer URL is 'safe' (allowed) , e.g. not an offsite URL, otherwise set referer to HOME page
			$referer = JRequest::getString('referer', JURI::base(), 'post');
			if ( ! flexicontent_html::is_safe_url($referer) ) $referer = JURI::base();
			$return = '&return='.base64_encode( $referer );
			$link .= $return;
		}
		
		// REDIRECT CASES FOR SAVING
		else {
			
			// REDIRECT CASE: Return to a custom page after creating a new item (e.g. a thanks page)
			if ( $newly_submitted_item && $submit_redirect_url_fe ) {
				$link = $submit_redirect_url_fe;
				$msg = JText::_( 'FLEXI_ITEM_SAVED' );
			}
			// REDIRECT CASE: Save and preview the latest version
			else if ($task=='save_a_preview') {
				$msg = JText::_( 'FLEXI_ITEM_SAVED' );
				$link = JRoute::_(FlexicontentHelperRoute::getItemRoute($model->_item->id.':'.$model->_item->alias, $model->_item->catid, 0, $model->_item).'&preview=1', false);
			}
			// REDIRECT CASE: Return to the form 's referer (previous page) after item saving
			else {
				$msg = $newly_submitted_item ? JText::_( 'FLEXI_THANKS_SUBMISSION' ) : JText::_( 'FLEXI_ITEM_SAVED' );
				
				// Check that referer URL is 'safe' (allowed) , e.g. not an offsite URL, otherwise for returning to HOME page
				$link = JRequest::getString('referer', JURI::base(), 'post');
				if ( ! flexicontent_html::is_safe_url($link) ) {
					if ( $dolog ) JFactory::getApplication()->enqueueMessage( 'refused redirection to possible unsafe URL: '.$link, 'notice' );
					$link = JURI::base();
				}
			}
		}
		
		$this->setRedirect($link, $msg);
	}
Esempio n. 7
0
        function save_import()
	{
		// Check for request forgeries
		//JRequest::checkToken() or jexit( 'Invalid Token' );
		
		
		
                //mara
                
                $arr_countries = array('AL' => 'Albania',
 'AM' => 'Armenia' ,
 'ARG' =>'Argentina' ,
 'AU' => 'Australia' ,
 'AUT' => 'Austria' ,
 'AZ' =>'Azerbaidjan' ,
 'BEL' => 'Belgium' ,
 'BGD' => 'Bangladesh' ,
 'BLG' => 'Bulgaria' ,
 'BLR' => 'Belarus' ,
 'BOS' => 'Bosnia-Herzegovina' ,
 'BRA' => 'Brazil' ,
 'CAN' => 'Canada' ,
 'CB' => 'Cuba' ,
 'CHE' => 'Switzerland' ,
 'CHI' => 'China' ,
 'CHL' => 'Chile' ,
 'CS' => 'Czech Republic' ,
 'DEU' => 'Germany' ,
 'DNK' => 'Denmark' ,
 'EGP' => 'Egypt' ,
 'EST' => 'Estonia' ,
 'FIN' => 'Finland' ,
 'FRA' => 'France' ,
 'GBR' => 'Great Britain' ,
 'GBRUSA' => 'Great Britain' ,
 'GEO' => 'Georgia' ,
 'GR' => 'Greece' ,
 'HK' => 'Hong Kong' ,
 'HOR' => 'Croatia' ,
 'HUN' => 'Hungary' ,
 'IDZ' => 'Indonesia' ,
 'IND' => 'India' ,
 'IOR' => 'Jordan' ,
 'IRA' => 'Iran' ,
 'IRL' => 'Ireland' ,
 'ISL' => 'Iceland' ,
 'ISR' => 'Israel' ,
 'ITA' => 'Italy' ,
 'JPN' => 'Japan' ,
 'KAZ' => 'Kazakhstan' ,
 'KGZ' => 'Kyrgyzstan' ,
 'KIP' => 'Cyprus' ,
 'LAT' => 'Latvia' ,
 'LIT' => 'Lithuania' ,
 'LUX' => 'Luxembourg' ,
 'MAK' => 'Macedonia' ,
 'ME' => 'Montenegro' ,
 'MEK' => 'Mexico' ,
 'MLT' => 'Malta' ,
 'MOL' => 'Moldavia' ,
 'MON' => 'Monaco' ,
 'NID' => 'Netherlands' ,
 'NOR' => 'Norway' ,
 'PAK' => 'Pakistan' ,
 'POL' => 'Poland' ,
 'PORT' => 'Portugal' ,
 'PR' => 'Puerto Rico' ,
 'PS' => 'Palestinian Territory' ,
 'RS' => 'Serbia' ,
 'RUM' => 'Romania' ,
 'RUS' => 'Russian Federation' ,
 'SA' => 'Saudi Arabia' ,
 'SCH' => 'Serbia' ,
 'SGP' => 'Singapore' ,
 'SHE' => 'Switzerland' ,
 'SKO' => 'South Korea' ,
 'SLO' => 'Slovenia' ,
 'SLR' => 'Slovak Republic' ,
 'SM' => 'San Marino' ,
 'SPN' => 'Spain' ,
 'SWE' => 'Sweden' ,
 'SYR' => 'Syria' ,
 'TA' => 'Thailand' ,
 'TUR' => 'Turkey' ,
 'UAR' => 'South Africa' ,
 'UGS' => 'Serbia' ,
 'UKR' => 'Ukraine' ,
 'unk' => 'Unknown' ,
 'USA' => 'United States' ,
 'USAFRA' => 'United States' ,
 'Uzb' => 'Uzbekistan' ,
 'VTN' => 'Vietnam');
                
                
		mysql_connect('localhost', 'root', 'staSPE8e');
                mysql_select_db('vidal');
                mysql_query("SET NAMES utf8");
                $query = "SELECT pa.ATCCode,m.LatName,n.NozologyCode,Document.DocumentID,"
                        ."Document.RusName,Document.EngName,Document.CompiledComposition,Document.PhInfluence,Document.PhKinetics,"
                        ."Document.Dosage,Document.OverDosage,Document.Interaction,Document.Lactation,Document.SideEffects,"
                        ."Document.StorageCondition,Document.Indication,Document.ContraIndication,Document.SpecialInstruction "
                        . "FROM Document"
                        ." LEFT JOIN Document_IndicNozology as n ON Document.DocumentID = n.DocumentID"
                        ." LEFT JOIN Molecule_Document as md ON md.DocumentID = Document.DocumentID"
                        ." LEFT JOIN Molecule as m ON m.MoleculeID = md.MoleculeID"
                        ." LEFT JOIN Product_Document as pd ON pd.DocumentID = Document.DocumentID"
                        ." LEFT JOIN Product_ATC as pa ON pd.ProductID = pa.ProductID"
                        ." GROUP BY Document.DocumentID";
                $result = mysql_query($query) or die(mysql_error());
		while($all = mysql_fetch_array($result)){
                    
                    
                    // Initialize variables
		$app     = JFactory::getApplication();
		$db      = JFactory::getDBO();
		$user    = JFactory::getUser();
		$menu    = $app->getMenu()->getActive();
		$config  = JFactory::getConfig();
		$session = JFactory::getSession();
		$task	   = JRequest::getVar('task');
		$model   = $this->getModel(FLEXI_ITEMVIEW);
		$isnew   = !$model->getId();
		$ctrl_task = FLEXI_J16GE ? 'task=items.' : 'controller=items&task=';
		
		$fc_params  = JComponentHelper::getParams( 'com_flexicontent' );
		$dolog      = $fc_params->get('print_logging_info');
		
		// Get the COMPONENT only parameters
		$comp_params = JComponentHelper::getComponent('com_flexicontent')->params;
		$params = FLEXI_J16GE ? clone ($comp_params) : new JParameter( $comp_params ); // clone( JComponentHelper::getParams('com_flexicontent') );
		
		// Merge the type parameters
		$tparams = $model->getTypeparams();
		$tparams = FLEXI_J16GE ? new JRegistry($tparams) : new JParameter($tparams);
		$params->merge($tparams);
		
		// Merge the menu parameters
		if ($menu) {
			$menu_params = FLEXI_J16GE ? $menu->params : new JParameter($menu->params);
			$params->merge($menu_params);
		}
		
		// Get needed parameters
		$submit_redirect_url_fe = $params->get('submit_redirect_url_fe', '');
		$allowunauthorize       = $params->get('allowunauthorize', 0);
                    
                    $data = array();
                    
                    $data['title'] = $all['RusName'];
                    //content
                    $data['text'] = $all['CompiledComposition'].$all['PhInfluence'].$all['PhKinetics'].$all['Dosage'].$all['OverDosage'].$all['Interaction'].$all['Lactation'].$all['SideEffects'].$all['StorageCondition'].$all['Indication'].$all['ContraIndication'].$all['SpecialInstruction'];
                    $data['state'] = 1;
                    $data['catid'] = 45;
                    $data['type_id'] = 2;
                    $data['id'] = 0;
                    //insert into content

                    //flexicontent_fields_item_relations
                    //15 field RusName EngName

                    //19 field Zabolev
                    $zab = '';
                    if($all['NozologyCode']){
                        $tmp = $all['NozologyCode'];
                        $zab_cif = substr($tmp,1,2);
                        $alpha = substr($tmp,0,1);
                        switch($alpha){
                            case 'A' : $zab = 'A00–B99'; break;
                            case 'B' : $zab = 'A00–B99';break;
                            case 'C' : $zab = 'C00–D48';break;
                            case 'D' : $zab = $zab_cif <= 48 ? 'C00–D48' : 'D50–D89';break;
                            case 'E' : $zab = 'E00–E90';break;
                            case 'F' : $zab = 'F00–F99';break;
                            case 'G' : $zab = 'G00–G99';break;
                            case 'H' : $zab = $zab_cif <= 59 ? 'H00–H59' : 'H60–H95';break;
                            case 'I' : $zab = 'I00–I99';break;
                            case 'J' : $zab = 'J00–J99';break;
                            case 'K' : $zab = 'K00–K93';break;
                            case 'L' : $zab = 'L00–L99';break;
                            case 'M' : $zab = 'M00–M99';break;
                            case 'N' : $zab = 'N00–N99';break;
                            case 'O' : $zab = 'O00–O99';break;
                            case 'P' : $zab = 'P00–P96'; break;
                            case 'R' : $zab = 'R00–R99'; break;
                            case 'S' : $zab = 'S00–T98'; break;
                            case 'V' : $zab = 'V01–Y98';break;
                            case 'Z' : $zab = 'Z00–Z99';break;
                            case 'U' : $zab = 'U00–U99'; break;
                            default: $zab = '';
                        }
                    }
                    $custom = array();
                    $custom['zabolevanie'] = $zab;
                    $custom['field24'] = $all['ATCCode'];
                    /*$custom['field24_1'] = '';
                    $custom['field24_2'] = '';
                    $custom['field24_3'] = '';
                    $custom['field24_4'] = '';
                    $custom['field24_5'] = '';*/
                    $custom['preparat'][0] = addslashes($all['RusName']);
                    $custom['preparat'][1] = addslashes($all['EngName']);
                    $custom['field22'][0] = addslashes($all['LatName']);
                    
                    
                    $query = "SELECT p.DateOfCloseRegistration, p.RegistrationNumber, p.Composition, p.ZipInfo, "
                            ." c.LocalName, c.CountryCode "
                        . "FROM Product as p"
                        ." JOIN Product_Company as pc ON pc.ProductID = p.ProductID"
                        ." JOIN Company as c ON c.CompanyID = pc.CompanyID"    
                        ." JOIN Product_Document d ON d.ProductID = p.ProductID"
                        ." WHERE d.DocumentID = ".$all['DocumentID'];
                    $result1 = mysql_query($query) or die(mysql_error());
                    $field_pr = array();
                    $z = 0;
                    while($proizv = mysql_fetch_array($result1)){
                        if(isset($arr_countries[$proizv['CountryCode']])){
                            $custom['field21'][0]['country'][$z] =  addslashes($arr_countries[$proizv['CountryCode']]);
                            $custom['field21'][0]['naimen'][$z] =  addslashes($proizv['LocalName']);//."<br />".$proizv['Composition']);
                            $custom['field21'][0]['vypusk'][$z] =  addslashes($proizv['ZipInfo']);
                            $custom['field21'][0]['reg'][$z] =  addslashes($proizv['RegistrationNumber']);
                            $custom['field21'][0]['date'][$z] =  addslashes($proizv['DateOfCloseRegistration']);
                        }
                        $z++;
                    }
                    
                                // *********************
                                // Get data from request
                                // *********************

                                if (FLEXI_J16GE) {
                                        // Retrieve form data these are subject to basic filtering
                                       // $data   = JRequest::getVar('jform', array(), 'post', 'array');   // Core Fields and and item Parameters
                                       // $custom = JRequest::getVar('custom', array(), 'post', 'array');  // Custom Fields
                                        $jfdata = JRequest::getVar('jfdata', array(), 'post', 'array');  // Joomfish Data
                                        if ( ! @ $data['rules'] ) $data['rules'] = array();
                                }

                                else {
                                        // Retrieve form data these are subject to basic filtering
                                        $data = JRequest::get( 'post' );  // Core & Custom Fields and item Parameters
                                }

                                // Set data id into model in case not already set ?
                                $model->setId((int) $data['id']);



                                // *************************************
                                // ENFORCE can change category ACL perms
                                // *************************************

                                $perms = FlexicontentHelperPerm::getPerm();
                                // Per content type change category permissions
                                if (FLEXI_J16GE) {
                                        $current_type_id  = ($isnew || !$model->get('type_id')) ? $data['type_id'] : $model->get('type_id');  // GET current (existing/old) item TYPE ID
                                        $CanChangeFeatCat = $user->authorise('flexicontent.change.cat.feat', 'com_flexicontent.type.' . $current_type_id);
                                        $CanChangeSecCat  = $user->authorise('flexicontent.change.cat.sec', 'com_flexicontent.type.' . $current_type_id);
                                        $CanChangeCat     = $user->authorise('flexicontent.change.cat', 'com_flexicontent.type.' . $current_type_id);
                                } else {
                                        $CanChangeFeatCat = 1;
                                        $CanChangeSecCat  = 1;
                                        $CanChangeCat     = 1;
                                }

                                $featured_cats_parent = $params->get('featured_cats_parent', 0);
                                $featured_cats = array();

                                $enable_featured_cid_selector = $perms->MultiCat && $CanChangeFeatCat;
                                $enable_cid_selector   = $perms->MultiCat && $CanChangeSecCat;
                                $enable_catid_selector = ($isnew && !$tparams->get('catid_default')) || (!$isnew && !$model->get('catid')) || $CanChangeCat;

                                // Enforce maintaining featured categories
                                $featured_cats_parent = $params->get('featured_cats_parent', 0);
                                $featured_cats = array();
                                if ( $featured_cats_parent && !$enable_featured_cid_selector )
                                {
                                        $featured_tree = flexicontent_cats::getCategoriesTree($published_only=1, $parent_id=$featured_cats_parent, $depth_limit=0);
                                        $featured_cid = array();
                                        if (!$isnew) {
                                                foreach($model->get('categories') as $item_cat) if (isset($featured_tree[$item_cat])) $featured_cid[] = $item_cat;
                                        }
                                        $data['featured_cid'] = $featured_cid;
                                }

                                // Enforce maintaining secondary categories
                                if (!$enable_cid_selector) {
                                        if ($isnew) {
                                                $data['cid'] = $tparams->get('cid_default');
                                        } else if ( isset($featured_cid) ) {
                                                $featured_cid_arr = array_flip($featured_cid);
                                                $sec_cid = array();
                                                foreach($model->get('cats') as $item_cat) if (!isset($featured_cid_arr[$item_cat])) $sec_cid[] = $item_cat;
                                                $data['cid'] = $sec_cid;
                                        } else {
                                                $data['cid'] = $model->get('cats');
                                        }
                                }

                                if (!$enable_catid_selector) {
                                        if ($isnew && $tparams->get('catid_default'))
                                                $data['catid'] = $tparams->get('catid_default');
                                        else if ($model->get('catid'))
                                                $data['catid'] = $model->get('catid');
                                }



                                // **************************
                                // Basic Form data validation
                                // **************************

                                if (FLEXI_J16GE)
                                {
                                        // *** MANUALLY CHECK CAPTCHA ***
                                        $use_captcha    = $params->get('use_captcha', 1);     // 1 for guests, 2 for any user
                                        $captcha_formop = $params->get('captcha_formop', 0);  // 0 for submit, 1 for submit/edit (aka always)
                                        $is_submitop = ((int) $data['id']) == 0;
                                        $display_captcha = $use_captcha >= 2 || ( $use_captcha == 1 &&  $user->guest );
                                        $display_captcha = $display_captcha && ( $is_submitop || $captcha_formop);  // for submit operation we do not need to check 'captcha_formop' ...
                                        if ($display_captcha)
                                        {
                                                // Try to force the use of recaptcha plugin
                                                JFactory::getConfig()->set('captcha', 'recaptcha');

                                                if ( $app->getCfg('captcha') == 'recaptcha' && JPluginHelper::isEnabled('captcha', 'recaptcha') ) {
                                                        JPluginHelper::importPlugin('captcha');
                                                        $dispatcher = JDispatcher::getInstance();
                                                        $result = $dispatcher->trigger('onCheckAnswer', JRequest::getString('recaptcha_response_field'));
                                                        if (!$result[0]) {
                                                                $errmsg  = JText::_('FLEXI_CAPTCHA_FAILED');
                                                                $errmsg .= ' '.JText::_('FLEXI_MUST_REFILL_SOME_FIELDS');
                                                                echo "<script>alert('".$errmsg."');";
                                                                echo "window.history.back();";
                                                                echo "</script>";
                                                                jexit();
                                                        }
                                                }
                                        }

                                        // Validate Form data for core fields and for parameters
                                        $form = $model->getForm();          // Do not pass any data we only want the form object in order to validate the data and not create a filled-in form
                                        $post = $model->validate($form, $data);

                                        // Check for validation error
                                        if (!$post) {
                                                // Get the validation messages.
                                                $errors	= $form->getErrors();

                                                // Push up to three validation messages out to the user.
                                                for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
                                                        if ($errors[$i] instanceof Exception)
                                                                $app->enqueueMessage($errors[$i]->getMessage(), 'notice');
                                                        else
                                                                $app->enqueueMessage($errors[$i], 'notice');
                                                }

                                                // Save the jform data in the session.
                                                $app->setUserState($form->option.'.edit.'.$form->context.'.data', $data);
                                                // Save the custom fields data in the session.
                                                $app->setUserState($form->option.'.edit.'.$form->context.'.custom', $custom);

                                                // Redirect back to the registration form.
                                                $this->setRedirect( $_SERVER['HTTP_REFERER'] );
                                                return false;
                                                //die('error');
                                        }

                                        /*if (!$post) {
                                                //JError::raiseWarning( 500, "Error while validating data: " . $model->getError() );
                                                echo "Error while validating data: " . $model->getError();
                                                echo '<span class="fc_return_msg">'.JText::sprintf('FLEXI_CLICK_HERE_TO_RETURN', '"JavaScript:window.history.back();"').'</span>';
                                                jexit();
                                        }*/

                                        // Some values need to be assigned after validation
                                        $post['attribs'] = @$data['attribs'];  // Workaround for item's template parameters being clear by validation since they are not present in item.xml
                                        $post['custom']  = & $custom;          // Assign array of custom field values, they are in the 'custom' form array instead of jform
                                        $post['jfdata']  = & $jfdata;          // Assign array of Joomfish field values, they are in the 'jfdata' form array instead of jform

                                        // Assign template parameters of the select ilayout as an sub-array (the DB model will handle the merging of parameters)
                                        $ilayout = @ $data['attribs']['ilayout'];  // normal not be set if frontend template editing is not shown
                                        if( $ilayout && !empty($data['layouts'][$ilayout]) )   $post['attribs']['layouts'] = $data['layouts'];
                                        //echo "<pre>"; print_r($post['attribs']); exit;
                                }

                                else {
                                        $post = $data;

                                        // Some values need to be assigned after validation
                                        $post['text'] = JRequest::getVar( 'text', '', 'post', 'string', JREQUEST_ALLOWRAW ); // Workaround for allowing raw text field

                                        // Assign template parameters of the select ilayout as an sub-array (the DB model will handle the merging of parameters)
                                        $ilayout = @ $post['params']['ilayout'];  // normal not be set if frontend template editing is not shown
                                        if( $ilayout && !empty($post['layouts'][$ilayout]) )  $post['params']['layouts'] = $post['layouts'];
                                        //echo "<pre>"; print_r($post['params']); exit;

                                }

                                // USEFULL FOR DEBUGING for J2.5 (do not remove commented code)
                                //$diff_arr = array_diff_assoc ( $data, $post);
                                //echo "<pre>"; print_r($diff_arr); jexit();


                                // ********************************************************************************
                                // PERFORM ACCESS CHECKS, NOTE: we need to check access again, despite having
                                // checked them on edit form load, because user may have tampered with the form ... 
                                // ********************************************************************************

                                $type_id = (int) @ $post['type_id'];  // Typecast to int, (already done for J2.5 via validating)
                                if ( !$isnew && $model->get('type_id') == $type_id ) {
                                        // Existing item with Type not being ALTERED, content type can be maintained regardless of privilege
                                        $canCreateType = true;
                                } else {
                                        // New item or existing item with Type is being ALTERED, check privilege to create items of this type
                                        $canCreateType = $model->canCreateType( array($type_id), true, $types );
                                }


                                // ****************************************************************
                                // Calculate user's privileges on current content item
                                // ... canPublish IS RECALCULATED after saving, maybe comment out ?
                                // ****************************************************************

                                if (!$isnew) {

                                        if (FLEXI_J16GE) {
                                                $asset = 'com_content.article.' . $model->get('id');
                                                $canPublish = $user->authorise('core.edit.state', $asset) || ($user->authorise('core.edit.state.own', $asset) && $model->get('created_by') == $user->get('id'));
                                                $canEdit = $user->authorise('core.edit', $asset) || ($user->authorise('core.edit.own', $asset) && $model->get('created_by') == $user->get('id'));
                                                // ALTERNATIVE 1
                                                //$canEdit = $model->getItemAccess()->get('access-edit'); // includes privileges edit and edit-own
                                                // ALTERNATIVE 2
                                                //$rights = FlexicontentHelperPerm::checkAllItemAccess($user->get('id'), 'item', $model->get('id'));
                                                //$canEdit = in_array('edit', $rights) || (in_array('edit.own', $rights) && $model->get('created_by') == $user->get('id')) ;
                                        } else if ($user->gid >= 25) {
                                                $canPublish = true;
                                                $canEdit = true;
                                        } else if (FLEXI_ACCESS) {
                                                $rights 	= FAccess::checkAllItemAccess('com_content', 'users', $user->gmid, $model->get('id'), $model->get('catid'));
                                                $canPublish = in_array('publish', $rights) || (in_array('publishown', $rights) && $model->get('created_by') == $user->get('id')) ;
                                                $canEdit = in_array('edit', $rights) || (in_array('editown', $rights) && $model->get('created_by') == $user->get('id')) ;
                                        } else {
                                                $canPublish = $user->authorize('com_content', 'publish', 'content', 'all');
                                                $canEdit = $user->authorize('com_content', 'edit', 'content', 'all') || ($user->authorize('com_content', 'edit', 'content', 'own') && $model->get('created_by') == $user->get('id'));
                                                //$canPublish = ($user->gid >= 21);  // At least J1.5 Publisher
                                                //$canEdit = ($user->gid >= 20);  // At least J1.5 Editor
                                        }

                                        if ( !$canEdit ) {
                                                // No edit privilege, check if item is editable till logoff
                                                if ($session->has('rendered_uneditable', 'flexicontent')) {
                                                        $rendered_uneditable = $session->get('rendered_uneditable', array(),'flexicontent');
                                                        $canEdit = isset($rendered_uneditable[$model->get('id')]) && $rendered_uneditable[$model->get('id')];
                                                }
                                        }

                                } else {

                                        if (FLEXI_J16GE) {
                                                $canAdd = $model->getItemAccess()->get('access-create'); // includes check of creating in at least one category
                                                $not_authorised = !$canAdd;

                                                $canPublish	= $user->authorise('core.edit.state', 'com_flexicontent') || $user->authorise('core.edit.state.own', 'com_flexicontent');
                                        } else if ($user->gid >= 25) {
                                                $canAdd = 1;
                                        } else if (FLEXI_ACCESS) {
                                                $canAdd = FAccess::checkUserElementsAccess($user->gmid, 'submit');
                                                $canAdd = @$canAdd['content'] || @$canAdd['category'];

                                                $canPublishAll 		= FAccess::checkAllContentAccess('com_content','publish','users',$user->gmid,'content','all');
                                                $canPublishOwnAll	= FAccess::checkAllContentAccess('com_content','publishown','users',$user->gmid,'content','all');
                                                $canPublish	= ($user->gid < 25) ? $canPublishAll || $canPublishOwnAll : 1;
                                        } else {
                                                $canAdd	= $user->authorize('com_content', 'add', 'content', 'all');
                                                //$canAdd = ($user->gid >= 19);  // At least J1.5 Author
                                                $not_authorised = ! $canAdd;
                                                $canPublish	= ($user->gid >= 21);
                                        }

                                        if ( $allowunauthorize ) {
                                                $canAdd = true;
                                                $canCreateType = true;
                                        }
                                }

                                // ... we use some strings from administrator part
                                // load english language file for 'com_flexicontent' component then override with current language file
                                JFactory::getLanguage()->load('com_flexicontent', JPATH_ADMINISTRATOR, 'en-GB', true);
                                JFactory::getLanguage()->load('com_flexicontent', JPATH_ADMINISTRATOR, null, true);

                                // Check for new content
                                if ( ($isnew && !$canAdd) || (!$isnew && !$canEdit)) {
                                        $msg = JText::_( 'FLEXI_ALERTNOTAUTH' );
                                        if (FLEXI_J16GE) throw new Exception($msg, 403); else JError::raiseError(403, $msg);
                                }

                                if ( !$canCreateType ) {
                                        $msg = isset($types[$type_id]) ?
                                                JText::sprintf( 'FLEXI_NO_ACCESS_CREATE_CONTENT_OF_TYPE', JText::_($types[$type_id]->name) ) :
                                                ' Content Type '.$type_id.' was not found OR is not published';
                                        if (FLEXI_J16GE) throw new Exception($msg, 403); else JError::raiseError(403, $msg);
                                        return;
                                }

                                // Get "BEFORE SAVE" categories for information mail
                                $before_cats = array();
                                if ( !$isnew )
                                {
                                        $query 	= 'SELECT DISTINCT c.id, c.title FROM #__categories AS c'
                                                . ' JOIN #__flexicontent_cats_item_relations AS rel ON rel.catid = c.id'
                                                . ' WHERE rel.itemid = '.(int) $model->get('id');
                                        $db->setQuery( $query );
                                        $before_cats = $db->loadObjectList('id');
                                        $before_maincat = $model->get('catid');
                                        $original_item = $model->getItem($post['id'], $check_view_access=false, $no_cache=true, $force_version=0);
                                }


                                // ****************************************
                                // Try to store the form data into the item
                                // ****************************************
                                if ( ! $model->store($post) )
                                {
                                        // Set error message about saving failed, and also the reason (=model's error message)
                                        $msg = JText::_( 'FLEXI_ERROR_STORING_ITEM' );
                                        JError::raiseWarning( 500, $msg .": " . $model->getError() );

                                        // Since an error occured, check if (a) the item is new and (b) was not created
                                        if ($isnew && !$model->get('id')) {
                                                $msg = '';
                                                $link = 'index.php?option=com_flexicontent&'.$ctrl_task.'add&id=0&typeid='.$type_id.'&'. (FLEXI_J30GE ? JSession::getFormToken() : JUtility::getToken()) .'=1';
                                                $this->setRedirect($link, $msg);
                                        } else {
                                                $msg = '';
                                                $link = 'index.php?option=com_flexicontent&'.$ctrl_task.'edit&id='.$model->get('id').'&'. (FLEXI_J30GE ? JSession::getFormToken() : JUtility::getToken()) .'=1';
                                                $this->setRedirect($link, $msg);
                                        }

                                        // Saving has failed check-in and return, (above redirection will be used)
                                        $model->checkin();
                                        return;
                                }


                                // **************************************************
                                // Check in model and get item id in case of new item
                                // **************************************************
                                $model->checkin();
                                $post['id'] = $isnew ? (int) $model->get('id') : $post['id'];

                                // Get items marked as newly submitted
                                $newly_submitted = $session->get('newly_submitted', array(), 'flexicontent');
                                if ($isnew) {
                                        // Mark item as newly submitted, to allow to a proper "THANKS" message after final save & close operation (since user may have clicked add instead of add & close)
                                        $newly_submitted[$model->get('id')] = 1;
                                        $session->set('newly_submitted', $newly_submitted, 'flexicontent');
                                }
                                $newly_submitted_item = @ $newly_submitted[$model->get('id')];


                                // ***********************************************************************************************************
                                // Get newly saved -latest- version (store task gets latest) of the item, and also calculate publish privelege
                                // ***********************************************************************************************************
                                $item = $model->getItem($post['id'], $check_view_access=false, $no_cache=true, $force_version=-1);
                                $canPublish = $model->canEditState( $item, $check_cat_perm=true );


                                // ********************************************************************************************
                                // Use session to detect multiple item saves to avoid sending notification EMAIL multiple times
                                // ********************************************************************************************
                                $is_first_save = true;
                                if ($session->has('saved_fcitems', 'flexicontent')) {
                                        $saved_fcitems = $session->get('saved_fcitems', array(), 'flexicontent');
                                        $is_first_save = $isnew ? true : !isset($saved_fcitems[$model->get('id')]);
                                }
                                // Add item to saved items of the corresponding session array
                                $saved_fcitems[$model->get('id')] = $timestamp = time();  // Current time as seconds since Unix epoc;
                                $session->set('saved_fcitems', $saved_fcitems, 'flexicontent');


                                // ********************************************
                                // Get categories added / removed from the item
                                // ********************************************
                                $query 	= 'SELECT DISTINCT c.id, c.title FROM #__categories AS c'
                                        . ' JOIN #__flexicontent_cats_item_relations AS rel ON rel.catid = c.id'
                                        . ' WHERE rel.itemid = '.(int) $model->get('id');
                                $db->setQuery( $query );
                                $after_cats = $db->loadObjectList('id');
                                if ( !$isnew ) {
                                        $cats_added_ids = array_diff(array_keys($after_cats), array_keys($before_cats));
                                        foreach($cats_added_ids as $cats_added_id) {
                                                $cats_added_titles[] = $after_cats[$cats_added_id]->title;
                                        }

                                        $cats_removed_ids = array_diff(array_keys($before_cats), array_keys($after_cats));
                                        foreach($cats_removed_ids as $cats_removed_id) {
                                                $cats_removed_titles[] = $before_cats[$cats_removed_id]->title;
                                        }
                                        $cats_altered = count($cats_added_ids) + count($cats_removed_ids);
                                        $after_maincat = $model->get('catid');
                                }


                                // *******************************************************************************************************************
                                // We need to get emails to notify, from Global/item's Content Type parameters -AND- from item's categories parameters
                                // *******************************************************************************************************************
                                $notify_emails = array();
                                if ( $is_first_save || $cats_altered || $params->get('nf_enable_debug',0) )
                                {
                                        // Get needed flags regarding the saved items
                                        $approve_version = 2;
                                        $pending_approval_state = -3;
                                        $draft_state = -4;

                                        $current_version = FLEXIUtilities::getCurrentVersions($item->id, true); // Get current item version
                                        $last_version    = FLEXIUtilities::getLastVersions($item->id, true);    // Get last version (=latest one saved, highest version id),

                                        // $post variables vstate & state may have been (a) tampered in the form, and/or (b) altered by save procedure so better not use them
                                        $needs_version_reviewal     = !$isnew && ($last_version > $current_version) && !$canPublish;
                                        $needs_publication_approval =  $isnew && ($item->state == $pending_approval_state) && !$canPublish;

                                        $draft_from_non_publisher = $item->state==$draft_state && !$canPublish;

                                        if ($draft_from_non_publisher) {
                                                // Suppress notifications for draft-state items (new or existing ones), for these each author will publication approval manually via a button
                                                $nConf = false;
                                        } else {
                                                // Get notifications configuration and select appropriate emails for current saving case
                                                $nConf = $model->getNotificationsConf($params);  //echo "<pre>"; print_r($nConf); "</pre>";
                                        }

                                        if ($nConf)
                                        {
                                                $states_notify_new = $params->get('states_notify_new', array(1,0,(FLEXI_J16GE ? 2:-1),-3,-4,-5));
                                                if ( empty($states_notify_new) )						$states_notify_new = array();
                                                else if ( ! is_array($states_notify_new) )	$states_notify_new = !FLEXI_J16GE ? array($states_notify_new) : explode("|", $states_notify_new);

                                                $states_notify_existing = $params->get('states_notify_existing', array(1,0,(FLEXI_J16GE ? 2:-1),-3,-4,-5));
                                                if ( empty($states_notify_existing) )						$states_notify_existing = array();
                                                else if ( ! is_array($states_notify_existing) )	$states_notify_existing = !FLEXI_J16GE ? array($states_notify_existing) : explode("|", $states_notify_existing);

                                                $n_state_ok = in_array($item->state, $states_notify_new);
                                                $e_state_ok = in_array($item->state, $states_notify_existing);

                                                if ($needs_publication_approval)   $notify_emails = $nConf->emails->notify_new_pending;
                                                else if ($isnew && $n_state_ok)    $notify_emails = $nConf->emails->notify_new;
                                                else if ($isnew)                   $notify_emails = array();
                                                else if ($needs_version_reviewal)  $notify_emails = $nConf->emails->notify_existing_reviewal;
                                                else if (!$isnew && $e_state_ok)   $notify_emails = $nConf->emails->notify_existing;
                                                else if (!$isnew)                  $notify_emails = array();

                                                if ($needs_publication_approval)   $notify_text = $params->get('text_notify_new_pending');
                                                else if ($isnew)                   $notify_text = $params->get('text_notify_new');
                                                else if ($needs_version_reviewal)  $notify_text = $params->get('text_notify_existing_reviewal');
                                                else if (!$isnew)                  $notify_text = $params->get('text_notify_existing');
                                                //print_r($notify_emails); jexit();
                                        }
                                }


                                // *********************************************************************************************************************
                                // If there are emails to notify for current saving case, then send the notifications emails, but 
                                // *********************************************************************************************************************
                                if ( !empty($notify_emails) && count($notify_emails) ) {
                                        $notify_vars = new stdClass();
                                        $notify_vars->needs_version_reviewal     = $needs_version_reviewal;
                                        $notify_vars->needs_publication_approval = $needs_publication_approval;
                                        $notify_vars->isnew         = $isnew;
                                        $notify_vars->notify_emails = $notify_emails;
                                        $notify_vars->notify_text   = $notify_text;
                                        $notify_vars->before_cats   = $before_cats;
                                        $notify_vars->after_cats    = $after_cats;
                                        $notify_vars->original_item = @ $original_item;

                                        $model->sendNotificationEmails($notify_vars, $params, $manual_approval_request=0);
                                }


                                // ***************************************************
                                // CLEAN THE CACHE so that our changes appear realtime
                                // ***************************************************
                                if (FLEXI_J16GE) {
                                        $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');
                                } else {
                                        $itemcache = JFactory::getCache('com_flexicontent_items');
                                        $itemcache->clean();
                                        $filtercache = JFactory::getCache('com_flexicontent_filters');
                                        $filtercache->clean();
                                }


                                // ****************************************************************************************************************************
                                // Recalculate EDIT PRIVILEGE of new item. Reason for needing to do this is because we can have create permission in a category
                                // and thus being able to set this category as item's main category, but then have no edit/editown permission for this category
                                // ****************************************************************************************************************************
                                if (FLEXI_J16GE) {
                                        $asset = 'com_content.article.' . $model->get('id');
                                        $canEdit = $user->authorise('core.edit', $asset) || ($user->authorise('core.edit.own', $asset) && $model->get('created_by') == $user->get('id'));
                                        // ALTERNATIVE 1
                                        //$canEdit = $model->getItemAccess()->get('access-edit'); // includes privileges edit and edit-own
                                        // ALTERNATIVE 2
                                        //$rights = FlexicontentHelperPerm::checkAllItemAccess($user->get('id'), 'item', $model->get('id'));
                                        //$canEdit = in_array('edit', $rights) || (in_array('edit.own', $rights) && $model->get('created_by') == $user->get('id')) ;
                                } else if (FLEXI_ACCESS && $user->gid < 25) {
                                        $rights 	= FAccess::checkAllItemAccess('com_content', 'users', $user->gmid, $model->get('id'), $model->get('catid'));
                                        $canEdit = in_array('edit', $rights) || (in_array('editown', $rights) && $model->get('created_by') == $user->get('id')) ;
                                } else {
                                        // This is meaningful when executed in frontend, since all backend users (managers and above) can edit items
                                        $canEdit = $user->authorize('com_content', 'edit', 'content', 'all') || ($user->authorize('com_content', 'edit', 'content', 'own') && $model->get('created_by') == $user->get('id'));
                                }


                                // *******************************************************************************************************
                                // Check if user can not edit item further (due to changed main category, without edit/editown permission)
                                // *******************************************************************************************************
                                if (!$canEdit)
                                {
                                        if ($task=='apply') {
                                                // APPLY TASK: Temporarily set item to be editable till closing it
                                                $rendered_uneditable = $session->get('rendered_uneditable', array(),'flexicontent');
                                                $rendered_uneditable[$model->get('id')]  = 1;
                                                $session->set('rendered_uneditable', $rendered_uneditable, 'flexicontent');
                                                $canEdit = 1;
                                        }

                                        else if ( $newly_submitted_item ) {
                                                // NEW ITEM: Do not use editable till logoff behaviour
                                                // ALSO: Clear editable FLAG set in the case that 'apply' button was used during new item creation
                                                if ( !$params->get('items_session_editable', 0) ) {
                                                        $rendered_uneditable = $session->get('rendered_uneditable', array(),'flexicontent');
                                                        if ( isset($rendered_uneditable[$model->get('id')]) ) {
                                                                unset( $rendered_uneditable[$model->get('id')] );
                                                                $session->set('rendered_uneditable', $rendered_uneditable, 'flexicontent');
                                                        }
                                                }
                                        }

                                        else {
                                                // EXISTING ITEM: (if enabled) Use the editable till logoff behaviour
                                                if ( $params->get('items_session_editable', 0) ) {

                                                        // Set notice for existing item being editable till logoff 
                                                        JError::raiseNotice( 403, JText::_( 'FLEXI_CANNOT_EDIT_AFTER_LOGOFF' ) );

                                                        // Allow item to be editable till logoff
                                                        $rendered_uneditable = $session->get('rendered_uneditable', array(),'flexicontent');
                                                        $rendered_uneditable[$model->get('id')]  = 1;
                                                        $session->set('rendered_uneditable', $rendered_uneditable, 'flexicontent');
                                                        $canEdit = 1;
                                                }
                                        }

                                        // Set notice about saving an item that cannot be changed further
                                        if ( !$canEdit ) {
                                                $app->enqueueMessage(JText::_( 'FLEXI_CANNOT_MAKE_FURTHER_CHANGES_TO_CONTENT' ), 'message' );
                                        }
                                }


                                // ****************************************************************
                                // Check for new Content Item is being closed, and clear some flags
                                // ****************************************************************

                                if ($task!='apply' && $newly_submitted_item )
                                {
                                        // Clear item from being marked as newly submitted
                                        unset($newly_submitted[$model->get('id')]);
                                        $session->set('newly_submitted', $newly_submitted, 'flexicontent');

                                        // The 'apply' task may set 'editable till logoff' FLAG ...
                                        // CLEAR IT, since NEW content this is meant to be used temporarily
                                        if ( !$params->get('items_session_editable', 0) ) {
                                                $rendered_uneditable = $session->get('rendered_uneditable', array(),'flexicontent');
                                                if ( isset($rendered_uneditable[$model->get('id')]) ) {
                                                        unset( $rendered_uneditable[$model->get('id')] );
                                                        $session->set('rendered_uneditable', $rendered_uneditable, 'flexicontent');
                                                }
                                        }
                                }


                               
                }
		//$this->setRedirect($link, $msg);
	}
Esempio n. 8
0
    /**
     * Creates the item submit form
     *
     * @since 1.0
     */
    function _displayForm($tpl)
    {
        jimport('joomla.html.parameter');
        // ... we use some strings from administrator part
        // load english language file for 'com_content' component then override with current language file
        JFactory::getLanguage()->load('com_content', JPATH_ADMINISTRATOR, 'en-GB', true);
        JFactory::getLanguage()->load('com_content', JPATH_ADMINISTRATOR, null, true);
        // load english language file for 'com_flexicontent' component then override with current language file
        JFactory::getLanguage()->load('com_flexicontent', JPATH_ADMINISTRATOR, 'en-GB', true);
        JFactory::getLanguage()->load('com_flexicontent', JPATH_ADMINISTRATOR, null, true);
        // ********************************
        // Initialize variables, flags, etc
        // ********************************
        $app = JFactory::getApplication();
        $dispatcher = JDispatcher::getInstance();
        $document = JFactory::getDocument();
        $session = JFactory::getSession();
        $user = JFactory::getUser();
        $db = JFactory::getDBO();
        $uri = JFactory::getURI();
        $nullDate = $db->getNullDate();
        $menu = $app->getMenu()->getActive();
        // Get the COMPONENT only parameters, then merge the menu parameters
        $comp_params = JComponentHelper::getComponent('com_flexicontent')->params;
        $params = FLEXI_J16GE ? clone $comp_params : new JParameter($comp_params);
        // clone( JComponentHelper::getParams('com_flexicontent') );
        if ($menu) {
            $menu_params = FLEXI_J16GE ? $menu->params : new JParameter($menu->params);
            $params->merge($menu_params);
        }
        // Some flags
        $enable_translation_groups = $params->get("enable_translation_groups") && (FLEXI_J16GE || FLEXI_FISH);
        $print_logging_info = $params->get('print_logging_info');
        if ($print_logging_info) {
            global $fc_run_times;
        }
        // *****************
        // Load JS/CSS files
        // *****************
        FLEXI_J30GE ? JHtml::_('behavior.framework', true) : JHTML::_('behavior.mootools');
        flexicontent_html::loadFramework('jQuery');
        flexicontent_html::loadFramework('select2');
        // Load custom behaviours: form validation, popup tooltips
        //JHTML::_('behavior.formvalidation');
        JHTML::_('behavior.tooltip');
        if (FLEXI_J30GE) {
            JHtml::_('bootstrap.tooltip');
        }
        //JHTML::_('script', 'joomla.javascript.js', 'includes/js/');
        // Add css files to the document <head> section (also load CSS joomla template override)
        $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontent.css');
        if (file_exists(JPATH_SITE . DS . 'templates' . DS . $app->getTemplate() . DS . 'css' . DS . 'flexicontent.css')) {
            $document->addStyleSheet(JPATH_SITE . DS . 'templates' . DS . $app->getTemplate() . DS . 'css' . DS . 'flexicontent.css');
        }
        if (!FLEXI_J16GE) {
            $document->addStyleSheet($this->baseurl . '/administrator/templates/khepri/css/general.css');
        }
        //$document->addCustomTag('<!--[if IE]><style type="text/css">.floattext{zoom:1;}, * html #flexicontent dd { height: 1%; }</style><![endif]-->');
        // Load backend / frontend shared and Joomla version specific CSS (different for frontend / backend)
        $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/flexi_shared.css');
        // NOTE: this is imported by main Frontend CSS file
        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');
            } else {
                $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/j15.css');
            }
        }
        // Add js function to overload the joomla submitform
        $document->addScript(JURI::base(true) . '/components/com_flexicontent/assets/js/admin.js');
        $document->addScript(JURI::base(true) . '/components/com_flexicontent/assets/js/validate.js');
        // Add js function for custom code used by FLEXIcontent item form
        $document->addScript(JURI::base(true) . '/components/com_flexicontent/assets/js/itemscreen.js');
        // ***********************************************
        // Get item and create form (that loads item data)
        // ***********************************************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $model = $this->getModel();
        // ** WE NEED TO get OR decide the Content Type, before we call the getItem
        // ** We rely on typeid Request variable to decide type for new items so make sure this is set,
        // ZERO means allow user to select type, but if user is only allowed a single type, then autoselect it!
        if ($menu && isset($menu->query['typeid'])) {
            JRequest::setVar('typeid', (int) $menu->query['typeid']);
            // This also forces zero if value not set
        }
        $new_typeid = JRequest::getVar('typeid', 0, '', 'int');
        if (!$new_typeid) {
            $types = $model->getTypeslist($type_ids_arr = false, $check_perms = true);
            if ($types && count($types) == 1) {
                $new_typeid = $types[0]->id;
            }
            JRequest::setVar('typeid', $new_typeid);
            $canCreateType = true;
        }
        $item = $this->get('Item');
        if (FLEXI_J16GE) {
            $form = $this->get('Form');
        }
        if ($print_logging_info) {
            $fc_run_times['get_item_data'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // *********************************************************************************************************
        // Get language stuff, and also load Template-Specific language file to override or add new language strings
        // *********************************************************************************************************
        if ($enable_translation_groups) {
            $langAssocs = $this->get('LangAssocs');
        }
        if (FLEXI_FISH || FLEXI_J16GE) {
            $langs = FLEXIUtilities::getLanguages('code');
        }
        if (FLEXI_FISH || FLEXI_J16GE) {
            FLEXIUtilities::loadTemplateLanguageFile($item->parameters->get('ilayout', 'default'));
        }
        // ****************************************************************************************
        // CHECK EDIT / CREATE PERMISSIONS (this is duplicate since it also done at the controller)
        // ****************************************************************************************
        // new item and ownership variables
        $isnew = !$item->id;
        $isOwner = $item->created_by == $user->get('id');
        // create and set (into HTTP request) a unique item id for plugins that needed it
        JRequest::setVar('unique_tmp_itemid', $item->id ? $item->id : date('_Y_m_d_h_i_s_', time()) . uniqid(true));
        // Component / Menu Item parameters
        $allowunauthorize = $params->get('allowunauthorize', 0);
        // allow unauthorised user to submit new content
        $unauthorized_page = $params->get('unauthorized_page', '');
        // page URL for unauthorized users (via global configuration)
        $notauth_itemid = $params->get('notauthurl', '');
        // menu itemid (to redirect) when user is not authorized to create content
        // Create captcha field or messages
        if (FLEXI_J16GE) {
            $use_captcha = $params->get('use_captcha', 1);
            // 1 for guests, 2 for any user
            $captcha_formop = $params->get('captcha_formop', 0);
            // 0 for submit, 1 for submit/edit (aka always)
            $display_captcha = $use_captcha >= 2 || $use_captcha == 1 && $user->guest;
            $display_captcha = $display_captcha && ($isnew || $captcha_formop);
            // Force using recaptcha
            if ($display_captcha) {
                // Try to force the use of recaptcha plugin
                JFactory::getConfig()->set('captcha', 'recaptcha');
                if (!$app->getCfg('captcha')) {
                    $captcha_errmsg = '-- Please select <b>CAPTCHA Type</b> at global Joomla parameters';
                } else {
                    if ($app->getCfg('captcha') != 'recaptcha') {
                        $captcha_errmsg = '-- Captcha Type: <b>' . $app->getCfg('captcha') . '</b> not supported';
                    } else {
                        if (!JPluginHelper::isEnabled('captcha', 'recaptcha')) {
                            $captcha_errmsg = '-- Please enable & configure the Joomla <b>ReCaptcha Plugin</b>';
                        } else {
                            $captcha_errmsg = '';
                            JPluginHelper::importPlugin('captcha');
                            $dispatcher->trigger('onInit', 'dynamic_recaptcha_1');
                            $field_description = JText::_('FLEXI_CAPTCHA_ENTER_CODE_DESC');
                            $label_tooltip = 'class="hasTip flexi_label" title="' . '::' . htmlspecialchars($field_description, ENT_COMPAT, 'UTF-8') . '"';
                            $captcha_field = '
						<label id="recaptcha_response_field-lbl" for="recaptcha_response_field" ' . $label_tooltip . ' >
						' . JText::_('FLEXI_CAPTCHA_ENTER_CODE') . '
						</label>
						<div class="container_fcfield container_fcfield_name_captcha">
							<div id="dynamic_recaptcha_1"></div>
						</div>
						';
                        }
                    }
                }
            }
        }
        // User Group / Author parameters
        $db->setQuery('SELECT author_basicparams FROM #__flexicontent_authors_ext WHERE user_id = ' . $user->id);
        $authorparams = $db->loadResult();
        $authorparams = FLEXI_J16GE ? new JRegistry($authorparams) : new JParameter($authorparams);
        $max_auth_limit = $authorparams->get('max_auth_limit', 0);
        // maximum number of content items the user can create
        if (!$isnew) {
            // EDIT action
            // Finally check if item is currently being checked-out (currently being edited)
            if ($model->isCheckedOut($user->get('id'))) {
                $msg = JText::sprintf('FLEXI_DESCBEINGEDITTED', $model->get('title'));
                $app->redirect(JRoute::_('index.php?view=' . FLEXI_ITEMVIEW . '&cid=' . $model->get('catid') . '&id=' . $model->get('id'), false), $msg);
            }
            //Checkout the item
            $model->checkout();
            if (FLEXI_J16GE) {
                $canEdit = $model->getItemAccess()->get('access-edit');
                // includes privileges edit and edit-own
                // ALTERNATIVE 1
                //$asset = 'com_content.article.' . $model->get('id');
                //$canEdit = $user->authorise('core.edit', $asset) || ($user->authorise('core.edit.own', $asset) && $model->get('created_by') == $user->get('id'));
                // ALTERNATIVE 2
                //$rights = FlexicontentHelperPerm::checkAllItemAccess($user->get('id'), 'item', $model->get('id'));
                //$canEdit = in_array('edit', $rights) || (in_array('edit.own', $rights) && $model->get('created_by') == $user->get('id')) ;
            } else {
                if ($user->gid >= 25) {
                    $canEdit = true;
                } else {
                    if (FLEXI_ACCESS) {
                        $rights = FAccess::checkAllItemAccess('com_content', 'users', $user->gmid, $model->get('id'), $model->get('catid'));
                        $canEdit = in_array('edit', $rights) || in_array('editown', $rights) && $model->get('created_by') == $user->get('id');
                    } else {
                        $canEdit = $user->authorize('com_content', 'edit', 'content', 'all') || $user->authorize('com_content', 'edit', 'content', 'own') && $model->get('created_by') == $user->get('id');
                        //$canEdit = ($user->gid >= 20);  // At least J1.5 Editor
                    }
                }
            }
            if (!$canEdit) {
                // No edit privilege, check if item is editable till logoff
                if ($session->has('rendered_uneditable', 'flexicontent')) {
                    $rendered_uneditable = $session->get('rendered_uneditable', array(), 'flexicontent');
                    $canEdit = isset($rendered_uneditable[$model->get('id')]) && $rendered_uneditable[$model->get('id')];
                }
            }
            if (!$canEdit) {
                if ($user->guest) {
                    $uri = JFactory::getURI();
                    $return = $uri->toString();
                    $fcreturn = serialize(array('id' => @$this->_item->id, 'cid' => $cid));
                    // a special url parameter, used by some SEF code
                    $com_users = FLEXI_J16GE ? 'com_users' : 'com_user';
                    $url = $params->get('login_page', 'index.php?option=' . $com_users . '&view=login');
                    $return = strtr(base64_encode($return), '+/=', '-_,');
                    $url .= '&return=' . $return;
                    //$url .= '&return='.urlencode(base64_encode($return));
                    $url .= '&fcreturn=' . base64_encode($fcreturn);
                    JError::raiseWarning(403, JText::sprintf("FLEXI_LOGIN_TO_ACCESS", $url));
                    $app->redirect($url);
                } else {
                    if ($unauthorized_page) {
                        //  unauthorized page via global configuration
                        JError::raiseNotice(403, JText::_('FLEXI_ALERTNOTAUTH_TASK'));
                        $app->redirect($unauthorized_page);
                    } else {
                        // user isn't authorize to edit this content
                        $msg = JText::_('FLEXI_ALERTNOTAUTH_TASK');
                        if (FLEXI_J16GE) {
                            throw new Exception($msg, 403);
                        } else {
                            JError::raiseError(403, $msg);
                        }
                    }
                }
            }
        } else {
            // CREATE action
            if (FLEXI_J16GE) {
                $canAdd = $model->getItemAccess()->get('access-create');
                // includes check of creating in at least one category
                $not_authorised = !$canAdd;
            } else {
                if ($user->gid >= 25) {
                    $not_authorised = 0;
                } else {
                    if (FLEXI_ACCESS) {
                        $canAdd = FAccess::checkUserElementsAccess($user->gmid, 'submit');
                        $not_authorised = !(@$canAdd['content'] || @$canAdd['category']);
                    } else {
                        $canAdd = $user->authorize('com_content', 'add', 'content', 'all');
                        //$canAdd = ($user->gid >= 19);  // At least J1.5 Author
                        $not_authorised = !$canAdd;
                    }
                }
            }
            // Check if Content Type can be created by current user
            if (empty($canCreateType)) {
                if ($new_typeid) {
                    $canCreateType = $model->canCreateType(array($new_typeid));
                    // Can create given Content Type
                } else {
                    $canCreateType = $model->canCreateType();
                    // Can create at least one Content Type
                }
            }
            $not_authorised = $not_authorised || !$canCreateType;
            // Allow item submission by unauthorized users, ... even guests ...
            if ($allowunauthorize == 2) {
                $allowunauthorize = !$user->guest;
            }
            if ($not_authorised && !$allowunauthorize) {
                if (!$canCreateType) {
                    $type_name = isset($types[$new_typeid]) ? '"' . JText::_($types[$new_typeid]->name) . '"' : JText::_('FLEXI_ANY');
                    $msg = JText::sprintf('FLEXI_NO_ACCESS_CREATE_CONTENT_OF_TYPE', $type_name);
                } else {
                    $msg = JText::_('FLEXI_ALERTNOTAUTH_CREATE');
                }
            } else {
                if ($max_auth_limit) {
                    $db->setQuery('SELECT COUNT(id) FROM #__content WHERE created_by = ' . $user->id);
                    $authored_count = $db->loadResult();
                    $content_is_limited = $authored_count >= $max_auth_limit;
                    $msg = $content_is_limited ? JText::sprintf('FLEXI_ALERTNOTAUTH_CREATE_MORE', $max_auth_limit) : '';
                }
            }
            if ($not_authorised && !$allowunauthorize || @$content_is_limited) {
                // User isn't authorize to add ANY content
                if ($notauth_menu = $app->getMenu()->getItem($notauth_itemid)) {
                    // a. custom unauthorized submission page via menu item
                    $internal_link_vars = @$notauth_menu->component ? '&Itemid=' . $notauth_itemid . '&option=' . $notauth_menu->component : '';
                    $notauthurl = JRoute::_($notauth_menu->link . $internal_link_vars, false);
                    JError::raiseNotice(403, $msg);
                    $app->redirect($notauthurl);
                } else {
                    if ($unauthorized_page) {
                        // b. General unauthorized page via global configuration
                        JError::raiseNotice(403, $msg);
                        $app->redirect($unauthorized_page);
                    } else {
                        // c. Finally fallback to raising a 403 Exception/Error that will redirect to site's default 403 unauthorized page
                        if (FLEXI_J16GE) {
                            throw new Exception($msg, 403);
                        } else {
                            JError::raiseError(403, $msg);
                        }
                    }
                }
            }
        }
        // *********************************************
        // Get more variables to push into the FORM view
        // *********************************************
        // Get available types and the currently selected/requested type
        $types = $model->getTypeslist();
        $typesselected = $model->getTypesselected();
        // Create the type parameters
        $tparams = $this->get('Typeparams');
        $tparams = FLEXI_J16GE ? new JRegistry($tparams) : new JParameter($tparams);
        // Merge item parameters, or type/menu parameters for new item
        if ($isnew) {
            if ($new_typeid) {
                $params->merge($tparams);
            }
            // Apply type configuration if it type is set
            if ($menu) {
                $params->merge($menu_params);
            }
            // Apply menu configuration if it menu is set, to override type configuration
        } else {
            $params = $item->parameters;
        }
        // Check if saving an item that translates an original content in site's default language
        $is_content_default_lang = substr(flexicontent_html::getSiteDefaultLang(), 0, 2) == substr($item->language, 0, 2);
        $modify_untraslatable_values = $enable_translation_groups && !$is_content_default_lang && $item->lang_parent_id && $item->lang_parent_id != $item->id;
        // *****************************************************************************
        // 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');
        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);
        }
        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 (FLEXI_J16GE) {
                    $is_editable = !$field->valueseditable || $user->authorise('flexicontent.editfieldvalues', 'com_flexicontent.field.' . $field->id);
                } else {
                    if (FLEXI_ACCESS && $user->gid < 25) {
                        $is_editable = !$field->valueseditable || FAccess::checkAllContentAccess('com_content', 'submit', 'users', $user->gmid, 'field', $field->id);
                    } else {
                        $is_editable = 1;
                    }
                }
                if (!$is_editable) {
                    $field->html = '<div class="fc-mssg fc-warning">' . JText::_('FLEXI_NO_ACCESS_LEVEL_TO_EDIT_FIELD') . '</div>';
                } else {
                    if ($modify_untraslatable_values && $field->untranslatable) {
                        $field->html = '<div class="fc-mssg fc-note">' . JText::_('FLEXI_FIELD_VALUE_IS_UNTRANSLATABLE') . '</div>';
                    } else {
                        FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayField', array(&$field, &$item));
                    }
                }
            }
            // c. Create main text field, via calling the display function of the textarea field (will also check for tabs)
            if ($field->field_type == 'maintext') {
                if (isset($item->item_translations)) {
                    $shortcode = substr($item->language, 0, 2);
                    foreach ($item->item_translations as $lang_id => $t) {
                        if ($shortcode == $t->shortcode) {
                            continue;
                        }
                        $field->name = array('jfdata', $t->shortcode, 'text');
                        $field->value[0] = html_entity_decode($t->fields->text->value, ENT_QUOTES, 'UTF-8');
                        FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
                        $t->fields->text->tab_labels = $field->tab_labels;
                        $t->fields->text->html = $field->html;
                        unset($field->tab_labels);
                        unset($field->html);
                    }
                }
                $field->name = 'text';
                // NOTE: We use the text created by the model and not the text retrieved by the CORE plugin code, which maybe overwritten with JoomFish/Falang data
                $field->value[0] = $item->text;
                // do not decode special characters this was handled during saving !
                // Render the field's (form) HTML
                FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
            }
        }
        if ($print_logging_info) {
            $fc_run_times['render_field_html'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // Tags used by the item
        $usedtagsids = $this->get('UsedtagsIds');
        // NOTE: This will normally return the already set versioned value of tags ($item->tags)
        //$usedtagsIds 	= $isnew ? array() : $fields['tags']->value;
        $usedtagsdata = $model->getUsedtagsData($usedtagsids);
        //echo "<br/>usedtagsIds: "; print_r($usedtagsids);
        //echo "<br/>usedtags (data): "; print_r($usedtagsdata);
        // Compatibility for old overriden templates ...
        if (!FLEXI_J16GE) {
            $tags = $this->get('Alltags');
            $usedtags = $this->get('UsedtagsIds');
        }
        // Load permissions (used by form template)
        $perms = $this->_getItemPerms($item, $typesselected);
        // Get the edit lists
        $lists = $this->_buildEditLists($perms, $params, $authorparams, $typesselected, $tparams);
        // Get number of subscribers
        $subscribers = $this->get('SubscribersCount');
        // Get menu overridden categories/main category fields
        $menuCats = $this->_getMenuCats($item, $perms, $params);
        // Create submit configuration (for new items) into the session
        $submitConf = $this->_createSubmitConf($item, $perms, $params);
        // Create placement configuration for CORE properties
        $placementConf = $this->_createPlacementConf($fields, $params, $item);
        // Item language related vars
        if (FLEXI_FISH || FLEXI_J16GE) {
            $languages = FLEXIUtilities::getLanguages();
            $itemlang = new stdClass();
            $itemlang->shortcode = substr($item->language, 0, 2);
            $itemlang->name = $languages->{$item->language}->name;
            $itemlang->image = '<img src="' . @$languages->{$item->language}->imgsrc . '" alt="' . $languages->{$item->language}->name . '" />';
        }
        //Load the JEditor object
        $editor = JFactory::getEditor();
        // **********************************************************
        // Calculate a (browser window) page title and a page heading
        // **********************************************************
        // Verify menu item points to current FLEXIcontent object
        if ($menu) {
            $menu_matches = false;
            $view_ok = FLEXI_ITEMVIEW == @$menu->query['view'] || 'article' == @$menu->query['view'];
            $menu_matches = $view_ok;
            //$menu_params = 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 {
            // Calculate default page heading (=called page title in J1.5), which in turn will be document title below !! ...
            $default_heading = !$isnew ? JText::_('FLEXI_EDIT') : JText::_('FLEXI_NEW');
            // Decide to show page heading (=J1.5 page title), there is no need for this in item view
            $show_default_heading = 0;
            // Set both (show_) page_heading / page_title for compatibility of J2.5+ with J1.5 template (and for J1.5 with J2.5 template)
            $params->set('page_title', $default_heading);
            $params->set('page_heading', $default_heading);
            $params->set('show_page_heading', $show_default_heading);
            $params->set('show_page_title', $show_default_heading);
        }
        // ************************************************************
        // Create the document title, by from page title and other data
        // ************************************************************
        // Use the page heading as document title, (already calculated above via 'appropriate' logic ...)
        $doc_title = $params->get('page_title');
        // Check and prepend or append site name
        if (FLEXI_J16GE) {
            // Not available in J1.5
            // Add Site Name to page title
            if ($app->getCfg('sitename_pagetitles', 0) == 1) {
                $doc_title = $app->getCfg('sitename') . " - " . $doc_title;
            } elseif ($app->getCfg('sitename_pagetitles', 0) == 2) {
                $doc_title = $doc_title . " - " . $app->getCfg('sitename');
            }
        }
        // Finally, set document title
        $document->setTitle($doc_title);
        // Add title to pathway
        $pathway = $app->getPathWay();
        $pathway->addItem($doc_title, '');
        // Get pageclass suffix
        $pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx'));
        // Ensure the row data is safe html
        // @TODO: check if this is really required as it conflicts with the escape function in the tmpl
        //JFilterOutput::objectHTMLSafe( $item );
        $this->assign('action', $uri->toString());
        $this->assignRef('item', $item);
        if (FLEXI_J16GE) {
            // most core field are created via calling methods of the form (J2.5)
            $this->assignRef('form', $form);
        }
        if ($enable_translation_groups) {
            $this->assignRef('lang_assocs', $langAssocs);
        }
        if (FLEXI_FISH || FLEXI_J16GE) {
            $this->assignRef('langs', $langs);
        }
        $this->assignRef('params', $params);
        $this->assignRef('lists', $lists);
        $this->assignRef('subscribers', $subscribers);
        $this->assignRef('editor', $editor);
        $this->assignRef('user', $user);
        if (!FLEXI_J16GE) {
            // compatibility old templates
            $this->assignRef('tags', $tags);
            $this->assignRef('usedtags', $usedtags);
        }
        $this->assignRef('usedtagsdata', $usedtagsdata);
        $this->assignRef('fields', $fields);
        $this->assignRef('tparams', $tparams);
        $this->assignRef('perms', $perms);
        $this->assignRef('document', $document);
        $this->assignRef('nullDate', $nullDate);
        $this->assignRef('menuCats', $menuCats);
        $this->assignRef('submitConf', $submitConf);
        $this->assignRef('placementConf', $placementConf);
        $this->assignRef('itemlang', $itemlang);
        $this->assignRef('pageclass_sfx', $pageclass_sfx);
        $this->assign('captcha_errmsg', @$captcha_errmsg);
        $this->assign('captcha_field', @$captcha_field);
        // **************************************************************************************
        // Load a different template file for parameters depending on whether we use FLEXI_ACCESS
        // **************************************************************************************
        if (!FLEXI_J16GE) {
            if (FLEXI_ACCESS) {
                $formparams = new JParameter('', JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_flexicontent' . DS . 'models' . DS . 'item2.xml');
            } else {
                $formparams = new JParameter('', JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_flexicontent' . DS . 'models' . DS . 'item.xml');
            }
        }
        // ****************************************************************
        // SET INTO THE FORM, parameter values for various parameter groups
        // ****************************************************************
        if (!FLEXI_J16GE) {
            // Permissions (Access) Group
            if (!FLEXI_ACCESS) {
                $formparams->set('access', $item->access);
            }
            // Set: (Publication) Details Group
            $created_by = intval($item->created_by) ? intval($item->created_by) : $user->get('id');
            $formparams->set('created_by', $created_by);
            $formparams->set('created_by_alias', $item->created_by_alias);
            $formparams->set('created', JHTML::_('date', $item->created, '%Y-%m-%d %H:%M:%S'));
            $formparams->set('publish_up', JHTML::_('date', $item->publish_up, '%Y-%m-%d %H:%M:%S'));
            if (JHTML::_('date', $item->publish_down, '%Y') <= 1969 || $item->publish_down == $nullDate || empty($item->publish_down)) {
                $formparams->set('publish_down', JText::_('FLEXI_NEVER'));
            } else {
                $formparams->set('publish_down', JHTML::_('date', $item->publish_down, '%Y-%m-%d %H:%M:%S'));
            }
            // Set:  Attributes (parameters) Group, (these are retrieved from the item table column 'attribs')
            // (also contains templates parameters, but we will use these individual for every template ... see below)
            $formparams->loadINI($item->attribs);
            //echo "<pre>"; print_r($formparams->_xml['themes']->_children[0]);  echo "<pre>"; print_r($formparams->_xml['themes']->param[0]); exit;
            foreach ($formparams->_xml['themes']->_children as $i => $child) {
                if (isset($child->_attributes['enableparam']) && !$params->get($child->_attributes['enableparam'])) {
                    unset($formparams->_xml['themes']->_children[$i]);
                    unset($formparams->_xml['themes']->param[$i]);
                }
            }
            // Set: Metadata (parameters) Group
            // NOTE: (2 params from 2 item table columns, and then multiple params from item table column 'metadata')
            $formparams->set('description', $item->metadesc);
            $formparams->set('keywords', $item->metakey);
            if (!empty($item->metadata)) {
                $formparams->loadINI($item->metadata->toString());
            }
            // Now create the sliders object,
            // And also push the Form Parameters object into the template (Template Parameters object is seperate)
            jimport('joomla.html.pane');
            $pane = JPane::getInstance('Sliders');
            //$tabs_pane = JPane::getInstance('Tabs');
            $this->assignRef('pane', $pane);
            //$this->assignRef('tabs_pane'	, $tabs_pane);
            $this->assignRef('formparams', $formparams);
        } else {
            if (JHTML::_('date', $item->publish_down, 'Y') <= 1969 || $item->publish_down == $nullDate) {
                $item->publish_down = JText::_('FLEXI_NEVER');
            }
        }
        // ****************************
        // Handle Template related work
        // ****************************
        // (a) Get the templates structures used to create form fields for template parameters
        $themes = flexicontent_tmpl::getTemplates();
        $tmpls_all = $themes->items;
        // (b) Get Content Type allowed templates
        $allowed_tmpls = $tparams->get('allowed_ilayouts');
        $type_default_layout = $tparams->get('ilayout', 'default');
        if (empty($allowed_tmpls)) {
            $allowed_tmpls = array();
        } else {
            if (!is_array($allowed_tmpls)) {
                $allowed_tmpls = !FLEXI_J16GE ? array($allowed_tmpls) : explode("|", $allowed_tmpls);
            }
        }
        // (c) Add default layout, unless all templates allowed (=array is empty)
        if (count($allowed_tmpls) && !in_array($type_default_layout, $allowed_tmpls)) {
            $allowed_tmpls[] = $type_default_layout;
        }
        // (d) Create array of template data according to the allowed templates for current content type
        if (count($allowed_tmpls)) {
            foreach ($tmpls_all as $tmpl) {
                if (in_array($tmpl->name, $allowed_tmpls)) {
                    $tmpls[] = $tmpl;
                }
            }
        } else {
            $tmpls = $tmpls_all;
        }
        // (e) Apply Template Parameters values into the form fields structures
        foreach ($tmpls as $tmpl) {
            if (FLEXI_J16GE) {
                $jform = new JForm('com_flexicontent.template.item', array('control' => 'jform', 'load_data' => true));
                $jform->load($tmpl->params);
                $tmpl->params = $jform;
                foreach ($tmpl->params->getGroup('attribs') as $field) {
                    $fieldname = $field->__get('fieldname');
                    $value = $item->itemparams->get($fieldname);
                    if (strlen($value)) {
                        $tmpl->params->setValue($fieldname, 'attribs', $value);
                    }
                }
            } else {
                $tmpl->params->loadINI($item->attribs);
            }
        }
        $this->assignRef('tmpls', $tmpls);
        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;
        }
    }