Ejemplo n.º 1
0
 function fetchElement($name, $value, &$node, $control_name)
 {
     $filename = 'components/com_flexicontent/index.html';
     if (file_exists($filename)) {
         $doc =& JFactory::getDocument();
         $fieldName = $control_name . '[' . $name . ']';
         $values = explode(",", $value);
         require_once JPATH_ROOT . DS . "components" . DS . "com_flexicontent" . DS . "classes" . DS . "flexicontent.categories.php";
         $tree = flexicontent_cats::getCategoriesTree();
         $js = "\n\t\t\t\tfunction FLEXIClickCategory(obj) {\n\t\t\t\t\tvalues=new Array();\n\t\t\t\t\tfor(i=0,j=0;i<obj.options.length;i++) {\n\t\t\t\t\t\tif(obj.options[i].selected==true)\n\t\t\t\t\t\t\tvalues[j++] = obj.options[i].value;\n\t\t\t\t\t}\n\t\t\t\t\tvalues = values.concat();\n\t\t\t\t\tdocument.getElementById('a_id').value = values;\n\t\t\t\t}";
         $doc->addScriptDeclaration($js);
         $html = flexicontent_cats::buildcatselect($tree, $fieldName, $values, false, ' onClick="javascript:FLEXIClickCategory(this);" class="inputbox required validate-cid" multiple="multiple" size="8"', true);
         $html .= "\n<input type=\"hidden\" id=\"a_id\" name=\"{$fieldName}\" value=\"{$value}\" />";
         return $html;
     } else {
         echo "";
     }
 }
Ejemplo n.º 2
0
 public static function decideCats(&$params)
 {
     global $globalcats;
     $display_cat_list = $params->get('display_cat_list', 0);
     $catids = $params->get('catids', array());
     $usesubcats = $params->get('usesubcats', 0);
     // FIND categories to display
     $allowed_cats = $disallowed_cats = false;
     if ($usesubcats) {
         // Find descendants of the categories
         $subcats = array();
         foreach ($catids as $catid) {
             $subcats = array_merge($subcats, array_map('trim', explode(",", $globalcats[$catid]->descendants)));
         }
         $catids = array_unique($subcats);
     }
     if ($display_cat_list == 1) {
         // include method
         $allowed_cats = $catids;
     } else {
         if ($display_cat_list == 2) {
             // exclude method
             $disallowed_cats = $catids;
         }
     }
     $tree = flexicontent_cats::getCategoriesTree();
     if ($allowed_cats) {
         foreach ($allowed_cats as $catid) {
             $allowedtree[$catid] = $tree[$catid];
         }
     }
     if ($disallowed_cats) {
         foreach ($disallowed_cats as $catid) {
             unset($tree[$catid]);
         }
         $allowedtree =& $tree;
     }
     if (!$allowed_cats && !$disallowed_cats) {
         $allowedtree =& $tree;
     }
     return $allowedtree;
 }
Ejemplo n.º 3
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');
     //echo '<html>  <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <body>';
     // Initialize variables
     $app = JFactory::getApplication();
     $db = JFactory::getDBO();
     $user = JFactory::getUser();
     $config = JFactory::getConfig();
     $session = JFactory::getSession();
     $task = JRequest::getVar('task');
     $ctrl_task = 'task=items.';
     // *********************
     // Get data from request
     // *********************
     // 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
     // Set into model: id (needed for loading correct item), and type id (e.g. needed for getting correct type parameters for new items)
     $data_id = (int) $data['id'];
     $isnew = $data_id == 0;
     // If new make sure that type id is set too, before creating the model
     if ($isnew) {
         $typeid = JRequest::setvar('typeid', (int) @$data['type_id']);
     }
     // Get the model
     $model = $this->getModel('item');
     $model->setId($data_id);
     // Make sure id is correct
     // Get some flags this will also trigger item loading if not already loaded
     $isOwner = $model->get('created_by') == $user->get('id');
     // Get merged parameters: component, type, menu (FE)
     $params = new JRegistry();
     $model_params = $model->getComponentTypeParams();
     $params->merge($model_params);
     // Unique id for new items, needed by some fields for temporary data
     $unique_tmp_itemid = JRequest::getVar('unique_tmp_itemid');
     // Auto title for some content types
     if ($params->get('auto_title', 0)) {
         $data['title'] = (int) $data['id'];
     }
     // item id or ZERO for new items
     // *************************************
     // ENFORCE can change category ACL perms
     // *************************************
     $perms = FlexicontentHelperPerm::getPerm();
     // Per content type change category permissions
     $current_type_id = $isnew || !$model->get('type_id') ? (int) @$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);
     $AutoApproveChanges = $perms->AutoApproveChanges;
     $enable_featured_cid_selector = $perms->MultiCat && $CanChangeFeatCat;
     $enable_cid_selector = $perms->MultiCat && $CanChangeSecCat;
     $enable_catid_selector = $isnew && !$params->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);
         $disabled_cats = $params->get('featured_cats_parent_disable', 1) ? array($featured_cats_parent) : array();
         $featured_cid = array();
         if (!$isnew) {
             foreach ($model->get('categories') as $item_cat) {
                 if (isset($featured_tree[$item_cat]) && !isset($disabled_cats[$item_cat])) {
                     $featured_cid[] = $item_cat;
                 }
             }
         }
         $data['featured_cid'] = $featured_cid;
     }
     // Enforce maintaining secondary categories
     if (!$enable_cid_selector) {
         if ($isnew) {
             $data['cid'] = $params->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 && $params->get('catid_default')) {
             $data['catid'] = $params->get('catid_default');
         } else {
             if ($model->get('catid')) {
                 $data['catid'] = $model->get('catid');
             }
         }
     }
     // **************************
     // Basic Form data validation
     // **************************
     // Get the JForm object, but do not pass any data we only want the form object,
     // in order to validate the data and not create a filled-in form
     $form = $model->getForm();
     // Validate Form data for core fields and for parameters
     $post = $model->validate($form, $data);
     // Check for validation error
     if (!$post) {
         // Get the validation messages and push up to three validation messages out to the user
         $errors = $form->getErrors();
         for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
             $app->enqueueMessage($errors[$i] instanceof Exception ? $errors[$i]->getMessage() : $errors[$i], 'error');
         }
         // Set POST form date into the session, so that they get reloaded
         $app->setUserState($form->option . '.edit.' . $form->context . '.data', $data);
         // Save the jform data in the session
         $app->setUserState($form->option . '.edit.' . $form->context . '.custom', $custom);
         // Save the custom fields data in the session
         $app->setUserState($form->option . '.edit.' . $form->context . '.jfdata', $jfdata);
         // Save the falang translations into the session
         $app->setUserState($form->option . '.edit.' . $form->context . '.unique_tmp_itemid', $unique_tmp_itemid);
         // Save temporary unique item id into the session
         // Redirect back to the item form
         $this->setRedirect($_SERVER['HTTP_REFERER']);
         if (JRequest::getVar('fc_doajax_submit')) {
             echo flexicontent_html::get_system_messages_html();
             exit;
             // Ajax submit, do not rerender the view
         }
         return false;
         //die('error');
     }
     // 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'];
     if (!empty($data['layouts'][$ilayout])) {
         //echo "<pre>"; print_r($post['attribs']);
         //$post['attribs'] = array_merge($post['attribs'], $data['layouts'][$ilayout]);
         $post['attribs']['layouts'] = $data['layouts'];
         //echo "<pre>"; print_r($post['attribs']); 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();
     // Make sure Content ID in the REQUEST is set, this is needed in BACKEND, needed in some cases
     // NOTE this is not the same as jform['cid'] which is the category IDs of the Content Item
     JRequest::setVar('cid', array($model->getId()), 'post', 'array');
     // ********************************************************************************
     // 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 ...
     // ********************************************************************************
     $itemAccess = $model->getItemAccess();
     $canAdd = $itemAccess->get('access-create');
     // includes check of creating in at least one category
     $canEdit = $itemAccess->get('access-edit');
     // includes privileges edit and edit-own
     $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 CREATE / EDIT privileges on current content item
     // *****************************************************************
     $hasCoupon = false;
     // Normally used in frontend only
     if (!$isnew) {
         // If no edit privilege, check if item is editable till logoff
         if (!$canEdit) {
             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')];
                 $hasCoupon = isset($rendered_uneditable[$model->get('id')]) && $rendered_uneditable[$model->get('id')] == 2;
                 // editable via coupon
             }
         }
     } else {
         // No special CREATE allowing case for backend
     }
     // New item: check if user can create in at least one category
     if ($isnew && !$canAdd) {
         JError::raiseWarning(403, JText::_('FLEXI_NO_ACCESS_CREATE'));
         $this->setRedirect($_SERVER['HTTP_REFERER']);
         if (JRequest::getVar('fc_doajax_submit')) {
             echo flexicontent_html::get_system_messages_html();
             exit;
             // Ajax submit, do not rerender the view
         }
         return;
     }
     // Existing item: Check if user can edit current item
     if (!$isnew && !$canEdit) {
         JError::raiseWarning(403, JText::_('FLEXI_NO_ACCESS_EDIT'));
         $this->setRedirect($_SERVER['HTTP_REFERER']);
         if (JRequest::getVar('fc_doajax_submit')) {
             echo flexicontent_html::get_system_messages_html();
             exit;
             // Ajax submit, do not rerender the view
         }
         return;
     }
     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';
         JError::raiseWarning(403, $msg);
         $this->setRedirect($_SERVER['HTTP_REFERER']);
         if (JRequest::getVar('fc_doajax_submit')) {
             echo flexicontent_html::get_system_messages_html();
             exit;
             // Ajax submit, do not rerender the view
         }
         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());
         // Set POST form date into the session, so that they get reloaded
         $app->setUserState($form->option . '.edit.' . $form->context . '.data', $data);
         // Save the jform data in the session
         $app->setUserState($form->option . '.edit.' . $form->context . '.custom', $custom);
         // Save the custom fields data in the session
         $app->setUserState($form->option . '.edit.' . $form->context . '.jfdata', $jfdata);
         // Save the falang translations into the session
         $app->setUserState($form->option . '.edit.' . $form->context . '.unique_tmp_itemid', $unique_tmp_itemid);
         // Save temporary unique item id into the session
         // Saving has failed check-in and redirect back to the item form,
         // redirect back to the item form reloading the posted data
         $model->checkin();
         $this->setRedirect($_SERVER['HTTP_REFERER']);
         if (JRequest::getVar('fc_doajax_submit')) {
             echo flexicontent_html::get_system_messages_html();
             exit;
             // Ajax submit, do not rerender the view
         }
         return;
         //die('save error');
     }
     // **************************************************
     // 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) || $hasCoupon;
     // ********************************************************************************************
     // 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 && !$AutoApproveChanges;
         $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
     // ***************************************************
     $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');
     // ****************************************************************************************************************************
     // 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
     // ****************************************************************************************************************************
     $asset = 'com_content.article.' . $model->get('id');
     $canEdit = $user->authorise('core.edit', $asset) || $user->authorise('core.edit.own', $asset) && $isOwner;
     // 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) && $isOwner) ;
     // *******************************************************************************************************
     // Check if user can not edit item further (due to changed main category, without edit/editown permission)
     // *******************************************************************************************************
     if (!$canEdit) {
         if ($task == 'apply' || $task == 'apply_type') {
             // APPLY TASK: Temporarily set item to be editable till closing it and not through all session
             // (we will/should clear this flag when item is closed, since we have another flag to indicate new items
             $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' && $task != 'apply_type' && $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
     // ****************************************
     switch ($task) {
         case 'apply':
         case 'apply_type':
             $link = 'index.php?option=com_flexicontent&' . $ctrl_task . 'edit&cid=' . (int) $model->get('id');
             break;
         case 'saveandnew':
             $link = $type_id ? 'index.php?option=com_flexicontent&view=item&typeid=' . $type_id : 'index.php?option=com_flexicontent&view=item';
             break;
         default:
             $link = 'index.php?option=com_flexicontent&view=items';
             break;
     }
     $msg = JText::_('FLEXI_ITEM_SAVED');
     $this->setRedirect($link, $msg);
     if (JRequest::getVar('fc_doajax_submit')) {
         JFactory::getApplication()->enqueueMessage($msg, 'message');
         echo flexicontent_html::get_system_messages_html();
         exit;
         // Ajax submit, do not rerender the view
     }
 }
Ejemplo n.º 4
0
    /**
     * Creates the HTML of various form fields used in the item edit form
     *
     * @since 1.0
     */
    function _buildEditLists(&$perms, &$params, &$authorparams)
    {
        $db = JFactory::getDBO();
        $user = JFactory::getUser();
        // get current user
        $item = $this->get('Item');
        // get the item from the model
        $document = JFactory::getDocument();
        $session = JFactory::getSession();
        global $globalcats;
        $categories = $globalcats;
        // get the categories tree
        $types = $this->get('Typeslist');
        $typesselected = $this->get('Typesselected');
        $subscribers = $this->get('SubscribersCount');
        $isnew = !$item->id;
        // *******************************
        // Get categories used by the item
        // *******************************
        if ($isnew) {
            // Case for preselected main category for new items
            $maincat = $item->catid ? $item->catid : JRequest::getInt('maincat', 0);
            if ($maincat) {
                $selectedcats = array($maincat);
                $item->catid = $maincat;
            } else {
                $selectedcats = array();
            }
            if ($params->get('cid_default')) {
                $selectedcats = $params->get('cid_default');
            }
            if ($params->get('catid_default')) {
                $item->catid = $params->get('catid_default');
            }
        } else {
            // NOTE: This will normally return the already set versioned value of categories ($item->categories)
            $selectedcats = $this->get('Catsselected');
        }
        // *********************************************************************************************
        // Build select lists for the form field. Only few of them are used in J1.6+, since we will use:
        // (a) form XML file to declare them and then (b) getInput() method form field to create them
        // *********************************************************************************************
        // First clean form data, we do this after creating the description field which may contain HTML
        JFilterOutput::objectHTMLSafe($item, ENT_QUOTES);
        flexicontent_html::loadFramework('select2');
        $prettycheckable_added = flexicontent_html::loadFramework('prettyCheckable');
        $lists = array();
        // build state list
        $non_publishers_stategrp = $perms['isSuperAdmin'] || $item->state == -3 || $item->state == -4;
        $special_privelege_stategrp = $item->state == 2 || $perms['canarchive'] || ($item->state == -2 || $perms['candelete']);
        $state = array();
        // Using <select> groups
        if ($non_publishers_stategrp || $special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_PUBLISHERS_WORKFLOW_STATES'));
        }
        $state[] = JHTML::_('select.option', 1, JText::_('FLEXI_PUBLISHED'));
        $state[] = JHTML::_('select.option', 0, JText::_('FLEXI_UNPUBLISHED'));
        $state[] = JHTML::_('select.option', -5, JText::_('FLEXI_IN_PROGRESS'));
        // States reserved for workflow
        if ($non_publishers_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_NON_PUBLISHERS_WORKFLOW_STATES'));
        }
        if ($item->state == -3 || $perms['isSuperAdmin']) {
            $state[] = JHTML::_('select.option', -3, JText::_('FLEXI_PENDING'));
        }
        if ($item->state == -4 || $perms['isSuperAdmin']) {
            $state[] = JHTML::_('select.option', -4, JText::_('FLEXI_TO_WRITE'));
        }
        // Special access states
        if ($special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_SPECIAL_ACTION_STATES'));
        }
        if ($item->state == 2 || $perms['canarchive']) {
            $state[] = JHTML::_('select.option', 2, JText::_('FLEXI_ARCHIVED'));
        }
        if ($item->state == -2 || $perms['candelete']) {
            $state[] = JHTML::_('select.option', -2, JText::_('FLEXI_TRASHED'));
        }
        // Close last <select> group
        if ($non_publishers_stategrp || $special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
        }
        $class = 'use_select2_lib';
        $attribs = 'class="' . $class . '"';
        $lists['state'] = JHTML::_('select.genericlist', $state, 'jform[state]', $attribs, 'value', 'text', $item->state, 'jform_state');
        if (!FLEXI_J16GE) {
            $lists['state'] = str_replace('<optgroup label="">', '</optgroup>', $lists['state']);
        }
        // *** BOF: J2.5 SPECIFIC SELECT LISTS
        if (FLEXI_J16GE) {
        }
        // *** EOF: J1.5 SPECIFIC SELECT LISTS
        // build version approval list
        $fieldname = 'jform[vstate]';
        $elementid = 'jform_vstate';
        /*
        $options = array();
        $options[] = JHTML::_('select.option',  1, JText::_( 'FLEXI_NO' ) );
        $options[] = JHTML::_('select.option',  2, JText::_( 'FLEXI_YES' ) );
        $attribs = FLEXI_J16GE ? ' style ="float:left!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
        $lists['vstate'] = JHTML::_('select.radiolist', $options, $fieldname, $attribs, 'value', 'text', 2, $elementid);
        */
        $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
        $attribs = ' class="' . $classes . '" ';
        $i = 1;
        $options = array(1 => JText::_('FLEXI_NO'), 2 => JText::_('FLEXI_YES'));
        $lists['vstate'] = '';
        foreach ($options as $option_id => $option_label) {
            $checked = $option_id == 2 ? ' checked="checked"' : '';
            $elementid_no = $elementid . '_' . $i;
            if (!$prettycheckable_added) {
                $lists['vstate'] .= '<label class="fccheckradio_lbl" for="' . $elementid_no . '">';
            }
            $extra_params = !$prettycheckable_added ? '' : ' data-labeltext="' . JText::_($option_label) . '" data-labelPosition="right" data-customClass="fcradiocheck"';
            $lists['vstate'] .= ' <input type="radio" id="' . $elementid_no . '" data-element-grpid="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="' . $option_id . '" ' . $checked . $extra_params . ' />';
            if (!$prettycheckable_added) {
                $lists['vstate'] .= '&nbsp;' . JText::_($option_label) . '</label>';
            }
            $i++;
        }
        // build field for notifying subscribers
        if (!$subscribers) {
            $lists['notify'] = !$isnew ? JText::_('FLEXI_NO_SUBSCRIBERS_EXIST') : '';
        } else {
            // b. Check if notification emails to subscribers , were already sent during current session
            $subscribers_notified = $session->get('subscribers_notified', array(), 'flexicontent');
            if (!empty($subscribers_notified[$item->id])) {
                $lists['notify'] = JText::_('FLEXI_SUBSCRIBERS_ALREADY_NOTIFIED');
            } else {
                // build favs notify field
                $fieldname = 'jform[notify]';
                $elementid = 'jform_notify';
                /*
                $attribs = FLEXI_J16GE ? ' style ="float:none!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
                $lists['notify'] = '<input type="checkbox" name="jform[notify]" id="jform_notify" '.$attribs.' /> '. $lbltxt;
                */
                $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
                $attribs = ' class="' . $classes . '" ';
                $lbltxt = $subscribers . ' ' . JText::_($subscribers > 1 ? 'FLEXI_SUBSCRIBERS' : 'FLEXI_SUBSCRIBER');
                if (!$prettycheckable_added) {
                    $lists['notify'] .= '<label class="fccheckradio_lbl" for="' . $elementid . '">';
                }
                $extra_params = !$prettycheckable_added ? '' : ' data-labeltext="' . $lbltxt . '" data-labelPosition="right" data-customClass="fcradiocheck"';
                $lists['notify'] = ' <input type="checkbox" id="' . $elementid . '" data-element-grpid="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="1" ' . $extra_params . ' checked="checked" />';
                if (!$prettycheckable_added) {
                    $lists['notify'] .= '&nbsp;' . $lbltxt . '</label>';
                }
            }
        }
        // Get author's maximum allowed categories per item and set js limitation
        $max_cat_assign = !$authorparams ? 0 : intval($authorparams->get('max_cat_assign', 0));
        $document->addScriptDeclaration('
			max_cat_assign_fc = ' . $max_cat_assign . ';
			existing_cats_fc  = ["' . implode('","', $selectedcats) . '"];
			max_cat_overlimit_msg_fc = "' . JText::_('FLEXI_TOO_MANY_ITEM_CATEGORIES', true) . '";
		');
        // Creating categorories tree for item assignment, we use the 'create' privelege
        $actions_allowed = array('core.create');
        // Featured categories form field
        $featured_cats_parent = $params->get('featured_cats_parent', 0);
        $featured_cats = array();
        $enable_featured_cid_selector = $perms['multicat'] && $perms['canchange_featcat'];
        if ($featured_cats_parent) {
            $featured_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $featured_cats_parent, $depth_limit = 0);
            $disabled_cats = $params->get('featured_cats_parent_disable', 1) ? array($featured_cats_parent) : array();
            $featured_sel = array();
            foreach ($selectedcats as $item_cat) {
                if (isset($featured_tree[$item_cat])) {
                    $featured_sel[] = $item_cat;
                }
            }
            $class = "use_select2_lib select2_list_selected";
            $attribs = 'class="' . $class . '" multiple="multiple" size="8"';
            $attribs .= $enable_featured_cid_selector ? '' : ' disabled="disabled"';
            $fieldname = 'jform[featured_cid][]';
            $lists['featured_cid'] = ($enable_featured_cid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($featured_tree, $fieldname, $featured_sel, 3, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees = array(), $disable_subtrees = array(), $custom_options = array(), $disabled_cats);
        } else {
            // Do not display, if not configured or not allowed to the user
            $lists['featured_cid'] = false;
        }
        // Multi-category form field, for user allowed to use multiple categories
        $lists['cid'] = '';
        $enable_cid_selector = $perms['multicat'] && $perms['canchange_seccat'];
        if (1) {
            if ($params->get('cid_allowed_parent')) {
                $cid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $params->get('cid_allowed_parent'), $depth_limit = 0);
                $disabled_cats = $params->get('cid_allowed_parent_disable', 1) ? array($params->get('cid_allowed_parent')) : array();
            } else {
                $cid_tree =& $categories;
                $disabled_cats = array();
            }
            // Get author's maximum allowed categories per item and set js limitation
            $max_cat_assign = !$authorparams ? 0 : intval($authorparams->get('max_cat_assign', 0));
            $document->addScriptDeclaration('
				max_cat_assign_fc = ' . $max_cat_assign . ';
				existing_cats_fc  = ["' . implode('","', $selectedcats) . '"];
				max_cat_overlimit_msg_fc = "' . JText::_('FLEXI_TOO_MANY_ITEM_CATEGORIES', true) . '";
			');
            $class = "mcat use_select2_lib select2_list_selected";
            $class .= $max_cat_assign ? " validate-fccats" : " validate";
            $attribs = 'class="' . $class . '" multiple="multiple" size="20"';
            $attribs .= $enable_cid_selector ? '' : ' disabled="disabled"';
            $fieldname = 'jform[cid][]';
            $skip_subtrees = $featured_cats_parent ? array($featured_cats_parent) : array();
            $lists['cid'] = ($enable_cid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($cid_tree, $fieldname, $selectedcats, false, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees, $disable_subtrees = array(), $custom_options = array(), $disabled_cats);
        } else {
            if (count($selectedcats) > 1) {
                foreach ($selectedcats as $catid) {
                    $cat_titles[$catid] = $globalcats[$catid]->title;
                }
                $lists['cid'] .= implode(', ', $cat_titles);
            } else {
                $lists['cid'] = false;
            }
        }
        // Main category form field
        $class = 'scat use_select2_lib';
        if ($perms['multicat']) {
            $class .= ' validate-catid';
        } else {
            $class .= ' required';
        }
        $attribs = 'class="' . $class . '"';
        $fieldname = 'jform[catid]';
        $enable_catid_selector = $isnew && !$params->get('catid_default') || !$isnew && empty($item->catid) || $perms['canchange_cat'];
        if ($params->get('catid_allowed_parent')) {
            $catid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $params->get('catid_allowed_parent'), $depth_limit = 0);
            $disabled_cats = $params->get('catid_allowed_parent_disable', 1) ? array($params->get('catid_allowed_parent')) : array();
        } else {
            $catid_tree =& $categories;
            $disabled_cats = array();
        }
        $lists['catid'] = false;
        if (!empty($catid_tree)) {
            $disabled = $enable_catid_selector ? '' : ' disabled="disabled"';
            $attribs .= $disabled;
            $lists['catid'] = ($enable_catid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($catid_tree, $fieldname, $item->catid, 2, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees = array(), $disable_subtrees = array(), $custom_options = array(), $disabled_cats, $empty_errmsg = JText::_('FLEXI_FORM_NO_MAIN_CAT_ALLOWED'));
        } else {
            if (!$isnew && $item->catid) {
                $lists['catid'] = $globalcats[$item->catid]->title;
            }
        }
        //buid types selectlist
        $class = 'required use_select2_lib';
        $attribs = 'class="' . $class . '"';
        $fieldname = 'jform[type_id]';
        $elementid = 'jform_type_id';
        $lists['type'] = flexicontent_html::buildtypesselect($types, $fieldname, $typesselected->id, 1, $attribs, $elementid, $check_perms = true);
        // build version approval list
        if ($params->get('allowdisablingcomments_fe')) {
            // Set to zero if disabled or to "" (aka use default) for any other value.  THIS WILL FORCE comment field use default Global/Category/Content Type setting or disable it,
            // thus a per item commenting system cannot be selected. This is OK because it makes sense to have a different commenting system per CONTENT TYPE by not per Content Item
            $isdisabled = !$params->get('comments') && strlen($params->get('comments'));
            $fieldvalue = $isdisabled ? 0 : "";
            $fieldname = 'jform[attribs][comments]';
            $elementid = 'jform_attribs_comments';
            /*
            $options = array();
            $options[] = JHTML::_('select.option', "",  JText::_( 'FLEXI_DEFAULT_BEHAVIOR' ) );
            $options[] = JHTML::_('select.option', 0, JText::_( 'FLEXI_DISABLE' ) );
            $attribs = FLEXI_J16GE ? ' style ="float:none!important;" ' : '';
            $lists['disable_comments'] = JHTML::_('select.radiolist', $options, $fieldname, $attribs, 'value', 'text', $fieldvalue, $elementid);
            */
            $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
            $attribs = ' class="' . $classes . '" ';
            $i = 1;
            $options = array("" => JText::_('FLEXI_DEFAULT_BEHAVIOR'), 0 => JText::_('FLEXI_DISABLE'));
            $lists['disable_comments'] = '';
            foreach ($options as $option_id => $option_label) {
                $checked = $option_id === $fieldvalue ? ' checked="checked"' : '';
                $elementid_no = $elementid . '_' . $i;
                if (!$prettycheckable_added) {
                    $lists['disable_comments'] .= '<label class="fccheckradio_lbl" for="' . $elementid_no . '">';
                }
                $extra_params = !$prettycheckable_added ? '' : ' data-labeltext="' . JText::_($option_label) . '" data-labelPosition="right" data-customClass="fcradiocheck"';
                $lists['disable_comments'] .= ' <input type="radio" id="' . $elementid_no . '" data-element-grpid="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="' . $option_id . '" ' . $checked . $extra_params . ' />';
                if (!$prettycheckable_added) {
                    $lists['disable_comments'] .= '&nbsp;' . JText::_($option_label) . '</label>';
                }
                $i++;
            }
        }
        // find user's allowed languages
        $allowed_langs = !$authorparams ? null : $authorparams->get('langs_allowed', null);
        $allowed_langs = !$allowed_langs ? null : FLEXIUtilities::paramToArray($allowed_langs);
        if (!$isnew && $allowed_langs) {
            $allowed_langs[] = $item->language;
        }
        // find globaly or per content type disabled languages
        $disable_langs = $params->get('disable_languages_fe', array());
        // Build languages list
        if (FLEXI_J16GE || FLEXI_FISH) {
            $item_lang = $item->language;
            // Model has already set default language according to parameters
            $langdisplay = $params->get('langdisplay_fe', 2);
            $langconf = array();
            $langconf['flags'] = $params->get('langdisplay_flags_fe', 1);
            $langconf['texts'] = $params->get('langdisplay_texts_fe', 1);
            $field_attribs = $langdisplay == 2 ? 'class="use_select2_lib"' : '';
            $lists['languages'] = flexicontent_html::buildlanguageslist('jform[language]', $field_attribs, $item->language, $langdisplay, $allowed_langs, $published_only = 1, $disable_langs, $add_all = true, $langconf);
        }
        return $lists;
    }
Ejemplo n.º 5
0
    /**
     * Creates the item page
     *
     * @since 1.0
     */
    function display($tpl = null)
    {
        // ********************************
        // Initialize variables, flags, etc
        // ********************************
        global $globalcats;
        $categories = $globalcats;
        $app = JFactory::getApplication();
        $dispatcher = JDispatcher::getInstance();
        $document = JFactory::getDocument();
        $config = JFactory::getConfig();
        $session = JFactory::getSession();
        $user = JFactory::getUser();
        $db = JFactory::getDBO();
        $option = JRequest::getVar('option');
        $nullDate = $db->getNullDate();
        // Get the COMPONENT only parameters
        // Get component parameters
        $params = new JRegistry();
        $cparams = JComponentHelper::getParams('com_flexicontent');
        $params->merge($cparams);
        $params = clone JComponentHelper::getParams('com_flexicontent');
        // Some flags
        $enable_translation_groups = flexicontent_db::useAssociations();
        //$params->get("enable_translation_groups");
        $print_logging_info = $params->get('print_logging_info');
        if ($print_logging_info) {
            global $fc_run_times;
        }
        // *****************
        // Load JS/CSS files
        // *****************
        // Add css to document
        $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontentbackend.css', FLEXI_VERSION);
        $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/j3x.css', FLEXI_VERSION);
        // Fields common CSS
        $document->addStyleSheetVersion(JURI::root(true) . '/components/com_flexicontent/assets/css/flexi_form_fields.css', FLEXI_VERSION);
        // Add JS frameworks
        flexicontent_html::loadFramework('select2');
        $prettycheckable_added = flexicontent_html::loadFramework('prettyCheckable');
        flexicontent_html::loadFramework('flexi-lib');
        // Add js function to overload the joomla submitform validation
        JHTML::_('behavior.formvalidation');
        // load default validation JS to make sure it is overriden
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/admin.js', FLEXI_VERSION);
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/validate.js', FLEXI_VERSION);
        // Add js function for custom code used by FLEXIcontent item form
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/itemscreen.js', FLEXI_VERSION);
        // ***********************
        // Get data from the model
        // ***********************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $model = $this->getModel();
        $item = $model->getItem();
        $form = $this->get('Form');
        if ($print_logging_info) {
            $fc_run_times['get_item_data'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // ***************************
        // Get Associated Translations
        // ***************************
        if ($enable_translation_groups) {
            $langAssocs = $this->get('LangAssocs');
        }
        $langs = FLEXIUtilities::getLanguages('code');
        // Get item id and new flag
        $cid = $model->getId();
        $isnew = !$cid;
        // Create and set a unique item id for plugins that needed it
        if ($cid) {
            $unique_tmp_itemid = $cid;
        } else {
            $unique_tmp_itemid = $app->getUserState('com_flexicontent.edit.item.unique_tmp_itemid');
            $unique_tmp_itemid = $unique_tmp_itemid ? $unique_tmp_itemid : date('_Y_m_d_h_i_s_', time()) . uniqid(true);
        }
        //print_r($unique_tmp_itemid);
        JRequest::setVar('unique_tmp_itemid', $unique_tmp_itemid);
        // Get number of subscribers
        $subscribers = $model->getSubscribersCount();
        // ******************
        // Version Panel data
        // ******************
        // Get / calculate some version related variables
        $versioncount = $model->getVersionCount();
        $versionsperpage = $params->get('versionsperpage', 10);
        $pagecount = (int) ceil($versioncount / $versionsperpage);
        // Data need by version panel: (a) current version page, (b) currently active version
        $current_page = 1;
        $k = 1;
        $allversions = $model->getVersionList();
        foreach ($allversions as $v) {
            if ($k > 1 && ($k - 1) % $versionsperpage == 0) {
                $current_page++;
            }
            if ($v->nr == $item->version) {
                break;
            }
            $k++;
        }
        // Finally fetch the version data for versions in current page
        $versions = $model->getVersionList(($current_page - 1) * $versionsperpage, $versionsperpage);
        // Create display of average rating
        $ratings = $model->getRatingDisplay();
        // *****************
        // Type related data
        // *****************
        // Get available types and the currently selected/requested type
        $types = $model->getTypeslist();
        $typesselected = $model->getTypesselected();
        // Get and merge type parameters
        $tparams = $this->get('Typeparams');
        $tparams = new JRegistry($tparams);
        $params->merge($tparams);
        // Apply type configuration if it type is set
        // Get user allowed permissions on the item ... to be used by the form rendering
        // Also hide parameters panel if user can not edit parameters
        $perms = $this->_getItemPerms($item);
        if (!$perms['canparams']) {
            $document->addStyleDeclaration('#details-options {display:none;}');
        }
        // ******************
        // Create the toolbar
        // ******************
        $toolbar = JToolBar::getInstance('toolbar');
        $tip_class = FLEXI_J30GE ? ' hasTooltip' : ' hasTip';
        // SET toolbar title
        if ($cid) {
            JToolBarHelper::title(JText::_('FLEXI_EDIT_ITEM'), 'itemedit');
            // Editing existing item
        } else {
            JToolBarHelper::title(JText::_('FLEXI_NEW_ITEM'), 'itemadd');
            // Creating new item
        }
        // **************
        // Common Buttons
        // **************
        // Applying new item type is a special case that has not loaded custom fieds yet
        JToolBarHelper::apply($item->type_id ? 'items.apply' : 'items.apply_type', !$isnew ? 'FLEXI_APPLY' : ($typesselected->id ? 'FLEXI_ADD' : 'FLEXI_APPLY_TYPE'), false);
        /*if (!$isnew || $item->version) flexicontent_html::addToolBarButton(
        		'FLEXI_FAST_APPLY', $btn_name='apply_ajax', $full_js="Joomla.submitbutton('items.apply_ajax')", $msg_alert='', $msg_confirm='',
        		$btn_task='items.apply_ajax', $extra_js='', $btn_list=false, $btn_menu=true, $btn_confirm=false, $btn_class="".$tip_class, $btn_icon="icon-loop",
        		'data-placement="bottom" title="Fast saving, without reloading the form. <br/><br/>Note: new files will not be uploaded, <br/>- in such a case please use \'Apply\'"');*/
        if (!$isnew || $item->version) {
            JToolBarHelper::save('items.save');
        }
        if (!$isnew || $item->version) {
            JToolBarHelper::custom('items.saveandnew', 'savenew.png', 'savenew.png', 'FLEXI_SAVE_AND_NEW', false);
        }
        JToolBarHelper::cancel('items.cancel');
        // ***********************
        // Add a preview button(s)
        // ***********************
        //$_sh404sef = JPluginHelper::isEnabled('system', 'sh404sef') && $config->get('sef');
        $_sh404sef = defined('SH404SEF_IS_RUNNING') && $config->get('sef');
        if ($cid) {
            // Domain URL and autologin vars
            $server = JURI::getInstance()->toString(array('scheme', 'host', 'port'));
            $autologin = '';
            //$params->get('autoflogin', 1) ? '&fcu='.$user->username . '&fcp='.$user->password : '';
            // Check if we are in the backend, in the back end we need to set the application to the site app instead
            // we do not remove 'isAdmin' check so that we can copy later without change, e.g. to a plugin
            $isAdmin = JFactory::getApplication()->isAdmin();
            if ($isAdmin && !$_sh404sef) {
                JFactory::$application = JApplication::getInstance('site');
            }
            // Create the URL
            $item_url = FlexicontentHelperRoute::getItemRoute($item->id . ':' . $item->alias, $categories[$item->catid]->slug) . ($item->language != '*' ? '&lang=' . substr($item->language, 0, 2) : '');
            $item_url = $_sh404sef ? Sh404sefHelperGeneral::getSefFromNonSef($item_url, $fullyQualified = true, $xhtml = false, $ssl = null) : JRoute::_($item_url);
            // Check if we are in the backend again
            // In backend we need to remove administrator from URL as it is added even though we've set the application to the site app
            if ($isAdmin && !$_sh404sef) {
                $admin_folder = str_replace(JURI::root(true), '', JURI::base(true));
                $item_url = str_replace($admin_folder . '/', '/', $item_url);
                // Restore application
                JFactory::$application = JApplication::getInstance('administrator');
            }
            $previewlink = $item_url . (strstr($item_url, '?') ? '&amp;' : '?') . 'preview=1' . $autologin;
            //$previewlink     = str_replace('&amp;', '&', $previewlink);
            //$previewlink = JRoute::_(JURI::root() . FlexicontentHelperRoute::getItemRoute($item->id.':'.$item->alias, $categories[$item->catid]->slug)) .$autologin;
            // PREVIEW for latest version
            if (!$params->get('use_versioning', 1) || $item->version == $item->current_version && $item->version == $item->last_version) {
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small btn-info spaced-btn" onClick="window.open(\'' . $previewlink . '\');"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('Preview') . '</button>', 'preview');
            } else {
                // Add a preview button for (currently) LOADED version of the item
                $previewlink_loaded_ver = $previewlink . '&version=' . $item->version;
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small" onClick="window.open(\'' . $previewlink_loaded_ver . '\');" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('FLEXI_PREVIEW_FORM_LOADED_VERSION') . ' [' . $item->version . ']</button>', 'preview');
                // Add a preview button for currently ACTIVE version of the item
                $previewlink_active_ver = $previewlink . '&version=' . $item->current_version;
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small" onClick="window.open(\'' . $previewlink_active_ver . '\');" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('FLEXI_PREVIEW_FRONTEND_ACTIVE_VERSION') . ' [' . $item->current_version . ']</button>', 'preview');
                // Add a preview button for currently LATEST version of the item
                $previewlink_last_ver = $previewlink;
                //'&version='.$item->last_version;
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small" onClick="window.open(\'' . $previewlink_last_ver . '\');" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('FLEXI_PREVIEW_LATEST_SAVED_VERSION') . ' [' . $item->last_version . ']</button>', 'preview');
            }
            JToolBarHelper::spacer();
            JToolBarHelper::divider();
            JToolBarHelper::spacer();
        }
        // ************************
        // Add modal layout editing
        // ************************
        if ($perms['cantemplates']) {
            JToolBarHelper::divider();
            if (!$isnew || $item->version) {
                flexicontent_html::addToolBarButton('FLEXI_EDIT_LAYOUT', $btn_name = 'apply_ajax', $full_js = "var url = jQuery(this).attr('data-href'); fc_showDialog(url, 'fc_modal_popup_container'); return false;", $msg_alert = '', $msg_confirm = '', $btn_task = 'items.apply_ajax', $extra_js = '', $btn_list = false, $btn_menu = true, $btn_confirm = false, $btn_class = "btn-info" . $tip_class, $btn_icon = "icon-pencil", 'data-placement="bottom" data-href="index.php?option=com_flexicontent&amp;view=template&amp;type=items&amp;tmpl=component&amp;ismodal=1&amp;folder=' . $item->itemparams->get('ilayout', $tparams->get('ilayout', 'default')) . '" title="Edit the display layout of this item. <br/><br/>Note: this layout maybe assigned to content types or other items, thus changing it will effect them too"');
            }
        }
        // Check if saving an item that translates an original content in site's default language
        $site_default = substr(flexicontent_html::getSiteDefaultLang(), 0, 2);
        $is_content_default_lang = $site_default == substr($item->language, 0, 2);
        // *****************************************************************************
        // Get (CORE & CUSTOM) fields and their VERSIONED values and then
        // (a) Apply Content Type Customization to CORE fields (label, description, etc)
        // (b) Create the edit html of the CUSTOM fields by triggering 'onDisplayField'
        // *****************************************************************************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $fields = $this->get('Extrafields');
        $item->fields =& $fields;
        if ($print_logging_info) {
            $fc_run_times['get_field_vals'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $jcustom = $app->getUserState('com_flexicontent.edit.item.custom');
        //print_r($jcustom);
        foreach ($fields as $field) {
            // a. Apply CONTENT TYPE customizations to CORE FIELDS, e.g a type specific label & description
            // NOTE: the field parameters are already created so there is not need to call this for CUSTOM fields, which do not have CONTENT TYPE customizations
            if ($field->iscore) {
                FlexicontentFields::loadFieldConfig($field, $item);
            }
            // b. Create field 's editing HTML (the form field)
            // NOTE: this is DONE only for CUSTOM fields, since form field html is created by the form for all CORE fields, EXCEPTION is the 'text' field (see bellow)
            if (!$field->iscore) {
                if (isset($jcustom[$field->name])) {
                    $field->value = array();
                    foreach ($jcustom[$field->name] as $i => $_val) {
                        $field->value[$i] = $_val;
                    }
                }
                $is_editable = !$field->valueseditable || $user->authorise('flexicontent.editfieldvalues', 'com_flexicontent.field.' . $field->id);
                if ($is_editable) {
                    FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayField', array(&$field, &$item));
                    if ($field->untranslatable) {
                        $field->html = (!isset($field->html) ? '<div class="fc-mssg-inline fc-warning" style="margin:0 4px 6px 4px; max-width: unset;">' . JText::_('FLEXI_PLEASE_PUBLISH_THIS_PLUGIN') . '</div><div class="clear"></div>' : '') . '<div class="alert alert-info fc-small fc-iblock" style="margin:0 4px 6px 4px; max-width: unset;">' . JText::_('FLEXI_FIELD_VALUE_IS_NON_TRANSLATABLE') . '</div>' . "\n" . (isset($field->html) ? '<div class="clear"></div>' . $field->html : '');
                    }
                } else {
                    if ($field->valueseditable == 1) {
                        $field->html = '<div class="fc-mssg fc-note">' . JText::_($field->parameters->get('no_acc_msg_form') ? $field->parameters->get('no_acc_msg_form') : 'FLEXI_NO_ACCESS_LEVEL_TO_EDIT_FIELD') . '</div>';
                    } else {
                        if ($field->valueseditable == 2) {
                            FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayFieldValue', array(&$field, $item));
                            $field->html = '<div class="fc-mssg fc-note">' . JText::_($field->parameters->get('no_acc_msg_form') ? $field->parameters->get('no_acc_msg_form') : 'FLEXI_NO_ACCESS_LEVEL_TO_EDIT_FIELD') . '</div>' . "\n" . $field->display;
                        } else {
                            if ($field->valueseditable == 3) {
                                FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayFieldValue', array(&$field, $item));
                                $field->html = $field->display;
                            } else {
                                if ($field->valueseditable == 4) {
                                    $field->html = '';
                                    $field->formhidden = 4;
                                }
                            }
                        }
                    }
                }
            }
            // c. Create main text field, via calling the display function of the textarea field (will also check for tabs)
            if ($field->field_type == 'maintext') {
                if (isset($item->item_translations)) {
                    $shortcode = substr($item->language, 0, 2);
                    foreach ($item->item_translations as $lang_id => $t) {
                        if ($shortcode == $t->shortcode) {
                            continue;
                        }
                        $field->name = array('jfdata', $t->shortcode, 'text');
                        $field->value[0] = html_entity_decode($t->fields->text->value, ENT_QUOTES, 'UTF-8');
                        FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
                        $t->fields->text->tab_labels = $field->tab_labels;
                        $t->fields->text->html = $field->html;
                        unset($field->tab_labels);
                        unset($field->html);
                    }
                }
                $field->name = 'text';
                // NOTE: We use the text created by the model and not the text retrieved by the CORE plugin code, which maybe overwritten with JoomFish/Falang data
                $field->value[0] = $item->text;
                // do not decode special characters this was handled during saving !
                // Render the field's (form) HTML
                FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
            }
        }
        if ($print_logging_info) {
            $fc_run_times['render_field_html'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // *************************
        // Get tags used by the item
        // *************************
        $usedtagsIds = $this->get('UsedtagsIds');
        // NOTE: This will normally return the already set versioned value of tags ($item->tags)
        $usedtags = $model->getUsedtagsData($usedtagsIds);
        // *******************************
        // Get categories used by the item
        // *******************************
        if ($isnew) {
            // Case for preselected main category for new items
            $maincat = $item->catid ? $item->catid : JRequest::getInt('maincat', 0);
            if (!$maincat) {
                $maincat = $app->getUserStateFromRequest($option . '.items.filter_cats', 'filter_cats', '', 'int');
            }
            if ($maincat) {
                $selectedcats = array($maincat);
                $item->catid = $maincat;
            } else {
                $selectedcats = array();
            }
            if ($tparams->get('cid_default')) {
                $selectedcats = $tparams->get('cid_default');
            }
            if ($tparams->get('catid_default')) {
                $item->catid = $tparams->get('catid_default');
            }
        } else {
            // NOTE: This will normally return the already set versioned value of categories ($item->categories)
            $selectedcats = $this->get('Catsselected');
        }
        //$selectedcats 	= $isnew ? array() : $fields['categories']->value;
        //echo "<br/>row->tags: "; print_r($item->tags);
        //echo "<br/>usedtagsIds: "; print_r($usedtagsIds);
        //echo "<br/>usedtags (data): "; print_r($usedtags);
        //echo "<br/>row->categories: "; print_r($item->categories);
        //echo "<br/>selectedcats: "; print_r($selectedcats);
        // *********************************************************************************************
        // Build select lists for the form field. Only few of them are used in J1.6+, since we will use:
        // (a) form XML file to declare them and then (b) getInput() method form field to create them
        // *********************************************************************************************
        // First clean form data, we do this after creating the description field which may contain HTML
        JFilterOutput::objectHTMLSafe($item, ENT_QUOTES);
        $lists = array();
        // build state list
        $non_publishers_stategrp = $perms['isSuperAdmin'] || $item->state == -3 || $item->state == -4;
        $special_privelege_stategrp = $item->state == 2 || $perms['canarchive'] || ($item->state == -2 || $perms['candelete']);
        $state = array();
        // Using <select> groups
        if ($non_publishers_stategrp || $special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_PUBLISHERS_WORKFLOW_STATES'));
        }
        $state[] = JHTML::_('select.option', 1, JText::_('FLEXI_PUBLISHED'));
        $state[] = JHTML::_('select.option', 0, JText::_('FLEXI_UNPUBLISHED'));
        $state[] = JHTML::_('select.option', -5, JText::_('FLEXI_IN_PROGRESS'));
        // States reserved for workflow
        if ($non_publishers_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_NON_PUBLISHERS_WORKFLOW_STATES'));
        }
        if ($item->state == -3 || $perms['isSuperAdmin']) {
            $state[] = JHTML::_('select.option', -3, JText::_('FLEXI_PENDING'));
        }
        if ($item->state == -4 || $perms['isSuperAdmin']) {
            $state[] = JHTML::_('select.option', -4, JText::_('FLEXI_TO_WRITE'));
        }
        // Special access states
        if ($special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_SPECIAL_ACTION_STATES'));
        }
        if ($item->state == 2 || $perms['canarchive']) {
            $state[] = JHTML::_('select.option', 2, JText::_('FLEXI_ARCHIVED'));
        }
        if ($item->state == -2 || $perms['candelete']) {
            $state[] = JHTML::_('select.option', -2, JText::_('FLEXI_TRASHED'));
        }
        // Close last <select> group
        if ($non_publishers_stategrp || $special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
        }
        $fieldname = 'jform[state]';
        $elementid = 'jform_state';
        $class = 'use_select2_lib';
        $attribs = 'class="' . $class . '"';
        $lists['state'] = JHTML::_('select.genericlist', $state, $fieldname, $attribs, 'value', 'text', $item->state, $elementid);
        if (!FLEXI_J16GE) {
            $lists['state'] = str_replace('<optgroup label="">', '</optgroup>', $lists['state']);
        }
        // *** BOF: J2.5 SPECIFIC SELECT LISTS
        if (FLEXI_J16GE) {
            // build featured flag
            $fieldname = 'jform[featured]';
            $elementid = 'jform_featured';
            /*
            $options = array();
            $options[] = JHTML::_('select.option',  0, JText::_( 'FLEXI_NO' ) );
            $options[] = JHTML::_('select.option',  1, JText::_( 'FLEXI_YES' ) );
            $attribs = FLEXI_J16GE ? ' style ="float:none!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
            $lists['featured'] = JHTML::_('select.radiolist', $options, $fieldname, $attribs, 'value', 'text', $item->featured, $elementid);
            */
            $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
            $attribs = ' class="' . $classes . '" ';
            $i = 1;
            $options = array(0 => JText::_('FLEXI_NO'), 1 => JText::_('FLEXI_YES'));
            $lists['featured'] = '';
            foreach ($options as $option_id => $option_label) {
                $checked = $option_id == $item->featured ? ' checked="checked"' : '';
                $elementid_no = $elementid . '_' . $i;
                if (!$prettycheckable_added) {
                    $lists['featured'] .= '<label class="fccheckradio_lbl" for="' . $elementid_no . '">';
                }
                $extra_params = !$prettycheckable_added ? '' : ' data-labeltext="' . JText::_($option_label) . '" data-labelPosition="right" data-customClass="fcradiocheck"';
                $lists['featured'] .= ' <input type="radio" id="' . $elementid_no . '" data-element-grpid="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="' . $option_id . '" ' . $checked . $extra_params . ' />';
                if (!$prettycheckable_added) {
                    $lists['featured'] .= '&nbsp;' . JText::_($option_label) . '</label>';
                }
                $i++;
            }
        }
        // *** EOF: J1.5 SPECIFIC SELECT LISTS
        // build version approval list
        $fieldname = 'jform[vstate]';
        $elementid = 'jform_vstate';
        /*
        $options = array();
        $options[] = JHTML::_('select.option',  1, JText::_( 'FLEXI_NO' ) );
        $options[] = JHTML::_('select.option',  2, JText::_( 'FLEXI_YES' ) );
        $attribs = FLEXI_J16GE ? ' style ="float:left!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
        $lists['vstate'] = JHTML::_('select.radiolist', $options, $fieldname, $attribs, 'value', 'text', 2, $elementid);
        */
        $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
        $attribs = ' class="' . $classes . '" ';
        $i = 1;
        $options = array(1 => JText::_('FLEXI_NO'), 2 => JText::_('FLEXI_YES'));
        $lists['vstate'] = '';
        foreach ($options as $option_id => $option_label) {
            $checked = $option_id == 2 ? ' checked="checked"' : '';
            $elementid_no = $elementid . '_' . $i;
            if (!$prettycheckable_added) {
                $lists['vstate'] .= '<label class="fccheckradio_lbl" for="' . $elementid_no . '">';
            }
            $extra_params = !$prettycheckable_added ? '' : ' data-labeltext="' . JText::_($option_label) . '" data-labelPosition="right" data-customClass="fcradiocheck"';
            $lists['vstate'] .= ' <input type="radio" id="' . $elementid_no . '" data-element-grpid="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="' . $option_id . '" ' . $checked . $extra_params . ' />';
            if (!$prettycheckable_added) {
                $lists['vstate'] .= '&nbsp;' . JText::_($option_label) . '</label>';
            }
            $i++;
        }
        // build field for notifying subscribers
        if (!$subscribers) {
            $lists['notify'] = !$isnew ? JText::_('FLEXI_NO_SUBSCRIBERS_EXIST') : '';
        } else {
            // b. Check if notification emails to subscribers , were already sent during current session
            $subscribers_notified = $session->get('subscribers_notified', array(), 'flexicontent');
            if (!empty($subscribers_notified[$item->id])) {
                $lists['notify'] = JText::_('FLEXI_SUBSCRIBERS_ALREADY_NOTIFIED');
            } else {
                // build favs notify field
                $fieldname = 'jform[notify]';
                $elementid = 'jform_notify';
                /*
                $attribs = FLEXI_J16GE ? ' style ="float:none!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
                $lists['notify'] = '<input type="checkbox" name="jform[notify]" id="jform_notify" '.$attribs.' /> '. $lbltxt;
                */
                $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
                $attribs = ' class="' . $classes . '" ';
                $lbltxt = $subscribers . ' ' . JText::_($subscribers > 1 ? 'FLEXI_SUBSCRIBERS' : 'FLEXI_SUBSCRIBER');
                if (!$prettycheckable_added) {
                    $lists['notify'] .= '<label class="fccheckradio_lbl" for="' . $elementid . '">';
                }
                $extra_params = !$prettycheckable_added ? '' : ' data-labeltext="' . $lbltxt . '" data-labelPosition="right" data-customClass="fcradiocheck"';
                $lists['notify'] = ' <input type="checkbox" id="' . $elementid . '" data-element-grpid="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="1" ' . $extra_params . ' checked="checked" />';
                if (!$prettycheckable_added) {
                    $lists['notify'] .= '&nbsp;' . $lbltxt . '</label>';
                }
            }
        }
        // Retrieve author configuration
        $authorparams = flexicontent_db::getUserConfig($user->id);
        // Get author's maximum allowed categories per item and set js limitation
        $max_cat_assign = intval($authorparams->get('max_cat_assign', 0));
        $document->addScriptDeclaration('
			max_cat_assign_fc = ' . $max_cat_assign . ';
			existing_cats_fc  = ["' . implode('","', $selectedcats) . '"];
		');
        JText::script('FLEXI_TOO_MANY_ITEM_CATEGORIES', true);
        // Creating categorories tree for item assignment, we use the 'create' privelege
        $actions_allowed = array('core.create');
        // Featured categories form field
        $featured_cats_parent = $params->get('featured_cats_parent', 0);
        $featured_cats = array();
        $enable_featured_cid_selector = $perms['multicat'] && $perms['canchange_featcat'];
        if ($featured_cats_parent) {
            $featured_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $featured_cats_parent, $depth_limit = 0);
            $disabled_cats = $params->get('featured_cats_parent_disable', 1) ? array($featured_cats_parent) : array();
            $featured_sel = array();
            foreach ($selectedcats as $item_cat) {
                if (isset($featured_tree[$item_cat])) {
                    $featured_sel[] = $item_cat;
                }
            }
            $class = "use_select2_lib select2_list_selected";
            $attribs = 'class="' . $class . '" multiple="multiple" size="8"';
            $attribs .= $enable_featured_cid_selector ? '' : ' disabled="disabled"';
            $fieldname = 'jform[featured_cid][]';
            $lists['featured_cid'] = ($enable_featured_cid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($featured_tree, $fieldname, $featured_sel, 3, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees = array(), $disable_subtrees = array(), $custom_options = array(), $disabled_cats);
        } else {
            // Do not display, if not configured or not allowed to the user
            $lists['featured_cid'] = false;
        }
        // Multi-category form field, for user allowed to use multiple categories
        $lists['cid'] = '';
        $enable_cid_selector = $perms['multicat'] && $perms['canchange_seccat'];
        if (1) {
            if ($tparams->get('cid_allowed_parent')) {
                $cid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $tparams->get('cid_allowed_parent'), $depth_limit = 0);
                $disabled_cats = $tparams->get('cid_allowed_parent_disable', 1) ? array($tparams->get('cid_allowed_parent')) : array();
            } else {
                $cid_tree =& $categories;
                $disabled_cats = array();
            }
            // Get author's maximum allowed categories per item and set js limitation
            $max_cat_assign = !$authorparams ? 0 : intval($authorparams->get('max_cat_assign', 0));
            $document->addScriptDeclaration('
				max_cat_assign_fc = ' . $max_cat_assign . ';
				existing_cats_fc  = ["' . implode('","', $selectedcats) . '"];
			');
            $class = "mcat use_select2_lib select2_list_selected";
            $class .= $max_cat_assign ? " validate-fccats" : " validate";
            $attribs = 'class="' . $class . '" multiple="multiple" size="20"';
            $attribs .= $enable_cid_selector ? '' : ' disabled="disabled"';
            $fieldname = 'jform[cid][]';
            $skip_subtrees = $featured_cats_parent ? array($featured_cats_parent) : array();
            $lists['cid'] = ($enable_cid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($cid_tree, $fieldname, $selectedcats, false, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees, $disable_subtrees = array(), $custom_options = array(), $disabled_cats);
        } else {
            if (count($selectedcats) > 1) {
                foreach ($selectedcats as $catid) {
                    $cat_titles[$catid] = $globalcats[$catid]->title;
                }
                $lists['cid'] .= implode(', ', $cat_titles);
            } else {
                $lists['cid'] = false;
            }
        }
        // Main category form field
        $class = 'scat use_select2_lib';
        if ($perms['multicat']) {
            $class .= ' validate-catid';
        } else {
            $class .= ' required';
        }
        $attribs = 'class="' . $class . '"';
        $fieldname = 'jform[catid]';
        $enable_catid_selector = $isnew && !$tparams->get('catid_default') || !$isnew && empty($item->catid) || $perms['canchange_cat'];
        if ($tparams->get('catid_allowed_parent')) {
            $catid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $tparams->get('catid_allowed_parent'), $depth_limit = 0);
            $disabled_cats = $tparams->get('catid_allowed_parent_disable', 1) ? array($tparams->get('catid_allowed_parent')) : array();
        } else {
            $catid_tree =& $categories;
            $disabled_cats = array();
        }
        $lists['catid'] = false;
        if (!empty($catid_tree)) {
            $disabled = $enable_catid_selector ? '' : ' disabled="disabled"';
            $attribs .= $disabled;
            $lists['catid'] = ($enable_catid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($catid_tree, $fieldname, $item->catid, 2, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees = array(), $disable_subtrees = array(), $custom_options = array(), $disabled_cats);
        } else {
            if (!$isnew && $item->catid) {
                $lists['catid'] = $globalcats[$item->catid]->title;
            }
        }
        //buid types selectlist
        $class = 'required use_select2_lib';
        $attribs = 'class="' . $class . '"';
        $fieldname = 'jform[type_id]';
        $elementid = 'jform_type_id';
        $lists['type'] = flexicontent_html::buildtypesselect($types, $fieldname, $typesselected->id, 1, $attribs, $elementid, $check_perms = true);
        //build languages list
        $allowed_langs = !$authorparams ? null : $authorparams->get('langs_allowed', null);
        $allowed_langs = !$allowed_langs ? null : FLEXIUtilities::paramToArray($allowed_langs);
        if (!$isnew && $allowed_langs) {
            $allowed_langs[] = $item->language;
        }
        // We will not use the default getInput() function of J1.6+ since we want to create a radio selection field with flags
        // we could also create a new class and override getInput() method but maybe this is an overkill, we may do it in the future
        $lists['languages'] = flexicontent_html::buildlanguageslist('jform[language]', 'class="use_select2_lib"', $item->language, 2, $allowed_langs);
        // Label for current item state: published, unpublished, archived etc
        switch ($item->state) {
            case 0:
                $published = JText::_('FLEXI_UNPUBLISHED');
                break;
            case 1:
                $published = JText::_('FLEXI_PUBLISHED');
                break;
            case -1:
                $published = JText::_('FLEXI_ARCHIVED');
                break;
            case -3:
                $published = JText::_('FLEXI_PENDING');
                break;
            case -5:
                $published = JText::_('FLEXI_IN_PROGRESS');
                break;
            case -4:
            default:
                $published = JText::_('FLEXI_TO_WRITE');
                break;
        }
        // **************************************************************
        // Handle Item Parameters Creation and Load their values for J1.5
        // In J1.6+ we declare them in the item form XML file
        // **************************************************************
        if (JHTML::_('date', $item->publish_down, 'Y') <= 1969 || $item->publish_down == $db->getNullDate() || empty($item->publish_down)) {
            $form->setValue('publish_down', null, '');
            // Setting to text will break form date element
        }
        // ****************************
        // Handle Template related work
        // ****************************
        // (a) Get the templates structures used to create form fields for template parameters
        $themes = flexicontent_tmpl::getTemplates();
        $tmpls_all = $themes->items;
        // (b) Get Content Type allowed templates
        $allowed_tmpls = $tparams->get('allowed_ilayouts');
        $type_default_layout = $tparams->get('ilayout', 'default');
        if (empty($allowed_tmpls)) {
            $allowed_tmpls = array();
        } else {
            if (!is_array($allowed_tmpls)) {
                $allowed_tmpls = explode("|", $allowed_tmpls);
            }
        }
        // (c) Add default layout, unless all templates allowed (=array is empty)
        if (count($allowed_tmpls) && !in_array($type_default_layout, $allowed_tmpls)) {
            $allowed_tmpls[] = $type_default_layout;
        }
        // (d) Create array of template data according to the allowed templates for current content type
        if (count($allowed_tmpls)) {
            foreach ($tmpls_all as $tmpl) {
                if (in_array($tmpl->name, $allowed_tmpls)) {
                    $tmpls[] = $tmpl;
                }
            }
        } else {
            $tmpls = $tmpls_all;
        }
        // (e) Apply Template Parameters values into the form fields structures
        foreach ($tmpls as $tmpl) {
            $jform = new JForm('com_flexicontent.template.item', array('control' => 'jform', 'load_data' => true));
            $jform->load($tmpl->params);
            $tmpl->params = $jform;
            foreach ($tmpl->params->getGroup('attribs') as $field) {
                $fieldname = $field->__get('fieldname');
                $value = $item->itemparams->get($fieldname);
                if (strlen($value)) {
                    $tmpl->params->setValue($fieldname, 'attribs', $value);
                }
            }
        }
        // ******************************
        // Assign data to VIEW's template
        // ******************************
        $this->assignRef('document', $document);
        $this->assignRef('lists', $lists);
        $this->assignRef('row', $item);
        if (FLEXI_J16GE) {
            $this->assignRef('form', $form);
        } else {
            $this->assignRef('editor', $editor);
            $this->assignRef('pane', $pane);
            $this->assignRef('formparams', $formparams);
        }
        if ($enable_translation_groups) {
            $this->assignRef('lang_assocs', $langAssocs);
        }
        if (FLEXI_FISH || FLEXI_J16GE) {
            $this->assignRef('langs', $langs);
        }
        $this->assignRef('typesselected', $typesselected);
        $this->assignRef('published', $published);
        $this->assignRef('nullDate', $nullDate);
        $this->assignRef('subscribers', $subscribers);
        $this->assignRef('fields', $fields);
        $this->assignRef('versions', $versions);
        $this->assignRef('ratings', $ratings);
        $this->assignRef('pagecount', $pagecount);
        $this->assignRef('params', $params);
        $this->assignRef('tparams', $tparams);
        $this->assignRef('tmpls', $tmpls);
        $this->assignRef('usedtags', $usedtags);
        $this->assignRef('perms', $perms);
        $this->assignRef('current_page', $current_page);
        // Clear custom form data from session
        $app->setUserState($form->option . '.edit.' . $form->context . '.custom', false);
        $app->setUserState($form->option . '.edit.' . $form->context . '.jfdata', false);
        $app->setUserState($form->option . '.edit.' . $form->context . '.unique_tmp_itemid', false);
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        parent::display($tpl);
        if ($print_logging_info) {
            $fc_run_times['form_rendering'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
    }
Ejemplo n.º 6
0
    function onDisplayField(&$field, &$item)
    {
        if (!in_array($field->field_type, self::$field_types)) {
            return;
        }
        $field->label = JText::_($field->label);
        // Get some api objects
        $db = JFactory::getDBO();
        $user = JFactory::getUser();
        $document = JFactory::getDocument();
        $field->html = '';
        $ri_field_name = str_replace('-', '_', $field->name);
        $fieldname = FLEXI_J16GE ? 'custom[' . $ri_field_name . '][]' : $ri_field_name . '[]';
        // Case of autorelated item
        $autorelation_itemid = JRequest::getInt('autorelation_' . $field->id);
        if ($autorelation_itemid) {
            // automatically related item
            $query = 'SELECT title, id, catid, state, alias ' . ' FROM #__content ' . ' WHERE id =' . $autorelation_itemid;
            $db->setQuery($query);
            $rel_item = $db->loadObject();
            if (!$rel_item) {
                $field->html = 'auto relating item id: ' . $autorelation_itemid . ' : item not found ';
                return;
            }
            $field->html = '<input id="' . $ri_field_name . '" name="' . $fieldname . '" type="hidden" value="' . $rel_item->id . ':' . $rel_item->catid . '" />';
            $field->html .= $rel_item->title;
            return;
        }
        // ************************************************************************
        // Initialise values and split them into: (a) item ids and (b) category ids
        // ************************************************************************
        $default_values = '';
        if ($item->version == 0 && $default_values) {
            $field->value = explode(",", $default_values);
        } else {
            if (!$field->value) {
                $field->value = array();
            } else {
                // Compatibility with old values, we no longer serialize all values to one, this way the field can be reversed more easily !!!
                $field->value = ($field_data = @unserialize($field->value[0])) ? $field_data : $field->value;
            }
        }
        $_itemids_catids = array();
        foreach ($field->value as $i => $val) {
            list($itemid, $catid) = explode(":", $val);
            $itemid = (int) $itemid;
            $catid = (int) $catid;
            $_itemids_catids[$itemid] = new stdClass();
            $_itemids_catids[$itemid]->itemid = $itemid;
            $_itemids_catids[$itemid]->catid = $catid;
            $_itemids_catids[$itemid]->value = $val;
        }
        $auto_relate_curritem = $field->parameters->get('auto_relate_curritem', 0);
        if ($auto_relate_curritem && !empty($_itemids_catids) && !FlexicontentHelperPerm::getPerm()->SuperAdmin) {
            $query = 'SELECT title, id, catid, state, alias ' . ' FROM #__content ' . ' WHERE id IN (' . implode(array_keys($_itemids_catids), ',') . ')';
            $db->setQuery($query);
            $rel_items = $db->loadObjectList();
            $i = 0;
            foreach ($rel_items as $rel_item) {
                $field->html .= '<input id="' . $ri_field_name . $i . '" name="' . $fieldname . '" type="hidden" value="' . $rel_item->id . ':' . $rel_item->catid . '" />';
                $field->html .= $rel_item->title . " <br/> \n";
                $i++;
            }
            return;
        }
        // ******************
        // SCOPE PARAMETERS
        // ******************
        // categories scope parameters
        $method_cat = $field->parameters->get('method_cat', 1);
        $usesubcats = $field->parameters->get('usesubcats', 0);
        $catids = $field->parameters->get('catids');
        if (empty($catids)) {
            $catids = array();
        } else {
            if (!is_array($catids)) {
                $catids = !FLEXI_J16GE ? array($catids) : explode("|", $catids);
            }
        }
        // types scope parameters
        $method_types = $field->parameters->get('method_types', 1);
        $types = $field->parameters->get('types');
        if (empty($types)) {
            $types = array();
        } else {
            if (!is_array($types)) {
                $types = !FLEXI_J16GE ? array($types) : explode("|", $types);
            }
        }
        // other limits of scope parameters
        $samelangonly = $field->parameters->get('samelangonly', 1);
        $onlypublished = $field->parameters->get('onlypublished', 1);
        $ownedbyuser = $field->parameters->get('ownedbyuser', 0);
        // ******************
        // EDITING PARAMETERS
        // ******************
        // some parameters shortcuts
        $size = $field->parameters->get('size', 12);
        $size = $size ? ' size="' . $size . '"' : '';
        $prepend_item_state = $field->parameters->get('prepend_item_state', 1);
        $maxtitlechars = $field->parameters->get('maxtitlechars', 40);
        $title_filter = $field->parameters->get('title_filter', 1);
        $required = $field->parameters->get('required', 0);
        $required = $required ? ' required' : '';
        $select_items_prompt = $field->parameters->get('select_items_prompt', 'FLEXI_RIFLD_SELECT_ITEMS_PROMPT');
        $selected_items_label = $field->parameters->get('selected_items_label', 'FLEXI_RIFLD_SELECTED_ITEMS_LABEL');
        $display_cat_filter_label = $field->parameters->get('display_cat_filter_label', 1);
        $display_title_filter_label = $field->parameters->get('display_title_filter_label', 1);
        $default_value_title_filter = $field->parameters->get('default_value_title_filter', '');
        // ***********************************************
        // Get & check Global category related permissions
        // ***********************************************
        require_once JPATH_ROOT . DS . 'components' . DS . 'com_flexicontent' . DS . 'helpers' . DS . 'permission.php';
        $viewallcats = FlexicontentHelperPerm::getPerm()->ViewAllCats;
        $viewtree = FlexicontentHelperPerm::getPerm()->ViewTree;
        if (!$viewtree) {
            $field->html = '<div class="alert alert-info fc-small fc-iblock">' . JText::_('FLEXI_NO_ACCESS_LEVEL_TO_VIEW_CATEGORY_TREE') . '</div><div class="clear"></div>';
            return;
        }
        // ****************************************************
        // Calculate categories to use for retrieving the items
        // ****************************************************
        $allowed_cats = $disallowed_cats = false;
        // Get user allowed categories
        $usercats = FLEXI_J16GE || FLEXI_ACCESS ? FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.create', 'core.edit', 'core.edit.own'), $require_all = false, $check_published = true) : FlexicontentHelperPerm::returnAllCats($check_published = true, $specific_catids = null);
        // Find (if configured) , descendants of the categories
        if ($usesubcats) {
            global $globalcats;
            $_catids = array();
            foreach ($catids as $catid) {
                $subcats = $globalcats[$catid]->descendantsarray;
                foreach ($subcats as $subcat) {
                    $_catids[(int) $subcat] = 1;
                }
            }
            $catids = array_keys($_catids);
        }
        // ... TODO: retrieve items via AJAX
        // *********************************************
        // Item retrieving query ... CREATE WHERE CLAUSE
        // *********************************************
        $where = array();
        // **************
        // CATEGORY SCOPE
        // **************
        // Include method
        if ($method_cat == 3) {
            $allowed_cats = $viewallcats ? $catids : array_intersect($usercats, $catids);
            if (!empty($allowed_cats)) {
                $where[] = " rel.catid IN (" . implode(',', $allowed_cats) . ") ";
            } else {
                $field->html = JText::_('FLEXI_CANNOT_EDIT_FIELD') . ': <br/> ' . JText::_('FLEXI_NO_ACCESS_TO_USE_CONFIGURED_CATEGORIES');
                return;
            }
        } else {
            if ($method_cat == 2) {
                $disallowed_cats = $viewallcats ? $catids : array_diff($usercats, $catids);
                if (!empty($disallowed_cats)) {
                    $where[] = " rel.catid NOT IN (" . implode(',', $disallowed_cats) . ") ";
                }
            } else {
                if (!$viewallcats) {
                    $allowed_cats = $usercats;
                    if (!empty($allowed_cats)) {
                        $where[] = " rel.catid IN (" . implode(',', $allowed_cats) . ") ";
                    } else {
                        $field->html = JText::_('FLEXI_CANNOT_EDIT_FIELD') . ': <br/> ' . JText::_('FLEXI_NO_ACCESS_TO_USE_ANY_CATEGORIES');
                        return;
                    }
                }
            }
        }
        // TYPE SCOPE
        if (($method_types == 2 || $method_types == 3) && (!count($types) || empty($types[0]))) {
            $field->html = 'Content Type scope is set to include/exclude but no Types are selected in field configuration, please set to "ALL" or select types to include/exclude';
            return;
        }
        if ($method_types == 2) {
            $where[] = ' ie.type_id NOT IN (' . implode(',', $types) . ')';
        } else {
            if ($method_types == 3) {
                $where[] = ' ie.type_id IN (' . implode(',', $types) . ')';
            }
        }
        // include method
        // OTHER SCOPE LIMITS
        if ($samelangonly) {
            $where[] = $item->language == '*' ? " ie.language='*' " : " (ie.language='{$item->language}' OR ie.language='*') ";
        }
        if ($onlypublished) {
            $where[] = " i.state IN (1, -5) ";
        }
        if ($ownedbyuser == 1) {
            $where[] = " i.created_by = " . $user->id;
        } else {
            if ($ownedbyuser == 2) {
                $where[] = " i.created_by = " . $item->created_by;
            }
        }
        $where = !count($where) ? "" : " WHERE " . implode(" AND ", $where);
        // ***********************************************
        // Item retrieving query ... CREATE ORDERBY CLAUSE
        // ***********************************************
        $order = $field->parameters->get('orderby_form', 'alpha');
        // TODO: add more orderings: commented, rated
        $orderby = flexicontent_db::buildItemOrderBy($field->parameters, $order, $request_var = '', $config_param = '', $item_tbl_alias = 'i', $relcat_tbl_alias = 'rel', $default_order = '', $default_order_dir = '', $sfx = '_form', $support_2nd_lvl = false);
        // Create JOIN for ordering items by a most rated
        if (in_array('author', $order) || in_array('rauthor', $order)) {
            $orderby_join = ' LEFT JOIN #__users AS u ON u.id = i.created_by';
        }
        // *****************************************************
        // Item retrieving query ... put together and execute it
        // *****************************************************
        $query = 'SELECT i.title, i.id, i.catid, i.state, i.alias' . ", GROUP_CONCAT(rel.catid SEPARATOR ',') as catlist" . ' FROM #__content AS i ' . ($samelangonly || $method_types > 1 ? " LEFT JOIN #__flexicontent_items_ext AS ie on i.id=ie.item_id " : "") . ' JOIN #__flexicontent_cats_item_relations AS rel on i.id=rel.itemid ' . @$orderby_join . $where . " GROUP BY rel.itemid " . $orderby;
        $db->setQuery($query);
        $items_arr = $db->loadObjectList();
        if ($db->getErrorNum()) {
            echo $db->getErrorMsg();
            $field->html = '';
            return false;
        }
        // *******************************************************
        // Create category tree to use for selecting related items
        // *******************************************************
        require_once JPATH_ROOT . DS . "components" . DS . "com_flexicontent" . DS . "classes" . DS . "flexicontent.categories.php";
        $tree = flexicontent_cats::getCategoriesTree();
        // Get categories without filtering
        if ($allowed_cats) {
            foreach ($allowed_cats as $catid) {
                $allowedtree[$catid] = $tree[$catid];
            }
        }
        if ($disallowed_cats) {
            foreach ($disallowed_cats as $catid) {
                unset($tree[$catid]);
            }
            $allowedtree =& $tree;
        }
        if (!$allowed_cats && !$disallowed_cats) {
            $allowedtree =& $tree;
        }
        // *****************************************
        // Create field's HTML display for item form
        // *****************************************
        static $common_css_js_added = false;
        if (!$common_css_js_added) {
            $common_css_js_added = true;
            flexicontent_html::loadFramework('select2');
            $css = '' . '.fcrelation_field_used_items, .fcrelation_field_unused_items, .fcrelation_field_controls { display:inline-block; float:left !important; margin: 0 0 8px 0; }' . '.fcrelation_field_used_items.fc_vertical,   .fcrelation_field_unused_items.fc_vertical   { min-width: 100%; }' . '.fcrelation_field_used_items.fc_horizontal, .fcrelation_field_unused_items.fc_horizontal { margin: 8px 0%; }' . '.fcrelation_field_controls.fc_vertical   { min-width: 100%; }' . '.fcrelation_field_controls.fc_horizontal { max-width:6%; margin: 48px 1% 0 1%; width: auto; }' . '.fcrelation_field_controls.fc_horizontal span.fcrelation_btn { float: left !important; clear: both !important; }' . '.fcfield-placement-h.fc_horizontal { display: none !important; }' . '.fcfield-placement-v.fc_vertical { display: none !important; }' . '.fcrelation_field_filters { display:inline-block; float:left !important; }' . '.fcrelation_field_filters span.label { min-width: 140px; }' . '.fcrelation_field_used_items select, .fcrelation_field_unused_items select { min-width: 100%; margin:0px; }';
            if ($css) {
                $document->addStyleDeclaration($css);
            }
        }
        // The split up the items
        $items_options = '';
        $items_options_select = '';
        $items_options_unused = '';
        $state_shortname = array(1 => 'P', 0 => 'U', -1 => 'A', -3 => 'PE', -4 => 'OQ', -5 => 'IP');
        foreach ($items_arr as $itemdata) {
            $itemtitle = mb_strlen($itemdata->title) > $maxtitlechars ? mb_substr($itemdata->title, 0, $maxtitlechars) . "..." : $itemdata->title;
            if ($prepend_item_state) {
                $statestr = "[" . @$state_shortname[$itemdata->state] . "] ";
                $itemtitle = $statestr . $itemtitle . " ";
                //.$itemdata->catlist;
            }
            $itemcat_arr = explode(",", $itemdata->catlist);
            $classes_str = "";
            $itemid = $itemdata->id;
            foreach ($itemcat_arr as $catid) {
                $classes_str .= " " . "cat_" . $catid;
            }
            if (isset($_itemids_catids[$itemid])) {
                $items_options .= '<option class="' . $classes_str . '" value="' . $_itemids_catids[$itemid]->value . '" >' . $itemtitle . '</option>' . "\n";
                $items_options_select .= '<option selected="selected" class="' . $classes_str . '" value="' . $_itemids_catids[$itemid]->value . '" >' . $itemtitle . '</option>' . "\n";
            } else {
                $items_options_unused .= '<option class="' . $classes_str . '" value="' . $itemid . '" >' . $itemtitle . '</option>' . "\n";
            }
        }
        $cat_selected = count($allowedtree) == 1 ? reset($allowedtree) : '';
        $cat_selecor_box_style = count($allowedtree) == 1 ? 'style="display:none;" ' : '';
        $_cat_selector = flexicontent_cats::buildcatselect($allowedtree, $ri_field_name . '_fccats', $catvals = $cat_selected ? $cat_selected->id : '', $top = 2, ' class="use_select2_lib ' . $ri_field_name . '_fccats" ', $check_published = true, $check_perms = true, $actions_allowed = array('core.create', 'core.edit', 'core.edit.own'), $require_all = false, $skip_subtrees = array(), $disable_subtrees = array(), $custom_options = array('__ALL__' => 'FLEXI_RIFLD_FILTER_LIST_ALL'));
        if ($title_filter) {
            $document->addScript(JURI::root(true) . '/components/com_flexicontent/assets/js/filterlist.js');
            $_title_filtering = '' . '<input class="fcfield_textval" id="' . $ri_field_name . '_regexp" name="' . $ri_field_name . '_regexp" onKeyUp="' . $ri_field_name . '_titlefilter.set(this.value)" size="30" onfocus="if (this.value==\'' . $default_value_title_filter . '\') this.value=\'\';" onblur="if (this.value==\'\') this.value=\'' . $default_value_title_filter . '\';" value="' . $default_value_title_filter . '" />' . '<input class="fcfield-button" type="button" onclick="' . $ri_field_name . '_titlefilter.reset();this.form.' . $ri_field_name . '_regexp.value=\'\'" value="' . JText::_('FLEXI_RIFLD_RESET') . '" />';
        }
        $field->html .= '
		<div class="fcfieldval_container valuebox fcfieldval_container_' . $field->id . '">
			<span class="fcrelation_field_filters">
				
				<span class="fcrelation_field_filter_by_cat nowrap_box" ' . $cat_selecor_box_style . '>
					' . ($display_cat_filter_label ? '<span class="label">' . JText::_('FLEXI_RIFLD_FILTER_BY_CAT') . '</span>' : '') . '
					' . $_cat_selector . '
				</span>
				
				' . ($title_filter ? '
				<span class="fcrelation_field_filter_by_title nowrap_box">
					' . ($display_title_filter_label ? '<span class="label">' . JText::_('FLEXI_RIFLD_FILTER_BY_TITLE') . '</span>' : '') . '
	    		' . $_title_filtering . '
				</span>
				' : '') . '
				
			</span>
			<div class="fcclear"></div>
		';
        $initial_placement = $field->parameters->get('initial_placement', 'h');
        $placement_class = $initial_placement == 'h' ? ' fc_horizontal' : ' fc_vertical';
        $field->html .= '
			<span class="fcrelation_field_unused_items' . $placement_class . '">
				<span class="label">' . JText::_($select_items_prompt) . '</span><br/>
				<select id="' . $ri_field_name . '_visitems" name="' . $ri_field_name . '_visitems[]" multiple="multiple" class="fcfield_selectmulval" ' . $size . ' >
				</select>
			</span>
		
			<span class="fcrelation_field_controls' . $placement_class . '">
				<span id="btn-add_' . $ri_field_name . '" class="fcrelation_btn fcfield-list-add ' . $placement_class . '" title="' . JText::_('FLEXI_ADD') . '"></span>
				<span id="btn-remove_' . $ri_field_name . '" class="fcrelation_btn fcfield-list-del ' . $placement_class . '" title="' . JText::_('FLEXI_REMOVE') . '"></span>
				<span id="btn-toggle_horizontal_' . $ri_field_name . '" class="fcrelation_btn fcfield-placement-h fc_toggle ' . $placement_class . '" onclick="jQuery(this).closest(\'.valuebox\').find(\'.fc_vertical\').removeClass(\'fc_vertical\').addClass(\'fc_horizontal\');" title="' . JText::_('FLEXI_HORIZONTAL') . '"></span>
				<span id="btn-toggle_vertical_' . $ri_field_name . '" class="fcrelation_btn fcfield-placement-v fc_toggle ' . $placement_class . '" onclick="jQuery(this).closest(\'.valuebox\').find(\'.fc_horizontal\').removeClass(\'fc_horizontal\').addClass(\'fc_vertical\');" title="' . JText::_('FLEXI_VERTICAL') . '"></span>
			</span>
    	
    	<span class="fcrelation_field_used_items' . $placement_class . '">
				<span class="label">' . JText::_($selected_items_label) . '</span><br/>
				<select id="' . $ri_field_name . '" name="' . $fieldname . '" multiple="multiple" class="' . $required . '" style="display:none;" ' . $size . ' >
					' . $items_options_select . '
				</select>
				
				<select id="' . $ri_field_name . '_selitems" name="' . $ri_field_name . '_selitems[]" multiple="multiple" class="fcfield_selectmulval" ' . $size . ' >
					' . $items_options . '
				</select>
				
				<select id="' . $ri_field_name . '_hiditems" name="' . $ri_field_name . '_hiditems" style="display:none;" >
					' . $items_options_unused . '
				</select>
			</span>
		</div>
		';
        $js = ($title_filter ? ' var filteredfield, ' . $ri_field_name . '_titlefilter;' : '') . "\n\njQuery(document).ready(function() {\n\n" . ($title_filter ? '
	filteredfield = document.getElementById("' . $ri_field_name . '_visitems");
	' . $ri_field_name . '_titlefilter = new filterlist( filteredfield );
	' : '') . "\n\n  jQuery('#btn-add_" . $ri_field_name . "').click(function(){\n      jQuery('#" . $ri_field_name . "_visitems option:selected').each( function() {\n          jQuery('#" . $ri_field_name . "_selitems').append(\"<option class='\"+jQuery(this).attr('class')+\"' value='\"+jQuery(this).val()+\"'>\"+jQuery(this).text()+\"</option>\");\n          jQuery('#" . $ri_field_name . "').append(\"<option selected='selected' class='\"+jQuery(this).attr('class')+\"' value='\"+jQuery(this).val()+\"'>\"+jQuery(this).text()+\"</option>\");\n          jQuery(this).remove();\n      });\n  });\n  jQuery('#btn-remove_" . $ri_field_name . "').click(function(){\n      jQuery('#" . $ri_field_name . "_selitems option:selected').each( function() {\n          jQuery('#" . $ri_field_name . "_visitems').append(\"<option class='\"+jQuery(this).attr('class')+\"' value='\"+jQuery(this).val()+\"'>\"+jQuery(this).text()+\"</option>\");\n          jQuery(\"#" . $ri_field_name . " option[value='\"+jQuery(this).val()+\"']\").remove();\n          jQuery(this).remove();\n      });\n  });\n\n});\n\njQuery(document).ready(function() {\n\t\n\tjQuery('#" . $ri_field_name . "_fccats').change(function() {\n\t\t\n\t\tvar " . $ri_field_name . "_fccats_val = jQuery('#" . $ri_field_name . "_fccats').val();\n\t\t\n\t\t" . ($title_filter ? $ri_field_name . "_titlefilter.reset(); this.form." . $ri_field_name . "_regexp.value='';" : "") . "\n\t\t\n\t  jQuery('#" . $ri_field_name . "_visitems option').each( function() {\n\t  \tvar data = jQuery(this).val().split(':'); \n\t  \tvar itemid = data[0];\n\t  \tjQuery('#" . $ri_field_name . "_hiditems').append(\"<option class='\"+jQuery(this).attr('class')+\"' value='\"+itemid+\"'>\"+jQuery(this).text()+\"</option>\");\n\t  \tjQuery(this).remove();\n\t\t});\n\t\t\n\t  jQuery('#" . $ri_field_name . "_hiditems option').each( function() {\n\t  \tif ( " . $ri_field_name . "_fccats_val == '__ALL__' || jQuery(this).hasClass('cat_' + " . $ri_field_name . "_fccats_val ) ) {\n\t\t\t  jQuery('#" . $ri_field_name . "_visitems').append(\"<option class='\"+jQuery(this).attr('class')+\"'value='\"+jQuery(this).val()+\":\"+ " . $ri_field_name . "_fccats_val+\"'>\"+jQuery(this).text()+\"</option>\");\n\t\t\t\tjQuery(this).remove();\n\t  \t}\n\t\t});\n\t\t\n\t\t" . ($title_filter ? $ri_field_name . "_titlefilter.init();" : "") . "\n\t});\n\t" . (count($allowedtree) == 1 ? "jQuery('#" . $ri_field_name . "_fccats').trigger('change');" : "") . "\n\t\n});";
        $document->addScriptDeclaration($js);
    }
Ejemplo n.º 7
0
 function fetchElement($name, $value, &$node, $control_name)
 {
     static $function_added = false;
     if (FLEXI_J16GE) {
         $node =& $this->element;
         $attributes = get_object_vars($node->attributes());
         $attributes = $attributes['@attributes'];
     } else {
         $attributes =& $node->_attributes;
     }
     $values = FLEXI_J16GE ? $this->value : $value;
     if (!empty($attributes['joinwith'])) {
         $values = explode($attributes['joinwith'], $values);
     }
     if (empty($values)) {
         $values = array();
     } else {
         if (!is_array($values)) {
             $values = !FLEXI_J16GE ? array($values) : explode("|", $values);
         }
     }
     $fieldname = FLEXI_J16GE ? $this->name : $control_name . '[' . $name . ']';
     $element_id = FLEXI_J16GE ? $this->id : $control_name . $name;
     $ffname = @$attributes['name'];
     $published_only = (bool) @$attributes['published_only'];
     $parent_id = (int) @$attributes['parent_id'];
     $depth_limit = (int) @$attributes['depth_limit'];
     $tree = flexicontent_cats::getCategoriesTree($published_only, $parent_id, $depth_limit);
     $attribs = '';
     // Steps needed for multi-value select field element, e.g. code to maximize select field
     if (@$attributes['multiple'] == 'multiple' || @$attributes['multiple'] == 'true') {
         $attribs .= ' multiple="multiple" ';
         $attribs .= @$attributes['size'] ? ' size="' . $attributes['size'] . '" ' : ' size="8" ';
         $fieldname .= !FLEXI_J16GE ? "[]" : "";
         // NOTE: this added automatically in J2.5
         /*$onclick = ""
         			."${element_id} = document.getElementById(\"${element_id}\");"
         			."if (${element_id}.size<40) {"
         			."	${element_id}_oldsize = ${element_id}.size;"
         			."	${element_id}.size=40;"
         			."} else {"
         			."	${element_id}.size = ${element_id}_oldsize;"
         			."}"
         			."parent = ${element_id}.getParent(); upcnt=0;"
         			."while(upcnt<10 && !parent.hasClass(\"jpane-slider\")) {"
         			."	upcnt++; parent = parent.getParent();"
         			."}"
         			."if (parent.hasClass(\"jpane-slider\")) parent.setStyle(\"height\", \"auto\");"
         		;
         		$style = 'display:inline-block;'.(FLEXI_J16GE ? 'float:left; margin: 6px 0px 0px 18px;':'margin:0px 0px 6px 12px');
         		$maximize_link = "<a style='$style' href='javascript:;' onclick='$onclick' >Maximize/Minimize</a>";*/
     } else {
         //$maximize_link = '';
     }
     $maximize_link = '';
     $top = @$attributes['top'] ? $attributes['top'] : false;
     $classes = 'use_select2_lib ';
     $classes .= @$attributes['required'] && @$attributes['required'] != 'false' ? ' required' : '';
     $classes .= $node->attributes('validation_class') ? ' ' . $node->attributes('validation_class') : '';
     $classes = ' class="' . $classes . '"';
     $attribs .= $classes . ' style="float:left;" ';
     // Add onClick functions (e.g. joining values to a string)
     if (!empty($attributes['joinwith']) && !$function_added) {
         $function_added = true;
         $js = "\n\t\t\tfunction FLEXIClickCategory(obj, name) {\n\t\t\t\tvalues=new Array();\n\t\t\t\tfor(i=0,j=0;i<obj.options.length;i++) {\n\t\t\t\t\tif(obj.options[i].selected==true)\n\t\t\t\t\t\tvalues[j++] = obj.options[i].value;\n\t\t\t\t}\n\t\t\t\tvalue_list = values.join(',');\n\t\t\t\tdocument.getElementById('a_id_'+name).value = value_list;\n\t\t\t\t//alert(document.getElementById('a_id_'+name).value);\n\t\t\t}";
         $doc = JFactory::getDocument();
         $doc->addScriptDeclaration($js);
     }
     $html = '';
     if (!empty($attributes['joinwith'])) {
         $select_fieldname = '_' . $ffname . '_';
         $text_fieldname = str_replace('[]', '', $fieldname);
         $attribs .= ' onclick="FLEXIClickCategory(this,\'' . $ffname . '\');" ';
         $html .= "\n<input type=\"hidden\" id=\"a_id_{$ffname}\" name=\"{$text_fieldname}\" value=\"" . @$values[0] . "\" />";
     } else {
         $select_fieldname = $fieldname;
     }
     $html .= flexicontent_cats::buildcatselect($tree, $select_fieldname, $values, $top, $attribs, false, true, $actions_allowed = array('core.create'));
     return $html . $maximize_link;
 }
Ejemplo n.º 8
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);
	}
Ejemplo n.º 9
0
    /**
     * Creates the item page
     *
     * @since 1.0
     */
    function display($tpl = null)
    {
        // ********************************
        // Initialize variables, flags, etc
        // ********************************
        global $globalcats;
        $categories = $globalcats;
        $app = JFactory::getApplication();
        $dispatcher = JDispatcher::getInstance();
        $document = JFactory::getDocument();
        $session = JFactory::getSession();
        $user = JFactory::getUser();
        $db = JFactory::getDBO();
        $option = JRequest::getVar('option');
        $nullDate = $db->getNullDate();
        // Get the COMPONENT only parameters
        $params = clone JComponentHelper::getParams('com_flexicontent');
        if (!FLEXI_J16GE) {
            jimport('joomla.html.pane');
            $pane = JPane::getInstance('sliders');
            $editor = JFactory::getEditor();
        }
        // 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');
        $prettycheckable_added = flexicontent_html::loadFramework('prettyCheckable');
        // Load custom behaviours: form validation, popup tooltips
        //JHTML::_('behavior.formvalidation');
        JHTML::_('behavior.tooltip');
        // Add css to document
        $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/flexicontentbackend.css');
        if (FLEXI_J30GE) {
            $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/j3x.css');
        } else {
            if (FLEXI_J16GE) {
                $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/j25.css');
            } else {
                $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/j15.css');
            }
        }
        // Add js function to overload the joomla submitform
        $document->addScript(JURI::root() . 'components/com_flexicontent/assets/js/admin.js');
        $document->addScript(JURI::root() . 'components/com_flexicontent/assets/js/validate.js');
        // Add js function for custom code used by FLEXIcontent item form
        $document->addScript(JURI::root() . 'components/com_flexicontent/assets/js/itemscreen.js');
        // ***********************
        // Get data from the model
        // ***********************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $model = $this->getModel();
        $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 Associated Translations
        // ***************************
        if ($enable_translation_groups) {
            $langAssocs = $this->get('LangAssocs');
        }
        if (FLEXI_FISH || FLEXI_J16GE) {
            $langs = FLEXIUtilities::getLanguages('code');
        }
        // Get item id and new flag
        $cid = $model->getId();
        $isnew = !$cid;
        // Create and set a unique item id for plugins that needed it
        JRequest::setVar('unique_tmp_itemid', $cid ? $cid : date('_Y_m_d_h_i_s_', time()) . uniqid(true));
        // Get number of subscribers
        $subscribers = $model->getSubscribersCount();
        // ******************
        // Version Panel data
        // ******************
        // Get / calculate some version related variables
        $versioncount = $model->getVersionCount();
        $versionsperpage = $params->get('versionsperpage', 10);
        $pagecount = (int) ceil($versioncount / $versionsperpage);
        // Data need by version panel: (a) current version page, (b) currently active version
        $current_page = 1;
        $k = 1;
        $allversions = $model->getVersionList();
        foreach ($allversions as $v) {
            if ($k > 1 && ($k - 1) % $versionsperpage == 0) {
                $current_page++;
            }
            if ($v->nr == $item->version) {
                break;
            }
            $k++;
        }
        // Finally fetch the version data for versions in current page
        $versions = $model->getVersionList(($current_page - 1) * $versionsperpage, $versionsperpage);
        // *****************
        // Type related data
        // *****************
        // Get available types and the currently selected/requested type
        $types = $model->getTypeslist();
        $typesselected = $model->getTypesselected();
        // Get and merge type parameters
        $tparams = $this->get('Typeparams');
        $tparams = FLEXI_J16GE ? new JRegistry($tparams) : new JParameter($tparams);
        $params->merge($tparams);
        // Apply type configuration if it type is set
        // Get user allowed permissions on the item ... to be used by the form rendering
        // Also hide parameters panel if user can not edit parameters
        $perms = $this->_getItemPerms($item, $typesselected);
        if (!$perms['canparams']) {
            $document->addStyleDeclaration((FLEXI_J16GE ? '#details-options' : '#det-pane') . '{display:none;}');
        }
        // ******************
        // Create the toolbar
        // ******************
        $toolbar = JToolBar::getInstance('toolbar');
        // SET toolbar title
        if ($cid) {
            JToolBarHelper::title(JText::_('FLEXI_EDIT_ITEM'), 'itemedit');
            // Editing existing item
        } else {
            JToolBarHelper::title(JText::_('FLEXI_NEW_ITEM'), 'itemadd');
            // Creating new item
        }
        // Add a preview button for LATEST version of the item
        if ($cid) {
            // Domain URL and autologin vars
            $server = JURI::getInstance()->toString(array('scheme', 'host', 'port'));
            $autologin = '';
            //$params->get('autoflogin', 1) ? '&fcu='.$user->username . '&fcp='.$user->password : '';
            // Check if we are in the backend, in the back end we need to set the application to the site app instead
            $isAdmin = JFactory::getApplication()->isAdmin();
            if ($isAdmin && FLEXI_J16GE) {
                JFactory::$application = JApplication::getInstance('site');
            }
            // Create the URL
            $item_url = JRoute::_(FlexicontentHelperRoute::getItemRoute($item->id . ':' . $item->alias, $categories[$item->catid]->slug) . $autologin);
            // Check if we are in the backend again
            // In backend we need to remove administrator from URL as it is added even though we've set the application to the site app
            if ($isAdmin) {
                if (FLEXI_J16GE) {
                    $admin_folder = str_replace(JURI::root(true), '', JURI::base(true));
                    $item_url = str_replace($admin_folder, '', $item_url);
                    // Restore application
                    JFactory::$application = JApplication::getInstance('administrator');
                } else {
                    $item_url = JURI::root(true) . '/' . $item_url;
                }
            }
            $previewlink = $item_url . (strstr($item_url, '?') ? '&' : '?') . 'preview=1';
            //$previewlink     = str_replace('&amp;', '&', $previewlink);
            //$previewlink = JRoute::_(JURI::root() . FlexicontentHelperRoute::getItemRoute($item->id.':'.$item->alias, $categories[$item->catid]->slug)) .$autologin;
            if (!$params->get('use_versioning', 1) || $item->version == $item->current_version && $item->version == $item->last_version) {
                $toolbar->appendButton('Custom', '<a class="preview btn btn-small" href="' . $previewlink . '" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-32-preview"></span>' . JText::_('Preview') . '</a>', 'preview');
            } else {
                // Add a preview button for (currently) LOADED version of the item
                $previewlink_loaded_ver = $previewlink . '&version=' . $item->version;
                $toolbar->appendButton('Custom', '<a class="preview btn btn-small" href="' . $previewlink_loaded_ver . '" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-32-preview"></span>' . JText::_('FLEXI_PREVIEW_FORM_LOADED_VERSION') . ' [' . $item->version . ']</a>', 'preview');
                // Add a preview button for currently ACTIVE version of the item
                $previewlink_active_ver = $previewlink . '&version=' . $item->current_version;
                $toolbar->appendButton('Custom', '<a class="preview btn btn-small" href="' . $previewlink_active_ver . '" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-32-preview"></span>' . JText::_('FLEXI_PREVIEW_FRONTEND_ACTIVE_VERSION') . ' [' . $item->current_version . ']</a>', 'preview');
                // Add a preview button for currently LATEST version of the item
                $previewlink_last_ver = $previewlink;
                //'&version='.$item->last_version;
                $toolbar->appendButton('Custom', '<a class="preview btn btn-small" href="' . $previewlink_last_ver . '" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-32-preview"></span>' . JText::_('FLEXI_PREVIEW_LATEST_SAVED_VERSION') . ' [' . $item->last_version . ']</a>', 'preview');
            }
            JToolBarHelper::spacer();
            JToolBarHelper::divider();
            JToolBarHelper::spacer();
        }
        // Common Buttons
        if (FLEXI_J16GE) {
            JToolBarHelper::apply('items.apply');
            if (!$isnew || $item->version) {
                JToolBarHelper::save('items.save');
            }
            if (!$isnew || $item->version) {
                JToolBarHelper::custom('items.saveandnew', 'savenew.png', 'savenew.png', 'FLEXI_SAVE_AND_NEW', false);
            }
            JToolBarHelper::cancel('items.cancel');
        } else {
            JToolBarHelper::apply();
            if (!$isnew || $item->version) {
                JToolBarHelper::save();
            }
            if (!$isnew || $item->version) {
                JToolBarHelper::custom('saveandnew', 'savenew.png', 'savenew.png', 'FLEXI_SAVE_AND_NEW', false);
            }
            JToolBarHelper::cancel();
        }
        // 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;
        }
        // *************************
        // Get tags used by the item
        // *************************
        $usedtagsIds = $this->get('UsedtagsIds');
        // NOTE: This will normally return the already set versioned value of tags ($item->tags)
        $usedtags = $model->getUsedtagsData($usedtagsIds);
        // *******************************
        // Get categories used by the item
        // *******************************
        if ($isnew) {
            // Case for preselected main category for new items
            $maincat = $item->catid ? $item->catid : JRequest::getInt('maincat', 0);
            if (!$maincat) {
                $maincat = $app->getUserStateFromRequest($option . '.items.filter_cats', 'filter_cats', '', 'int');
            }
            if ($maincat) {
                $selectedcats = array($maincat);
                $item->catid = $maincat;
            } else {
                $selectedcats = array();
            }
            if ($tparams->get('cid_default')) {
                $selectedcats = $tparams->get('cid_default');
            }
            if ($tparams->get('catid_default')) {
                $item->catid = $tparams->get('catid_default');
            }
        } else {
            // NOTE: This will normally return the already set versioned value of categories ($item->categories)
            $selectedcats = $this->get('Catsselected');
        }
        //$selectedcats 	= $isnew ? array() : $fields['categories']->value;
        //echo "<br/>row->tags: "; print_r($item->tags);
        //echo "<br/>usedtagsIds: "; print_r($usedtagsIds);
        //echo "<br/>usedtags (data): "; print_r($usedtags);
        //echo "<br/>row->categories: "; print_r($item->categories);
        //echo "<br/>selectedcats: "; print_r($selectedcats);
        // *********************************************************************************************
        // Build select lists for the form field. Only few of them are used in J1.6+, since we will use:
        // (a) form XML file to declare them and then (b) getInput() method form field to create them
        // *********************************************************************************************
        // First clean form data, we do this after creating the description field which may contain HTML
        JFilterOutput::objectHTMLSafe($item, ENT_QUOTES);
        $lists = array();
        // build granular access list
        if (!FLEXI_J16GE) {
            if (FLEXI_ACCESS) {
                if (isset($user->level)) {
                    $lists['access'] = FAccess::TabGmaccess($item, 'item', 1, 0, 0, 1, 0, 1, 0, 1, 1);
                } else {
                    $lists['access'] = JText::_('Your profile has been changed, please logout to access to the permissions');
                }
            } else {
                $lists['access'] = JHTML::_('list.accesslevel', $item);
                // created but not used in J1.5 backend form
            }
        }
        // build state list
        $_arc_ = FLEXI_J16GE ? 2 : -1;
        $non_publishers_stategrp = $perms['isSuperAdmin'] || $item->state == -3 || $item->state == -4;
        $special_privelege_stategrp = $item->state == $_arc_ || $perms['canarchive'] || ($item->state == -2 || $perms['candelete']);
        $state = array();
        // Using <select> groups
        if ($non_publishers_stategrp || $special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_PUBLISHERS_WORKFLOW_STATES'));
        }
        $state[] = JHTML::_('select.option', 1, JText::_('FLEXI_PUBLISHED'));
        $state[] = JHTML::_('select.option', 0, JText::_('FLEXI_UNPUBLISHED'));
        $state[] = JHTML::_('select.option', -5, JText::_('FLEXI_IN_PROGRESS'));
        // States reserved for workflow
        if ($non_publishers_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_NON_PUBLISHERS_WORKFLOW_STATES'));
        }
        if ($item->state == -3 || $perms['isSuperAdmin']) {
            $state[] = JHTML::_('select.option', -3, JText::_('FLEXI_PENDING'));
        }
        if ($item->state == -4 || $perms['isSuperAdmin']) {
            $state[] = JHTML::_('select.option', -4, JText::_('FLEXI_TO_WRITE'));
        }
        // Special access states
        if ($special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_SPECIAL_ACTION_STATES'));
        }
        if ($item->state == $_arc_ || $perms['canarchive']) {
            $state[] = JHTML::_('select.option', $_arc_, JText::_('FLEXI_ARCHIVED'));
        }
        if ($item->state == -2 || $perms['candelete']) {
            $state[] = JHTML::_('select.option', -2, JText::_('FLEXI_TRASHED'));
        }
        // Close last <select> group
        if ($non_publishers_stategrp || $special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
        }
        $fieldname = FLEXI_J16GE ? 'jform[state]' : 'state';
        $elementid = FLEXI_J16GE ? 'jform_state' : 'state';
        $class = 'use_select2_lib';
        $attribs = 'class="' . $class . '"';
        $lists['state'] = JHTML::_('select.genericlist', $state, $fieldname, $attribs, 'value', 'text', $item->state, $elementid);
        if (!FLEXI_J16GE) {
            $lists['state'] = str_replace('<optgroup label="">', '</optgroup>', $lists['state']);
        }
        // *** BOF: J2.5 SPECIFIC SELECT LISTS
        if (FLEXI_J16GE) {
            // build featured flag
            $fieldname = 'jform[featured]';
            $elementid = 'jform_featured';
            /*
            $options = array();
            $options[] = JHTML::_('select.option',  0, JText::_( 'FLEXI_NO' ) );
            $options[] = JHTML::_('select.option',  1, JText::_( 'FLEXI_YES' ) );
            $attribs = FLEXI_J16GE ? ' style ="float:none!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
            $lists['featured'] = JHTML::_('select.radiolist', $options, $fieldname, $attribs, 'value', 'text', $item->featured, $elementid);
            */
            $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
            $attribs = ' class="' . $classes . '" ';
            $i = 1;
            $options = array(0 => JText::_('FLEXI_NO'), 1 => JText::_('FLEXI_YES'));
            $lists['featured'] = '';
            foreach ($options as $option_id => $option_label) {
                $checked = $option_id == $item->featured ? ' checked="checked"' : '';
                $elementid_no = $elementid . '_' . $i;
                if (!$prettycheckable_added) {
                    $lists['featured'] .= '<label class="fccheckradio_lbl" for="' . $elementid_no . '">';
                }
                $extra_params = !$prettycheckable_added ? '' : ' data-label="' . JText::_($option_label) . '" data-labelPosition="right" data-customClass="fcradiocheck"';
                $lists['featured'] .= ' <input type="radio" id="' . $elementid_no . '" element_group_id="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="' . $option_id . '" ' . $checked . $extra_params . ' />';
                if (!$prettycheckable_added) {
                    $lists['featured'] .= '&nbsp;' . JText::_($option_label) . '</label>';
                }
                $i++;
            }
        }
        // *** EOF: J1.5 SPECIFIC SELECT LISTS
        // build version approval list
        $fieldname = FLEXI_J16GE ? 'jform[vstate]' : 'vstate';
        $elementid = FLEXI_J16GE ? 'jform_vstate' : 'vstate';
        /*
        $options = array();
        $options[] = JHTML::_('select.option',  1, JText::_( 'FLEXI_NO' ) );
        $options[] = JHTML::_('select.option',  2, JText::_( 'FLEXI_YES' ) );
        $attribs = FLEXI_J16GE ? ' style ="float:left!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
        $lists['vstate'] = JHTML::_('select.radiolist', $options, $fieldname, $attribs, 'value', 'text', 2, $elementid);
        */
        $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
        $attribs = ' class="' . $classes . '" ';
        $i = 1;
        $options = array(1 => JText::_('FLEXI_NO'), 2 => JText::_('FLEXI_YES'));
        $lists['vstate'] = '';
        foreach ($options as $option_id => $option_label) {
            $checked = $option_id == 2 ? ' checked="checked"' : '';
            $elementid_no = $elementid . '_' . $i;
            if (!$prettycheckable_added) {
                $lists['vstate'] .= '<label class="fccheckradio_lbl" for="' . $elementid_no . '">';
            }
            $extra_params = !$prettycheckable_added ? '' : ' data-label="' . JText::_($option_label) . '" data-labelPosition="right" data-customClass="fcradiocheck"';
            $lists['vstate'] .= ' <input type="radio" id="' . $elementid_no . '" element_group_id="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="' . $option_id . '" ' . $checked . $extra_params . ' />';
            if (!$prettycheckable_added) {
                $lists['vstate'] .= '&nbsp;' . JText::_($option_label) . '</label>';
            }
            $i++;
        }
        // build field for notifying subscribers
        if (!$subscribers) {
            $lists['notify'] = !$isnew ? JText::_('FLEXI_NO_SUBSCRIBERS_EXIST') : '';
        } else {
            // b. Check if notification emails to subscribers , were already sent during current session
            $subscribers_notified = $session->get('subscribers_notified', array(), 'flexicontent');
            if (!empty($subscribers_notified[$item->id])) {
                $lists['notify'] = JText::_('FLEXI_SUBSCRIBERS_ALREADY_NOTIFIED');
            } else {
                // build favs notify field
                $fieldname = FLEXI_J16GE ? 'jform[notify]' : 'notify';
                $elementid = FLEXI_J16GE ? 'jform_notify' : 'notify';
                /*
                $attribs = FLEXI_J16GE ? ' style ="float:none!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
                $lists['notify'] = '<input type="checkbox" name="jform[notify]" id="jform_notify" '.$attribs.' /> '. $lbltxt;
                */
                $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
                $attribs = ' class="' . $classes . '" ';
                $lbltxt = $subscribers . ' ' . JText::_($subscribers > 1 ? 'FLEXI_SUBSCRIBERS' : 'FLEXI_SUBSCRIBER');
                if (!$prettycheckable_added) {
                    $lists['notify'] .= '<label class="fccheckradio_lbl" for="' . $elementid . '">';
                }
                $extra_params = !$prettycheckable_added ? '' : ' data-label="' . $lbltxt . '" data-labelPosition="right" data-customClass="fcradiocheck"';
                $lists['notify'] = ' <input type="checkbox" id="' . $elementid . '" element_group_id="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="1" ' . $extra_params . ' checked="checked" />';
                if (!$prettycheckable_added) {
                    $lists['notify'] .= '&nbsp;' . $lbltxt . '</label>';
                }
            }
        }
        // Retrieve author configuration
        $db->setQuery('SELECT author_basicparams FROM #__flexicontent_authors_ext WHERE user_id = ' . $user->id);
        if ($authorparams = $db->loadResult()) {
            $authorparams = FLEXI_J16GE ? new JRegistry($authorparams) : new JParameter($authorparams);
        }
        // Get author's maximum allowed categories per item and set js limitation
        $max_cat_assign = !$authorparams ? 0 : intval($authorparams->get('max_cat_assign', 0));
        $document->addScriptDeclaration('
			max_cat_assign_fc = ' . $max_cat_assign . ';
			existing_cats_fc  = ["' . implode('","', $selectedcats) . '"];
			max_cat_overlimit_msg_fc = "' . JText::_('FLEXI_TOO_MANY_ITEM_CATEGORIES', true) . '";
		');
        // Creating categorories tree for item assignment, we use the 'create' privelege
        $actions_allowed = array('core.create');
        // Featured categories form field
        $featured_cats_parent = $params->get('featured_cats_parent', 0);
        $featured_cats = array();
        $enable_featured_cid_selector = $perms['multicat'] && $perms['canchange_featcat'];
        if ($featured_cats_parent) {
            $featured_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $featured_cats_parent, $depth_limit = 0);
            $featured_sel = array();
            foreach ($selectedcats as $item_cat) {
                if (isset($featured_tree[$item_cat])) {
                    $featured_sel[] = $item_cat;
                }
            }
            $class = "use_select2_lib select2_list_selected";
            $attribs = 'class="' . $class . '" multiple="multiple" size="8"';
            $attribs .= $enable_featured_cid_selector ? '' : ' disabled="disabled"';
            $fieldname = FLEXI_J16GE ? 'jform[featured_cid][]' : 'featured_cid[]';
            $lists['featured_cid'] = ($enable_featured_cid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($featured_tree, $fieldname, $featured_sel, 3, $attribs, true, true, $actions_allowed);
        } else {
            // Do not display, if not configured or not allowed to the user
            $lists['featured_cid'] = false;
        }
        // Multi-category form field, for user allowed to use multiple categories
        $lists['cid'] = '';
        $enable_cid_selector = $perms['multicat'] && $perms['canchange_seccat'];
        if (1) {
            if ($tparams->get('cid_allowed_parent')) {
                $cid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $tparams->get('cid_allowed_parent'), $depth_limit = 0);
            } else {
                $cid_tree =& $categories;
            }
            // Get author's maximum allowed categories per item and set js limitation
            $max_cat_assign = !$authorparams ? 0 : intval($authorparams->get('max_cat_assign', 0));
            $document->addScriptDeclaration('
				max_cat_assign_fc = ' . $max_cat_assign . ';
				existing_cats_fc  = ["' . implode('","', $selectedcats) . '"];
				max_cat_overlimit_msg_fc = "' . JText::_('FLEXI_TOO_MANY_ITEM_CATEGORIES', true) . '";
			');
            $class = "mcat use_select2_lib select2_list_selected";
            $class .= $max_cat_assign ? " validate-fccats" : " validate";
            $attribs = 'class="' . $class . '" multiple="multiple" size="20"';
            $attribs .= $enable_cid_selector ? '' : ' disabled="disabled"';
            $fieldname = FLEXI_J16GE ? 'jform[cid][]' : 'cid[]';
            $skip_subtrees = $featured_cats_parent ? array($featured_cats_parent) : array();
            $lists['cid'] = ($enable_cid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($cid_tree, $fieldname, $selectedcats, false, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees, $disable_subtrees = array());
        } else {
            if (count($selectedcats) > 1) {
                foreach ($selectedcats as $catid) {
                    $cat_titles[$catid] = $globalcats[$catid]->title;
                }
                $lists['cid'] .= implode(', ', $cat_titles);
            } else {
                $lists['cid'] = false;
            }
        }
        // Main category form field
        $class = 'scat use_select2_lib';
        if ($perms['multicat']) {
            $class .= ' validate-catid';
        } else {
            $class .= ' required';
        }
        $attribs = 'class="' . $class . '"';
        $fieldname = FLEXI_J16GE ? 'jform[catid]' : 'catid';
        $enable_catid_selector = $isnew && !$tparams->get('catid_default') || !$isnew && empty($item->catid) || $perms['canchange_cat'];
        if ($tparams->get('catid_allowed_parent')) {
            $catid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $tparams->get('catid_allowed_parent'), $depth_limit = 0);
        } else {
            $catid_tree =& $categories;
        }
        $lists['catid'] = false;
        if (!empty($catid_tree)) {
            $disabled = $enable_catid_selector ? '' : ' disabled="disabled"';
            $attribs .= $disabled;
            $lists['catid'] = ($enable_catid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($catid_tree, $fieldname, $item->catid, 2, $attribs, true, true, $actions_allowed);
        } else {
            if (!$isnew && $item->catid) {
                $lists['catid'] = $globalcats[$item->catid]->title;
            }
        }
        //buid types selectlist
        $class = 'required use_select2_lib';
        $attribs = 'class="' . $class . '"';
        $fieldname = FLEXI_J16GE ? 'jform[type_id]' : 'type_id';
        $elementid = FLEXI_J16GE ? 'jform_type_id' : 'type_id';
        $lists['type'] = flexicontent_html::buildtypesselect($types, $fieldname, $typesselected->id, 1, $attribs, $elementid, $check_perms = true);
        //build languages list
        $allowed_langs = !$authorparams ? null : $authorparams->get('langs_allowed', null);
        $allowed_langs = !$allowed_langs ? null : FLEXIUtilities::paramToArray($allowed_langs);
        if (!$isnew && $allowed_langs) {
            $allowed_langs[] = $item->language;
        }
        // We will not use the default getInput() function of J1.6+ since we want to create a radio selection field with flags
        // we could also create a new class and override getInput() method but maybe this is an overkill, we may do it in the future
        $language_fieldname = FLEXI_J16GE ? 'jform[language]' : 'language';
        if (FLEXI_FISH || FLEXI_J16GE) {
            $lists['languages'] = flexicontent_html::buildlanguageslist($language_fieldname, '', $item->language, 3, $allowed_langs);
        }
        // Label for current item state: published, unpublished, archived etc
        switch ($item->state) {
            case 0:
                $published = JText::_('FLEXI_UNPUBLISHED');
                break;
            case 1:
                $published = JText::_('FLEXI_PUBLISHED');
                break;
            case -1:
                $published = JText::_('FLEXI_ARCHIVED');
                break;
            case -3:
                $published = JText::_('FLEXI_PENDING');
                break;
            case -5:
                $published = JText::_('FLEXI_IN_PROGRESS');
                break;
            case -4:
            default:
                $published = JText::_('FLEXI_TO_WRITE');
                break;
        }
        // **************************************************************
        // Handle Item Parameters Creation and Load their values for J1.5
        // In J1.6+ we declare them in the item form XML file
        // **************************************************************
        if (!FLEXI_J16GE) {
            // Create the form parameters object
            if (FLEXI_ACCESS) {
                $formparams = new JParameter('', JPATH_COMPONENT . DS . 'models' . DS . 'item2.xml');
            } else {
                $formparams = new JParameter('', JPATH_COMPONENT . DS . 'models' . DS . 'item.xml');
            }
            // Details Group
            $active = intval($item->created_by) ? intval($item->created_by) : $user->get('id');
            if (!FLEXI_ACCESS) {
                $formparams->set('access', $item->access);
            }
            $formparams->set('created_by', $active);
            $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 == $db->getNullDate() || 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'));
            }
            // Advanced Group
            $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]);
                }
            }
            // Metadata Group
            $formparams->set('description', $item->metadesc);
            $formparams->set('keywords', $item->metakey);
            $formparams->loadINI($item->metadata);
        } else {
            if (JHTML::_('date', $item->publish_down, 'Y') <= 1969 || $item->publish_down == $db->getNullDate() || empty($item->publish_down)) {
                $form->setValue('publish_down', null, 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);
            }
        }
        // ******************************
        // Assign data to VIEW's template
        // ******************************
        $this->assignRef('document', $document);
        $this->assignRef('lists', $lists);
        $this->assignRef('row', $item);
        if (FLEXI_J16GE) {
            $this->assignRef('form', $form);
        } else {
            $this->assignRef('editor', $editor);
            $this->assignRef('pane', $pane);
            $this->assignRef('formparams', $formparams);
        }
        if ($enable_translation_groups) {
            $this->assignRef('lang_assocs', $langAssocs);
        }
        if (FLEXI_FISH || FLEXI_J16GE) {
            $this->assignRef('langs', $langs);
        }
        $this->assignRef('typesselected', $typesselected);
        $this->assignRef('published', $published);
        $this->assignRef('nullDate', $nullDate);
        $this->assignRef('subscribers', $subscribers);
        $this->assignRef('fields', $fields);
        $this->assignRef('versions', $versions);
        $this->assignRef('pagecount', $pagecount);
        $this->assignRef('params', $params);
        $this->assignRef('tparams', $tparams);
        $this->assignRef('tmpls', $tmpls);
        $this->assignRef('usedtags', $usedtags);
        $this->assignRef('perms', $perms);
        $this->assignRef('current_page', $current_page);
        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;
        }
    }
Ejemplo n.º 10
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);
	}