Example #1
0
 function display($tpl = null)
 {
     //initialise variables
     global $globalcats;
     $app = JFactory::getApplication();
     $option = JRequest::getVar('option');
     $view = JRequest::getVar('view');
     $user = JFactory::getUser();
     $db = JFactory::getDBO();
     $document = JFactory::getDocument();
     $cparams = JComponentHelper::getParams('com_flexicontent');
     $print_logging_info = $cparams->get('print_logging_info');
     if ($print_logging_info) {
         global $fc_run_times;
     }
     JHTML::_('behavior.tooltip');
     //get vars
     $order_property = !FLEXI_J16GE ? 'c.ordering' : 'c.lft';
     $filter_order = $app->getUserStateFromRequest($option . '.' . $view . '.filter_order', 'filter_order', $order_property, 'cmd');
     $filter_order_Dir = $app->getUserStateFromRequest($option . '.' . $view . '.filter_order_Dir', 'filter_order_Dir', '', 'word');
     $filter_state = $app->getUserStateFromRequest($option . '.' . $view . '.filter_state', 'filter_state', '', 'string');
     $filter_cats = $app->getUserStateFromRequest($option . '.' . $view . '.filter_cats', 'filter_cats', '', 'int');
     $filter_level = $app->getUserStateFromRequest($option . '.' . $view . '.filter_level', 'filter_level', '', 'string');
     $filter_access = $app->getUserStateFromRequest($option . '.' . $view . '.filter_access', 'filter_access', '', 'string');
     if (FLEXI_J16GE) {
         $filter_language = $app->getUserStateFromRequest($option . '.' . $view . '.filter_language', 'filter_language', '', 'string');
     }
     $search = $app->getUserStateFromRequest($option . '.' . $view . '.search', 'search', '', 'string');
     $search = FLEXI_J16GE ? $db->escape(trim(JString::strtolower($search))) : $db->getEscaped(trim(JString::strtolower($search)));
     // Prepare the document: add css files, etc
     $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');
         }
     }
     // Get User's Global Permissions
     $perms = FlexicontentHelperPerm::getPerm();
     // Create Submenu (and also check access to current view)
     FLEXISubmenu('CanCats');
     // Create document/toolbar titles
     $doc_title = JText::_('FLEXI_CATEGORIES');
     $site_title = $document->getTitle();
     JToolBarHelper::title($doc_title, 'fc_categories');
     $document->setTitle($doc_title . ' - ' . $site_title);
     // ******************
     // Create the toolbar
     // ******************
     $js = "window.addEvent('domready', function(){";
     $contrl = FLEXI_J16GE ? "categories." : "";
     $contrl_singular = FLEXI_J16GE ? "category." : "";
     $toolbar = JToolBar::getInstance('toolbar');
     // Copy Parameters
     $btn_task = '';
     $popup_load_url = JURI::base() . 'index.php?option=com_flexicontent&view=categories&layout=params&tmpl=component';
     if (FLEXI_J30GE || !FLEXI_J16GE) {
         // Layout of Popup button broken in J3.1, add in J1.5 it generates duplicate HTML tag id (... just for validation), so add manually
         $js .= "\n\t\t\t\tjQuery('#toolbar-params a.toolbar, #toolbar-params button')\n\t\t\t\t\t.attr('onclick', 'javascript:;')\n\t\t\t\t\t.attr('href', '" . $popup_load_url . "')\n\t\t\t\t\t.attr('rel', '{handler: \\'iframe\\', size: {x: 600, y: 440}, onClose: function() {}}');\n\t\t\t";
         JToolBarHelper::custom($btn_task, 'params.png', 'params_f2.png', 'FLEXI_COPY_PARAMS', false);
         JHtml::_('behavior.modal', '#toolbar-params a.toolbar, #toolbar-params button');
     } else {
         $toolbar->appendButton('Popup', 'params', JText::_('FLEXI_COPY_PARAMS'), str_replace('&', '&', $popup_load_url), 600, 440);
     }
     //if (FLEXI_J16GE)
     //	$toolbar->appendButton('Popup', 'move', JText::_('FLEXI_COPY_MOVE'), JURI::base().'index.php?option=com_flexicontent&view=categories&layout=batch&tmpl=component', 800, 440);
     JToolBarHelper::divider();
     $add_divider = false;
     if (!FLEXI_J16GE || $user->authorise('core.create', 'com_flexicontent')) {
         $cancreate_cat = true;
     } else {
         $usercats = FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.create'), $require_all = true, $check_published = true, $specific_catids = false, $find_first = true);
         $cancreate_cat = count($usercats) > 0;
     }
     if ($cancreate_cat) {
         JToolBarHelper::addNew($contrl_singular . 'add');
         $add_divider = true;
     }
     if (!FLEXI_J16GE || ($user->authorise('core.edit', 'com_flexicontent') || $user->authorise('core.edit.own', 'com_flexicontent'))) {
         JToolBarHelper::editList($contrl_singular . 'edit');
         $add_divider = true;
     }
     if (FLEXI_J16GE && $user->authorise('core.admin', 'checkin')) {
         JToolBarHelper::checkin($contrl . 'checkin');
         $add_divider = true;
     }
     if ($add_divider) {
         JToolBarHelper::divider();
     }
     $add_divider = false;
     if (!FLEXI_J16GE || ($user->authorise('core.edit.state', 'com_flexicontent') || $user->authorise('core.edit.state.own', 'com_flexicontent'))) {
         JToolBarHelper::publishList($contrl . 'publish');
         JToolBarHelper::unpublishList($contrl . 'unpublish');
         JToolBarHelper::divider();
         if (FLEXI_J16GE) {
             JToolBarHelper::archiveList($contrl . 'archive');
         }
     }
     $add_divider = false;
     if (!FLEXI_J16GE || $filter_state == -2 && $user->authorise('core.delete', 'com_flexicontent')) {
         //JToolBarHelper::deleteList(JText::_('FLEXI_ARE_YOU_SURE'), $contrl.'remove');
         // This will work in J2.5+ too and is offers more options (above a little bogus in J1.5, e.g. bad HTML id tag)
         $msg_alert = JText::sprintf('FLEXI_SELECT_LIST_ITEMS_TO', JText::_('FLEXI_DELETE'));
         $msg_confirm = JText::_('FLEXI_ITEMS_DELETE_CONFIRM');
         $btn_task = $contrl . 'remove';
         $extra_js = "";
         flexicontent_html::addToolBarButton('FLEXI_DELETE', 'delete', '', $msg_alert, $msg_confirm, $btn_task, $extra_js, $btn_list = true, $btn_menu = true, $btn_confirm = true);
         $add_divider = true;
     } elseif ($user->authorise('core.edit.state', 'com_flexicontent')) {
         JToolBarHelper::trash($contrl . 'trash');
         $add_divider = true;
     }
     if ($add_divider) {
         JToolBarHelper::divider();
     }
     if ($perms->CanConfig) {
         //JToolBarHelper::custom($contrl.'rebuild', 'refresh.png', 'refresh_f2.png', 'JTOOLBAR_REBUILD', false);
         $session = JFactory::getSession();
         $fc_screen_width = (int) $session->get('fc_screen_width', 0, 'flexicontent');
         $_width = $fc_screen_width && $fc_screen_width - 84 > 940 ? $fc_screen_width - 84 > 1400 ? 1400 : $fc_screen_width - 84 : 940;
         $fc_screen_height = (int) $session->get('fc_screen_height', 0, 'flexicontent');
         $_height = $fc_screen_height && $fc_screen_height - 128 > 550 ? $fc_screen_height - 128 > 1000 ? 1000 : $fc_screen_height - 128 : 550;
         JToolBarHelper::preferences('com_flexicontent', $_height, $_width, 'Configuration');
     }
     $js .= "});";
     $document->addScriptDeclaration($js);
     //Get data from the model
     if ($print_logging_info) {
         $start_microtime = microtime(true);
     }
     if (FLEXI_J16GE) {
         $rows = $this->get('Items');
     } else {
         $rows = $this->get('Data');
     }
     if ($print_logging_info) {
         @($fc_run_times['execute_main_query'] += round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
     }
     // Get assigned items
     $model = $this->getModel();
     $rowids = array();
     foreach ($rows as $row) {
         $rowids[] = $row->id;
     }
     if ($print_logging_info) {
         $start_microtime = microtime(true);
     }
     $rowtotals = $model->getAssignedItems($rowids);
     if ($print_logging_info) {
         @($fc_run_times['execute_sec_queries'] += round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
     }
     foreach ($rows as $row) {
         $row->nrassigned = isset($rowtotals[$row->id]) ? $rowtotals[$row->id]->nrassigned : 0;
     }
     // Parse configuration for every category
     foreach ($rows as $cat) {
         $cat->config = FLEXI_J16GE ? new JRegistry($cat->config) : new JParameter($cat->config);
     }
     if (FLEXI_J16GE) {
         $this->state = $this->get('State');
         // Preprocess the list of items to find ordering divisions.
         foreach ($rows as &$item) {
             $this->ordering[$item->parent_id][] = $item->id;
         }
     }
     $pagination = $this->get('Pagination');
     $categories =& $globalcats;
     $lists['copyid'] = flexicontent_cats::buildcatselect($categories, 'copycid', '', 2, 'class="inputbox"', false, true, $actions_allowed = array('core.edit'));
     $lists['destid'] = flexicontent_cats::buildcatselect($categories, 'destcid[]', '', false, 'class="inputbox" size="15" multiple="true"', false, true, $actions_allowed = array('core.edit'));
     // *******************
     // Create Form Filters
     // *******************
     // filter by a category (it's subtree will be displayed)
     $categories = $globalcats;
     $lists['cats'] = flexicontent_cats::buildcatselect($categories, 'filter_cats', $filter_cats, 2, 'class="inputbox" size="1" onchange="this.form.submit();"', $check_published = true, $check_perms = false);
     // filter depth level
     $options = array();
     $options[] = JHtml::_('select.option', '', JText::_('FLEXI_SELECT_MAX_DEPTH'));
     for ($i = 1; $i <= 10; $i++) {
         $options[] = JHtml::_('select.option', $i, $i);
     }
     $fieldname = $elementid = 'filter_level';
     $attribs = ' size="1" class="inputbox" onchange="this.form.submit();" ';
     $lists['level'] = JHTML::_('select.genericlist', $options, $fieldname, $attribs, 'value', 'text', $filter_level, $elementid, $translate = true);
     // filter publication state
     if (FLEXI_J16GE) {
         $options = JHtml::_('jgrid.publishedOptions');
         array_unshift($options, JHtml::_('select.option', '', JText::_('JOPTION_SELECT_PUBLISHED')));
         $fieldname = $elementid = 'filter_state';
         $attribs = ' size="1" class="inputbox" onchange="Joomla.submitform()" ';
         $lists['state'] = JHTML::_('select.genericlist', $options, $fieldname, $attribs, 'value', 'text', $filter_state, $elementid, $translate = true);
     } else {
         $lists['state'] = JHTML::_('grid.state', $filter_state);
     }
     if (FLEXI_J16GE) {
         // filter access level
         $options = JHtml::_('access.assetgroups');
         array_unshift($options, JHtml::_('select.option', '', JText::_('JOPTION_SELECT_ACCESS')));
         $fieldname = $elementid = 'filter_access';
         $attribs = ' size="1" class="inputbox" onchange="Joomla.submitform()" ';
         $lists['access'] = JHTML::_('select.genericlist', $options, $fieldname, $attribs, 'value', 'text', $filter_access, $elementid, $translate = true);
         // filter language
         $lists['language'] = flexicontent_html::buildlanguageslist('filter_language', 'size="1" class="inputbox" onchange="submitform();"', $filter_language, 2);
     } else {
         // filter access level
         $options = array();
         $options[] = JHtml::_('select.option', '', JText::_('FLEXI_SELECT_ACCESS_LEVEL'));
         $options[] = JHtml::_('select.option', '0', JText::_('Public'));
         $options[] = JHtml::_('select.option', '1', JText::_('Registered'));
         $options[] = JHtml::_('select.option', '2', JText::_('SPECIAL'));
         $fieldname = $elementid = 'filter_access';
         $attribs = ' size="1" class="inputbox" onchange="this.form.submit()" ';
         $lists['access'] = JHTML::_('select.genericlist', $options, $fieldname, $attribs, 'value', 'text', $filter_access, $elementid, $translate = true);
     }
     // filter search word
     $lists['search'] = $search;
     // table ordering
     $lists['order_Dir'] = $filter_order_Dir;
     $lists['order'] = $filter_order;
     $ordering = $lists['order'] == $order_property ? $order_property : '';
     //assign data to template
     $this->assignRef('lists', $lists);
     $this->assignRef('rows', $rows);
     $this->assignRef('perms', $perms);
     if (FLEXI_J16GE) {
         $this->assignRef('orderingx', $ordering);
     } else {
         $this->assignRef('ordering', $ordering);
     }
     $this->assignRef('pagination', $pagination);
     $this->assignRef('user', $user);
     parent::display($tpl);
 }
Example #2
0
 function display($tpl = null)
 {
     global $globalcats;
     $app = JFactory::getApplication();
     $user = JFactory::getUser();
     $document = JFactory::getDocument();
     if (FLEXI_J16GE) {
         JFactory::getLanguage()->load('com_categories', JPATH_ADMINISTRATOR, 'en-GB', true);
         JFactory::getLanguage()->load('com_categories', JPATH_ADMINISTRATOR, null, true);
     }
     // ***********************************************************
     // Get category data, and check if item is already checked out
     // ***********************************************************
     // Get data from the model
     $model = $this->getModel();
     if (FLEXI_J16GE) {
         $row = $this->get('Item');
         $form = $this->get('Form');
     } else {
         $row = $this->get('Category');
     }
     $catparams = FLEXI_J16GE ? new JRegistry($row->params) : new JParameter($row->params);
     $cid = $row->id;
     $isnew = !$cid;
     // Check category is checked out by different editor / administrator
     if (!$isnew && $model->isCheckedOut($user->get('id'))) {
         JError::raiseWarning('SOME_ERROR_CODE', $row->title . ' ' . JText::_('FLEXI_EDITED_BY_ANOTHER_ADMIN'));
         $app->redirect('index.php?option=com_flexicontent&view=categories');
     }
     // ***************************************************************************
     // Currently access checking for category add/edit form , it is done here, for
     // most other views we force going though the controller and checking it there
     // ***************************************************************************
     // *********************************************************************************************
     // Global Permssions checking (needed because this view can be called without a controller task)
     // *********************************************************************************************
     // Get global permissions
     $perms = FlexicontentHelperPerm::getPerm();
     // handles super admins correctly
     // Check no access to categories management (Global permission)
     if (!$perms->CanCats) {
         $app->redirect('index.php?option=com_flexicontent', JText::_('FLEXI_NO_ACCESS'));
     }
     // Check no privilege to create new categories (Global permission)
     if ($isnew && !$perms->CanAddCats) {
         JError::raiseWarning(403, JText::_('FLEXI_NO_ACCESS_CREATE'));
         $app->redirect('index.php?option=com_flexicontent');
     }
     // ************************************************************************************
     // Record Permssions (needed because this view can be called without a controller task)
     // ************************************************************************************
     // Get edit privilege for current category
     if (!$isnew) {
         if (FLEXI_J16GE) {
             $isOwner = $row->get('created_by') == $user->id;
             $rights = FlexicontentHelperPerm::checkAllItemAccess($user->id, 'category', $cid);
             $canedit_cat = in_array('edit', $rights) || in_array('edit.own', $rights) && $isOwner;
         } else {
             if (FLEXI_ACCESS) {
                 $rights = FAccess::checkAllItemAccess('com_content', 'users', $user->gmid, 0, $row->id);
                 $canedit_cat = $user->gid < 25 ? in_array('edit', $rights) || in_array('editown', $rights) : 1;
             } else {
                 $canedit_cat = true;
             }
         }
     }
     // Get if we can create inside at least one (com_content) category
     if (!FLEXI_J16GE || $user->authorise('core.create', 'com_flexicontent')) {
         $cancreate_cat = true;
     } else {
         $usercats = FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.create'), $require_all = true, $check_published = true, $specific_catids = false, $find_first = true);
         $cancreate_cat = count($usercats) > 0;
     }
     // Creating new category: Check if user can create inside any existing category
     if ($isnew && !$cancreate_cat) {
         $acc_msg = JText::_('FLEXI_NO_ACCESS_CREATE') . "<br/>" . (FLEXI_J16GE ? JText::_('FLEXI_CANNOT_ADD_CATEGORY_REASON') : "");
         JError::raiseWarning(403, $acc_msg);
         $app->redirect('index.php?option=com_flexicontent&view=categories');
     }
     // Editing existing category: Check if user can edit existing (current) category
     if (!$isnew && !$canedit_cat) {
         $acc_msg = JText::_('FLEXI_NO_ACCESS_EDIT') . "<br/>" . JText::_('FLEXI_CANNOT_EDIT_CATEGORY_REASON');
         JError::raiseWarning(403, $acc_msg);
         $app->redirect('index.php?option=com_flexicontent&view=categories');
     }
     // **************************************************
     // Include needed files and add needed js / css files
     // **************************************************
     FLEXI_J30GE ? JHtml::_('behavior.framework', true) : JHTML::_('behavior.mootools');
     flexicontent_html::loadFramework('jQuery');
     flexicontent_html::loadFramework('select2');
     // Load pane behavior
     jimport('joomla.html.pane');
     // Load tooltips
     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');
     // ********************
     // Initialise variables
     // ********************
     $editor_name = $user->getParam('editor', $app->getCfg('editor'));
     $editor = JFactory::getEditor($editor_name);
     $cparams = JComponentHelper::getParams('com_flexicontent');
     $bar = JToolBar::getInstance('toolbar');
     if (!FLEXI_J16GE) {
         $pane = JPane::getInstance('sliders');
         $tpane = JPane::getInstance('tabs', array('startOffset' => 0, 'allowAllClose' => true, 'opacityTransition' => true, 'duration' => 600));
     }
     $categories = $globalcats;
     // ******************
     // Create the toolbar
     // ******************
     // Create Toolbar title and add the preview button
     if (!$isnew) {
         JToolBarHelper::title(JText::_('FLEXI_EDIT_CATEGORY'), 'fc_categoryedit');
         $autologin = $cparams->get('autoflogin', 1) ? '&fcu=' . $user->username . '&fcp=' . $user->password : '';
         $previewlink = JRoute::_(JURI::root() . FlexicontentHelperRoute::getCategoryRoute($categories[$cid]->slug)) . $autologin;
         // Add a preview button
         $bar->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 {
         JToolBarHelper::title(JText::_('FLEXI_NEW_CATEGORY'), 'fc_categoryadd');
     }
     // Add apply and save buttons
     if (FLEXI_J16GE) {
         JToolBarHelper::apply('category.apply');
         JToolBarHelper::save('category.save');
     } else {
         JToolBarHelper::apply();
         JToolBarHelper::save();
     }
     // Add a save and new button, if user can create inside at least one (com_content) category
     if ($cancreate_cat) {
         if (FLEXI_J16GE) {
             JToolBarHelper::save2new('category.save2new');
         } else {
             JToolBarHelper::custom('saveandnew', 'savenew.png', 'savenew.png', 'FLEXI_SAVE_AND_NEW', false);
         }
     }
     // Add a save as copy button, if editing an existing category (J2.5 only)
     if (FLEXI_J16GE && !$isnew && $cancreate_cat) {
         JToolBarHelper::save2copy('category.save2copy');
     }
     // Add a cancel or close button
     if ($isnew) {
         if (FLEXI_J16GE) {
             JToolBarHelper::cancel('category.cancel');
         } else {
             JToolBarHelper::cancel();
         }
     } else {
         if (FLEXI_J16GE) {
             JToolBarHelper::cancel('category.cancel', 'JTOOLBAR_CLOSE');
         } else {
             JToolBarHelper::custom('cancel', 'cancel.png', 'cancel.png', 'CLOSE', false);
         }
     }
     // *******************************************
     // Prepare data to pass to the form's template
     // *******************************************
     if (!FLEXI_J16GE) {
         //clean data
         JFilterOutput::objectHTMLSafe($row, ENT_QUOTES, 'description');
         // Create the form
         $form = new JParameter($row->params, JPATH_COMPONENT . DS . 'models' . DS . 'category.xml');
         //$form->loadINI($row->attribs);
         //echo "<pre>"; print_r($form->_xml['templates']->_children[0]);  echo "<pre>"; print_r($form->_xml['templates']->param[0]); exit;
         foreach ($form->_xml['templates']->_children as $i => $child) {
             if (isset($child->_attributes['enableparam']) && !$cparams->get($child->_attributes['enableparam'])) {
                 unset($form->_xml['templates']->_children[$i]);
                 unset($form->_xml['templates']->param[$i]);
             }
         }
         foreach ($form->_xml['special']->_children as $i => $child) {
             if (isset($child->_attributes['enableparam']) && !$cparams->get($child->_attributes['enableparam'])) {
                 unset($form->_xml['special']->_children[$i]);
                 unset($form->_xml['special']->param[$i]);
             }
         }
     }
     // **********************************************************************************
     // Get Templates and apply Template Parameters values into the form fields structures
     // **********************************************************************************
     $themes = flexicontent_tmpl::getTemplates();
     $tmpls = $themes->category;
     foreach ($tmpls as $tmpl) {
         if (FLEXI_J16GE) {
             $jform = new JForm('com_flexicontent.template.category', array('control' => 'jform', 'load_data' => true));
             $jform->load($tmpl->params);
             $tmpl->params = $jform;
             // ... values applied at the template form file
         } else {
             $tmpl->params->loadINI($row->params);
         }
     }
     //build selectlists
     $Lists = array();
     if (!FLEXI_J16GE) {
         $javascript = "onchange=\"javascript:if (document.forms[0].image.options[selectedIndex].value!='') {document.imagelib.src='../images/stories/' + document.forms[0].image.options[selectedIndex].value} else {document.imagelib.src='../images/blank.png'}\"";
         $Lists['imagelist'] = JHTML::_('list.images', 'image', $row->image, $javascript, '/images/stories/');
         $Lists['access'] = JHTML::_('list.accesslevel', $row);
         // build granular access list
         if (FLEXI_ACCESS) {
             $Lists['access'] = FAccess::TabGmaccess($row, 'category', 1, 1, 1, 1, 1, 1, 1, 1, 1);
         }
     }
     $check_published = false;
     $check_perms = true;
     $actions_allowed = array('core.create');
     $fieldname = FLEXI_J16GE ? 'jform[parent_id]' : 'parent_id';
     $Lists['parent_id'] = flexicontent_cats::buildcatselect($categories, $fieldname, $row->parent_id, $top = 1, 'class="use_select2_lib"', $check_published, $check_perms, $actions_allowed, $require_all = true, $skip_subtrees = array(), $disable_subtrees = array($row->id));
     $check_published = false;
     $check_perms = true;
     $actions_allowed = array('core.edit', 'core.edit.own');
     $fieldname = FLEXI_J16GE ? 'jform[copycid]' : 'copycid';
     $Lists['copycid'] = flexicontent_cats::buildcatselect($categories, $fieldname, '', $top = 2, 'class="use_select2_lib"', $check_published, $check_perms, $actions_allowed, $require_all = false);
     $custom_options[''] = 'FLEXI_USE_GLOBAL';
     $custom_options['0'] = 'FLEXI_COMPONENT_ONLY';
     $custom_options['-1'] = 'FLEXI_PARENT_CAT_MULTI_LEVEL';
     $check_published = false;
     $check_perms = true;
     $actions_allowed = array('core.edit', 'core.edit.own');
     $fieldname = FLEXI_J16GE ? 'jform[special][inheritcid]' : 'params[inheritcid]';
     $Lists['inheritcid'] = flexicontent_cats::buildcatselect($categories, $fieldname, $catparams->get('inheritcid', ''), $top = false, 'class="use_select2_lib"', $check_published, $check_perms, $actions_allowed, $require_all = false, $skip_subtrees = array(), $disable_subtrees = array(), $custom_options);
     // ************************
     // Assign variables to view
     // ************************
     $this->assignRef('document', $document);
     $this->assignRef('Lists', $Lists);
     $this->assignRef('row', $row);
     $this->assignRef('form', $form);
     $this->assignRef('perms', $perms);
     $this->assignRef('editor', $editor);
     $this->assignRef('tmpls', $tmpls);
     $this->assignRef('cparams', $cparams);
     if (!FLEXI_J16GE) {
         $this->assignRef('pane', $pane);
         $this->assignRef('tpane', $tpane);
     }
     parent::display($tpl);
 }
 /**
  * Build a html select form field that displays a Category Tree
  *
  * The output is filtered (via FLEXIaccess or via J1.6+ permission) and has disabled specific categories
  * About Disabled categories:
  * - currently edited category is disabled
  * - if the user can view all categories then categories he has no permission are disabled !!!
  *
  * @param array $list
  * @param string $name
  * @param array $selected
  * @param bool $top
  * @param string $check_published
  * @param string $check_perms
  * @param string $require_all
  * @param array $skip_subtrees
  * @param array $disable_subtrees
  * @param array $custom_options
  *
  * @return a category form field element
  */
 public static function buildcatselect($list, $name, $selected, $top, $attribs = 'class="inputbox"', $check_published = false, $check_perms = true, $actions_allowed = array('core.create', 'core.edit', 'core.edit.own'), $require_all = true, $skip_subtrees = array(), $disable_subtrees = array(), $custom_options = array(), $disable_specific_cats = array(), $empty_errmsg = false)
 {
     // ***************************
     // Initialize needed variables
     // ***************************
     global $globalcats;
     $cparams = JComponentHelper::getParams('com_flexicontent');
     $user = JFactory::getUser();
     $controller = JRequest::getVar('controller');
     $task = JRequest::getVar('task');
     $print_logging_info = $cparams->get('print_logging_info');
     if ($print_logging_info) {
         global $fc_run_times;
         $start_microtime = microtime(true);
     }
     // Privilege of (a) viewing all categories (even if disabled) and (b) viewing as a tree
     require_once JPATH_ROOT . DS . 'components' . DS . 'com_flexicontent' . DS . 'helpers' . DS . 'permission.php';
     $viewallcats = FlexicontentHelperPerm::getPerm()->ViewAllCats;
     $viewtree = FlexicontentHelperPerm::getPerm()->ViewTree;
     // Global parameter to force always displaying of categories as tree
     if ($cparams->get('cats_always_astree', 1)) {
         $viewtree = 1;
     }
     // **************************************************************
     // Find user allowed categories to be used during Filtering below
     // **************************************************************
     if ($check_perms) {
         // Get user allowed categories, NOTE: if user (a) (J2.5) has 'core.admin' or (b) (J1.5) user is super admin (gid==25) then all cats are allowed
         $usercats = FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed, $require_all, $check_published);
         // NOTE: already selected categories will be allowed to the user, add them to the category list
         $selectedcats = !is_array($selected) ? array($selected) : $selected;
         $usercats_indexed = array_flip($usercats);
         foreach ($selectedcats as $selectedcat) {
             if ($selectedcat) {
                 $usercats_indexed[$selectedcat] = 1;
             }
         }
     }
     // *********************************************************************************
     // Excluded subtrees e.g. featured categories subtree in item form
     // Disabled subtrees e.g. existing children subtree when selecting category's parent
     // *********************************************************************************
     $skip_cats_arr = array();
     if (!empty($skip_subtrees)) {
         foreach ($skip_subtrees as $subtree_rootid) {
             if ($subtree_rootid && isset($globalcats[$subtree_rootid]->descendantsarray)) {
                 foreach ($globalcats[$subtree_rootid]->descendantsarray as $_excluded) {
                     $skip_cats_arr[$_excluded] = 1;
                 }
             }
         }
     }
     $disable_cats_arr = array();
     if (!empty($disable_subtrees)) {
         foreach ($disable_subtrees as $subtree_rootid) {
             if ($subtree_rootid && isset($globalcats[$subtree_rootid]->descendantsarray)) {
                 foreach ($globalcats[$subtree_rootid]->descendantsarray as $_excluded) {
                     $disable_cats_arr[$_excluded] = 1;
                 }
             }
         }
     }
     // Disable specific categories
     if (!empty($disable_specific_cats)) {
         foreach ($disable_specific_cats as $_excluded) {
             $disable_cats_arr[$_excluded] = 1;
         }
     }
     // **************************************************************************
     // TOP parameter: defines the APPROPRIATE PROMPT option at top of select list
     // **************************************************************************
     $cats_count = 0;
     $catlist = array();
     // A tree to select: e.g. a parent category
     if (!is_numeric($top) && strlen($top)) {
         $catlist[] = JHTML::_('select.option', '', $top);
     } else {
         if ($top == 1) {
             $catlist[] = JHTML::_('select.option', FLEXI_J16GE ? 1 : 0, JText::_('FLEXI_TOPLEVEL'));
         } else {
             if ($top == 2 || $top == -1) {
                 $catlist[] = JHTML::_('select.option', '', JText::_($top == -1 ? '' : 'FLEXI_SELECT_CAT'));
             } else {
                 if ($top == 3) {
                     $first_item = reset($list);
                     //$first_key = key($list);
                     $_first_item_treename = $first_item->treename;
                     $_first_item_title = $first_item->title;
                     $_first_item_id = $first_item->id;
                     $first_item->treename = $first_item->title = JText::_('FLEXI_SELECT_CAT');
                     $first_item->id = "";
                 }
             }
         }
     }
     // Extra custom options ... applies to all top parameters
     foreach ($custom_options as $custom_value => $custom_option) {
         $catlist[] = JHTML::_('select.option', $custom_value, '-- ' . JText::_($custom_option) . ' --');
     }
     // ********************************************************************************************************
     // Loop through categories to create the select option using user allowed categories (if filtering enabled)
     // ********************************************************************************************************
     foreach ($list as $cat) {
         $cat->treename = str_replace("&nbsp;", " ", strip_tags($cat->treename));
         $cat_title = $viewtree ? $cat->treename : $cat->title;
         if (!$check_published && $cat->published != 1) {
             $cat_title .= ' --U--';
         }
         if (!$check_published || $cat->published) {
             // CASE 1: SKIPPED categories e.g. featured categories subtree in item form
             if (isset($skip_cats_arr[$cat->id])) {
             } else {
                 if ($check_perms) {
                     // a. Category NOT ALLOWED
                     if (!isset($usercats_indexed[$cat->id])) {
                         // Add current category to the select list as disabled if user can view all categories, OTHERWISE DO NOT ADD IT
                         if ($viewallcats) {
                             $catlist[] = JHTML::_('select.option', $cat->id, $cat_title, 'value', 'text', $disabled = true);
                         }
                     } else {
                         // CASE: DISABLED categories e.g. existing children subtree when selecting category's parent
                         if (isset($disable_cats_arr[$cat->id])) {
                             $catlist[] = JHTML::_('select.option', $cat->id, $cat_title, 'value', 'text', $disabled = true);
                         } else {
                             $catlist[] = JHTML::_('select.option', $cat->id, $cat_title);
                             $cats_count++;
                         }
                     }
                 } else {
                     $catlist[] = JHTML::_('select.option', $cat->id, $cat_title);
                     $cats_count++;
                 }
             }
         }
     }
     // ************************************
     // Finally create the HTML form element
     // ************************************
     $replace_char = FLEXI_J16GE ? '_' : '';
     $idtag = preg_replace('/(\\]|\\[)+/', $replace_char, $name);
     $idtag = preg_replace('/_$/', '', $idtag);
     $html = $empty_errmsg && $cats_count == 0 ? '<div class="alert alert-error">' . $empty_errmsg . '</div>' : JHTML::_('select.genericlist', $catlist, $name, $attribs, 'value', 'text', $selected, $idtag);
     if ($top == 3) {
         // Restore first category element
         $first_item = reset($list);
         $first_item->treename = $_first_item_treename;
         $first_item->title = $_first_item_title;
         $first_item->id = $_first_item_id;
     }
     if ($print_logging_info) {
         @($fc_run_times['render_categories_select'] += round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
     }
     return $html;
 }
Example #4
0
 /**
  * Method to check if you can add a new record.
  *
  * Extended classes can override this if necessary.
  *
  * @param	array	An array of input data.
  *
  * @return	boolean
  * @since	1.6
  */
 protected function allowAdd($data = array())
 {
     $user = JFactory::getUser();
     if (!FLEXI_J16GE || $user->authorise('core.create', $this->extension)) {
         $cancreate_cat = true;
     } else {
         $usercats = FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.create'), $require_all = true, $check_published = true, $specific_catids = false, $find_first = true);
         $cancreate_cat = count($usercats) > 0;
     }
     return $cancreate_cat;
 }
 static function getUserPerms($user_id = null)
 {
     // handle jcomments integration
     if (JPluginHelper::isEnabled('system', 'jcomments')) {
         $JComments_Installed = 1;
         $destpath = JPATH_SITE . DS . 'components' . DS . 'com_jcomments' . DS . 'plugins';
         $dest = $destpath . DS . 'com_flexicontent.plugin.php';
         $source = JPATH_SITE . DS . 'components' . DS . 'com_flexicontent' . DS . 'librairies' . DS . 'jcomments' . DS . 'com_flexicontent.plugin.php';
         jimport('joomla.filesystem.file');
         if (!JFile::exists($dest)) {
             if (!JFolder::exists($destpath)) {
                 if (!JFolder::create($destpath)) {
                     JError::raiseWarning(100, JText::_('FLEXIcontent: Unable to create jComments plugin folder'));
                 }
             }
             if (!JFile::copy($source, $dest)) {
                 JError::raiseWarning(100, JText::_('FLEXIcontent: Unable to copy jComments plugin'));
             } else {
                 $mainframe->enqueueMessage(JText::_('Copied FLEXIcontent jComments plugin'));
             }
         }
     } else {
         $JComments_Installed = 0;
     }
     // Find permissions for given user id
     $user = $user_id ? JFactory::getUser($user_id) : JFactory::getUser();
     // no user id given, use current user)
     $permission = new stdClass();
     // !!! This is the Super User Privelege of GLOBAL Configuration		(==> (for J2.5) core.admin ACTION allowed on ROOT ASSET: 'root.1')
     $permission->SuperAdmin = JAccess::check($user->id, 'core.admin', 'root.1');
     //!!! ALLOWs USERS to change component's CONFIGURATION						(==> (for J2.5) core.admin ACTION allowed on COMPONENT ASSET: e.g. 'com_flexicontent')
     $permission->CanConfig = $user->authorise('core.admin', 'com_flexicontent');
     //!!! ALLOWs USERS in JOOMLA BACKEND : (not used in J1.5)
     //   (a) to view the FLEXIcontent menu item in Components Menu and
     //   (b) to access the FLEXIcontent component screens (whatever they are allowed to see by individual FLEXIcontent area permissions)
     //       NOTE: the initially installed permissions allows all areas to be managed for J2.5 and none (except for items) for J1.5
     $permission->CanManage = $user->authorise('core.manage', 'com_flexicontent');
     // ITEMS/CATEGORIES: category-inherited permissions, (NOTE: these are the global settings, so:)
     // *** 1. the action permissions of individual items are checked seperately per item
     // *** 2. the view permission is checked via the access level of each item
     // --- *. We will check for SOFT DENY, and then try to find the FIRST ALLOWED CATEGORY FOR EACH ACTION
     $permission->CanAdd = $user->authorise('core.create', 'com_flexicontent');
     if ($permission->CanAdd === NULL) {
         $allowedcats = FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.create'), $require_all = true, $check_published = true, false, $find_first = true);
         $permission->CanAdd = count($allowedcats) > 0;
     }
     $permission->CanEdit = $user->authorise('core.edit', 'com_flexicontent');
     if ($permission->CanEdit === NULL) {
         $allowedcats = FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.edit'), $require_all = true, $check_published = true, false, $find_first = true);
         $permission->CanEdit = count($allowedcats) > 0;
     }
     $permission->CanEditOwn = $user->authorise('core.edit.own', 'com_flexicontent');
     if ($permission->CanEditOwn === NULL) {
         $allowedcats = FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.edit.own'), $require_all = true, $check_published = true, false, $find_first = true);
         $permission->CanEditOwn = count($allowedcats) > 0;
     }
     $permission->CanPublish = $user->authorise('core.edit.state', 'com_flexicontent');
     if ($permission->CanPublish === NULL) {
         $allowedcats = FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.edit.state'), $require_all = true, $check_published = true, false, $find_first = true);
         $permission->CanPublish = count($allowedcats) > 0;
     }
     $permission->CanPublishOwn = $user->authorise('core.edit.state.own', 'com_flexicontent');
     if ($permission->CanPublishOwn === NULL) {
         $allowedcats = FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.edit.state.own'), $require_all = true, $check_published = true, false, $find_first = true);
         $permission->CanPublishOwn = count($allowedcats) > 0;
     }
     $permission->CanDelete = $user->authorise('core.delete', 'com_flexicontent');
     if ($permission->CanDelete === NULL) {
         $allowedcats = FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.delete'), $require_all = true, $check_published = true, false, $find_first = true);
         $permission->CanDelete = count($allowedcats) > 0;
     }
     $permission->CanDeleteOwn = $user->authorise('core.delete.own', 'com_flexicontent');
     if ($permission->CanDeleteOwn === NULL) {
         $allowedcats = FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.delete.own'), $require_all = true, $check_published = true, false, $find_first = true);
         $permission->CanDeleteOwn = count($allowedcats) > 0;
     }
     $permission->CanChangeCat = $user->authorise('flexicontent.change.cat', 'com_flexicontent');
     $permission->CanChangeSecCat = $user->authorise('flexicontent.change.cat.sec', 'com_flexicontent');
     $permission->CanChangeFeatCat = $user->authorise('flexicontent.change.cat.feat', 'com_flexicontent');
     // Permission for changing the ACL rules of items and categories that user can edit
     // Currently given to user that can edit component configuration
     $permission->CanRights = $permission->CanConfig;
     // Permission for changing the access level of items and categories that user can edit
     // (a) In J1.5 with FLEXIaccess, this is given to those that can edit the FLEXIaccess configuration
     // (b) In J1.5 without FLEXIaccess, this is given to users being at least an Editor
     // (c) In J2.5, this is the FLEXIcontent component ACTION 'accesslevel'
     $permission->CanAccLvl = $user->authorise('flexicontent.accesslevel', 'com_flexicontent');
     // ITEMS: component controlled permissions
     $permission->DisplayAllItems = $user->authorise('flexicontent.displayallitems', 'com_flexicontent');
     // (backend) List all items (otherwise only items that can be edited)
     $permission->CanCopy = $user->authorise('flexicontent.copyitems', 'com_flexicontent');
     // (backend) Item Copy Task
     $permission->CanOrder = $user->authorise('flexicontent.orderitems', 'com_flexicontent');
     // (backend) Reorder items inside the category
     $permission->CanParams = $user->authorise('flexicontent.paramsitem', 'com_flexicontent');
     // (backend) Edit item parameters like meta data and template parameters
     $permission->CanVersion = $user->authorise('flexicontent.versioning', 'com_flexicontent');
     // (backend) Use item versioning
     $permission->AssocAnyTrans = $user->authorise('flexicontent.assocanytrans', 'com_flexicontent');
     // (item edit form) associate any translation
     $permission->EditCreationDate = $user->authorise('flexicontent.editcreationdate', 'com_flexicontent');
     // (item edit form) edit creation date (frontend)
     $permission->IgnoreViewState = $user->authorise('flexicontent.ignoreviewstate', 'com_flexicontent');
     // (Frontend Content Lists) ignore view state
     $permission->RequestApproval = $user->authorise('flexicontent.requestapproval', 'com_flexicontent');
     // (Workflow) Send Approval Requests (for ANY draft items)
     $permission->AutoApproveChanges = $user->authorise('flexicontent.autoapprovechanges', 'com_flexicontent');
     // (Workflow) Can publish document changes regardless of edit state
     // CATEGORIES: management tab and usage
     $permission->CanCats = $user->authorise('flexicontent.managecats', 'com_flexicontent');
     // (item edit form) view the categories which user cannot assign to items
     $permission->ViewAllCats = $user->authorise('flexicontent.usercats', 'com_flexicontent');
     // (item edit form) view the categories which user cannot assign to items
     $permission->ViewTree = $user->authorise('flexicontent.viewtree', 'com_flexicontent');
     // (item edit form) view categories as tree instead of flat list
     $permission->MultiCat = $user->authorise('flexicontent.multicat', 'com_flexicontent');
     // (item edit form) allow user to assign items to multiple categories
     $permission->CanAddCats = $permission->CanAdd && $permission->CanCats;
     // TAGS: management tab and usage
     $permission->CanTags = $user->authorise('flexicontent.managetags', 'com_flexicontent');
     // (backend) Allow management of Item Types
     $permission->CanUseTags = $user->authorise('flexicontent.usetags', 'com_flexicontent');
     // edit already assigned Tags of items
     $permission->CanNewTags = $user->authorise('flexicontent.newtags', 'com_flexicontent');
     // add new Tags to items
     // VARIOUS management TABS: types, archives, statistics, templates, tags
     $permission->CanTypes = $user->authorise('flexicontent.managetypes', 'com_flexicontent');
     // (backend) Allow management of Item Types
     $permission->CanArchives = $user->authorise('flexicontent.managearchives', 'com_flexicontent');
     // (backend) Allow management of Archives
     $permission->CanTemplates = $user->authorise('flexicontent.managetemplates', 'com_flexicontent');
     // (backend) Allow management of Templates
     $permission->CanStats = $user->authorise('flexicontent.managestats', 'com_flexicontent');
     // (backend) Allow management of Statistics
     $permission->CanImport = $user->authorise('flexicontent.manageimport', 'com_flexicontent');
     // (backend) Allow management of (Content) Import
     // FIELDS: management tab
     $permission->CanFields = $user->authorise('flexicontent.managefields', 'com_flexicontent');
     // (backend) Allow management of Fields
     $permission->CanCopyFields = $user->authorise('flexicontent.copyfields', 'com_flexicontent');
     // (backend) Field Copy Task
     $permission->CanOrderFields = $user->authorise('flexicontent.orderfields', 'com_flexicontent');
     // (backend) Reorder fields inside each item type
     $permission->CanAddField = $user->authorise('flexicontent.createfield', 'com_flexicontent');
     // (backend) Create fields
     $permission->CanEditField = $user->authorise('flexicontent.editfield', 'com_flexicontent');
     // (backend) Edit fields
     $permission->CanDeleteField = $user->authorise('flexicontent.deletefield', 'com_flexicontent');
     // (backend) Delete fields
     $permission->CanPublishField = $user->authorise('flexicontent.publishfield', 'com_flexicontent');
     // (backend) Publish fields
     // FILES: management tab
     $permission->CanFiles = $user->authorise('flexicontent.managefiles', 'com_flexicontent');
     // (backend) Allow management of Files
     $permission->CanUpload = $user->authorise('flexicontent.uploadfiles', 'com_flexicontent');
     // allow user to upload Files
     $permission->CanViewAllFiles = $user->authorise('flexicontent.viewallfiles', 'com_flexicontent');
     // allow user to view all Files
     // AUTHORS: management tab
     $permission->CanAuthors = $user->authorise('core.manage', 'com_users');
     $permission->CanGroups = FLEXI_J16GE ? $permission->CanAuthors : 0;
     // SEARCH INDEX: management tab
     $permission->CanIndex = $permission->CanFields && ($permission->CanAddField || $permission->CanEditField);
     // OTHER components permissions
     $permission->CanPlugins = $user->authorise('core.manage', 'com_plugins');
     $permission->CanComments = $user->authorise('core.manage', 'com_jcomments');
     $permission->CanComments = $permission->CanComments && $JComments_Installed;
     $permission->JComments_Installed = $JComments_Installed;
     // Global parameter to force always displaying of categories as tree
     if (JComponentHelper::getParams('com_flexicontent')->get('cats_always_astree', 1)) {
         $permission->ViewTree = 1;
     }
     return $permission;
 }
Example #6
0
 /**
  * Method to build the where clause of the query for the Items
  *
  * @access private
  * @return string
  * @since 1.0
  */
 function _buildContentWhere(&$extra_joins = "")
 {
     $session = JFactory::getSession();
     $user = JFactory::getUser();
     $perms = FlexicontentHelperPerm::getPerm();
     // ***********************************
     // FLAGs to decide which items to list
     // ***********************************
     $allitems = $perms->DisplayAllItems;
     $viewable_items = $this->cparams->get('iman_viewable_items', 1);
     $editable_items = $this->cparams->get('iman_editable_items', 0);
     // ************************************************************************
     // SPECIAL item listing CASES, item ids are already calculated and provided,
     // in such a case WHERE clause limits to the given item ids
     // ************************************************************************
     // CASE 1: listing items using a file
     $filter_fileid = $this->getState('filter_fileid');
     if ($filter_fileid) {
         $fileid_to_itemids = $session->get('fileid_to_itemids', array(), 'flexicontent');
         $itemids = $fileid_to_itemids[$filter_fileid];
         if (empty($itemids)) {
             return ' WHERE 0 ';
         } else {
             return ' WHERE i.id IN (' . implode(',', $itemids) . ') ';
         }
     }
     // *********************
     // Get item list filters
     // *********************
     // various filters (mostly multi-value)
     $filter_tag = $this->getState('filter_tag');
     $filter_lang = $this->getState('filter_lang');
     $filter_type = $this->getState('filter_type');
     $filter_author = $this->getState('filter_author');
     $filter_state = $this->getState('filter_state');
     $filter_access = $this->getState('filter_access');
     // category related filters
     $filter_cats = $this->getState('filter_cats');
     $filter_subcats = $this->getState('filter_subcats');
     $filter_catsinstate = $this->getState('filter_catsinstate');
     // filter id
     $filter_id = $this->getState('filter_id');
     // text search and search scope
     $scope = $this->getState('scope');
     $search = $this->getState('search');
     $search = trim(JString::strtolower($search));
     // date filters
     $date = $this->getState('date');
     $startdate = $this->getState('startdate');
     $enddate = $this->getState('enddate');
     $startdate = trim(JString::strtolower($startdate));
     $enddate = trim(JString::strtolower($enddate));
     // ********************************************
     // Start building the AND parts of where clause
     // ********************************************
     $where = array();
     // Limit items to the children of the FLEXI_CATEGORY, currently FLEXI_CATEGORY is root category (id:1) ...
     //$where[] = ' (cat.lft > ' . $this->_db->Quote(FLEXI_LFT_CATEGORY) . ' AND cat.rgt < ' . $this->_db->Quote(FLEXI_RGT_CATEGORY) . ')';
     //$where[] = ' cat.extension = ' . $this->_db->Quote(FLEXI_CAT_EXTENSION);
     // *************************************
     // IF items viewable: default is enabled
     // *************************************
     $joinaccess = "";
     if (!$allitems && $viewable_items) {
         $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
         $aid_list = implode(",", $aid_arr);
         $where[] = ' t.access IN (0,' . $aid_list . ')';
         $where[] = ' c.access IN (0,' . $aid_list . ')';
         $where[] = ' i.access IN (0,' . $aid_list . ')';
     }
     $extra_joins .= $joinaccess;
     // ************************************************************
     // IF items in an editable (main) category: default is disabled
     // ************************************************************
     $allowedcats = false;
     $allowedcats_own = false;
     if (!$allitems && $editable_items) {
         $allowedcats = FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.edit'), $require_all = true, $check_published = false, false, $find_first = false);
         $allowedcats_own = FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.edit.own'), $require_all = true, $check_published = false, false, $find_first = false);
         if ($allowedcats || $allowedcats_own) {
             $_edit_where = '( ';
             if ($allowedcats) {
                 $_edit_where .= '( i.catid IN (' . implode(', ', $allowedcats) . ') )';
             }
             if ($allowedcats && $allowedcats_own) {
                 $_edit_where .= ' OR ';
             }
             if ($allowedcats_own) {
                 $_edit_where .= '( i.catid IN (' . implode(', ', $allowedcats_own) . ') AND i.created_by=' . $user->id . ')';
             }
             $where[] = $_edit_where . ' )';
         }
     }
     // *******************************
     // Limit using the category filter
     // *******************************
     if ($filter_cats) {
         // CURRENTLY in main or secondary category.  -TODO-  maybe add limiting by main category, if ... needed
         $cat_type = 'rel.catid';
         // $filter_maincat ? 'i.catid' : 'rel.catid';
         if ($filter_subcats) {
             global $globalcats;
             $_sub_cids = array();
             if ($filter_catsinstate == 99) {
                 $_sub_cids = $globalcats[$filter_cats]->descendantsarray;
             } else {
                 foreach ($globalcats[$filter_cats]->descendantsarray as $_dcatid) {
                     if ($globalcats[$_dcatid]->published == $filter_catsinstate) {
                         $_sub_cids[] = $_dcatid;
                     }
                 }
             }
             if (empty($_sub_cids)) {
                 $where[] = ' FALSE  ';
             } else {
                 $where[] = '(' . $cat_type . ' IN (' . implode(', ', $_sub_cids) . ')' . ' OR ' . 'c.id IN (' . implode(', ', $_sub_cids) . '))';
             }
         } else {
             $where[] = $cat_type . ' = ' . $filter_cats;
         }
     } else {
         if ($filter_catsinstate != 99) {
             // if not showing items in any category state
             $where[] = '(rel.catid IN ( SELECT id FROM #__categories WHERE published=' . $filter_catsinstate . ' )' . ' OR ' . 'c.published = ' . $filter_catsinstate . ')';
         }
     }
     // ************************************************************
     // Limit using state or group of states (e.g. published states)
     // ************************************************************
     if (empty($filter_state)) {
         $where[] = 'i.state <> -2';
         $where[] = 'i.state <> 2';
     } else {
         $filter_state = empty($filter_state) ? array() : (!is_array($filter_state) ? array($filter_state) : $filter_state);
         $FS = array_flip($filter_state);
         $states = array();
         if (isset($FS['ALL'])) {
         } else {
             if (isset($FS['ORPHAN'])) {
                 $where[] = 'i.state NOT IN(2,-2,1,0,-3,-4,-5)';
             } else {
                 if (isset($FS['ALL_P'])) {
                     array_push($states, 1, -5);
                 }
                 if (isset($FS['ALL_U'])) {
                     array_push($states, 0, -3, -4);
                 }
                 if (isset($FS['P'])) {
                     array_push($states, 1);
                 }
                 if (isset($FS['U'])) {
                     array_push($states, 0);
                 }
                 if (isset($FS['PE'])) {
                     array_push($states, -3);
                 }
                 if (isset($FS['OQ'])) {
                     array_push($states, -4);
                 }
                 if (isset($FS['IP'])) {
                     array_push($states, -5);
                 }
                 if (isset($FS['RV'])) {
                     array_push($states, 1, -5);
                 }
                 if (isset($FS['A'])) {
                     array_push($states, 2);
                 }
                 if (isset($FS['T'])) {
                     array_push($states, -2);
                 }
                 $states = array_unique($states, SORT_REGULAR);
                 if (!empty($states)) {
                     $where[] = 'i.state IN (' . implode(',', $states) . ')';
                 }
             }
         }
     }
     // *******************************************************************************
     // Limit using simpler filtering, (item) type, author, (item) id, language, access
     // *******************************************************************************
     if (!empty($filter_tag)) {
         JArrayHelper::toInteger($filter_tag, null);
         $where[] = 'tg.tid IN (' . implode(',', $filter_tag) . ')';
     }
     if (!empty($filter_type)) {
         JArrayHelper::toInteger($filter_type, null);
         $where[] = 'i.type_id IN (' . implode(',', $filter_type) . ')';
     }
     if (!empty($filter_author)) {
         JArrayHelper::toInteger($filter_author, null);
         $where[] = 'i.created_by IN (' . implode(',', $filter_author) . ')';
     }
     if ($filter_id) {
         $where[] = 'i.id = ' . $filter_id;
     }
     if (!empty($filter_lang)) {
         if (!is_array($filter_lang)) {
             $filter_langs[] = $this->_db->Quote($filter_lang);
         } else {
             foreach ($filter_lang as $val) {
                 $filter_langs[] = $this->_db->Quote($val);
             }
         }
         $where[] = 'i.language IN (' . implode(',', $filter_langs) . ')';
     }
     if (!empty($filter_access)) {
         JArrayHelper::toInteger($filter_access, null);
         $where[] = 'i.access IN (' . implode(',', $filter_access) . ')';
     }
     // **************
     // CUSTON filters
     // **************
     $customFilts = $this->getCustomFilts();
     $_filts_vals_clause = array();
     foreach ($customFilts as $filter) {
         if (!count($filter->value)) {
             continue;
         }
         $_filts_vals_clause[] = ' (fi.field_id=' . $filter->id . ' AND fi.value=' . $this->_db->Quote($filter->value[0]) . ')';
     }
     if (count($_filts_vals_clause)) {
         $where[] = ' (' . implode(' OR ', $_filts_vals_clause) . ' )';
     }
     // *********************
     // TEXT search filtering
     // *********************
     $search_prefix = JComponentHelper::getParams('com_flexicontent')->get('add_search_prefix') ? 'vvv' : '';
     // SEARCH WORD Prefix
     if ($search) {
         $escaped_search = $this->_db->escape($search, true);
     }
     if ($search && $scope == 1) {
         $where[] = ' LOWER(i.title) LIKE ' . $this->_db->Quote('%' . $escaped_search . '%', false);
     }
     if ($search && $scope == 2) {
         $where[] = ' LOWER(i.introtext) LIKE ' . $this->_db->Quote('%' . $escaped_search . '%', false);
     }
     if ($search && $scope == 4) {
         $where[] = ' MATCH (ie.search_index) AGAINST (' . $this->_db->Quote($search_prefix . $escaped_search . '*', false) . ' IN BOOLEAN MODE)';
     }
     // ***************************************************
     // Date range filtering (creation and/or modification)
     // ***************************************************
     $nullDate = $this->_db->getNullDate();
     if ($date == 1) {
         if ($startdate && !$enddate) {
             // from only
             $where[] = ' i.created >= ' . $this->_db->Quote($startdate);
         }
         if (!$startdate && $enddate) {
             // to only
             $where[] = ' i.created <= ' . $this->_db->Quote($enddate);
         }
         if ($startdate && $enddate) {
             // date range
             $where[] = '( i.created >= ' . $this->_db->Quote($startdate) . ' AND i.created <= ' . $this->_db->Quote($enddate) . ' )';
         }
     }
     if ($date == 2) {
         if ($startdate && !$enddate) {
             // from only
             $where[] = '( i.modified >= ' . $this->_db->Quote($startdate) . ' OR ( i.modified = ' . $this->_db->Quote($nullDate) . ' AND i.created >= ' . $this->_db->Quote($startdate) . '))';
         }
         if (!$startdate && $enddate) {
             // to only
             $where[] = '( i.modified <= ' . $this->_db->Quote($enddate) . ' OR ( i.modified = ' . $this->_db->Quote($nullDate) . ' AND i.created <= ' . $this->_db->Quote($enddate) . '))';
         }
         if ($startdate && $enddate) {
             // date range
             $where[] = '(( i.modified >= ' . $this->_db->Quote($startdate) . ' OR ( i.modified = ' . $this->_db->Quote($nullDate) . ' AND i.created >= ' . $this->_db->Quote($startdate) . ')) AND ( i.modified <= ' . $this->_db->Quote($enddate) . ' OR ( i.modified = ' . $this->_db->Quote($nullDate) . ' AND i.created <= ' . $this->_db->Quote($enddate) . ')))';
         }
     }
     // *************************************************
     // Finally create the AND clause of the WHERE clause
     // *************************************************
     $where = count($where) ? ' WHERE ' . implode(' AND ', $where) : '';
     return $where;
 }
 /**
  * Creates the add button
  *
  * @param array $params
  * @since 1.0
  */
 static function addbutton(&$params, &$submit_cat = null, $menu_itemid = 0, $submit_text = '', $auto_relations = false, $ignore_unauthorized = false)
 {
     if (!$params->get('show_addbutton', 1) || JRequest::getCmd('print')) {
         return;
     }
     // Currently add button will appear to logged users only
     // ... unless unauthorized users are allowed
     $user = JFactory::getUser();
     if (!$user->id && $ignore_unauthorized < 2) {
         return '';
     }
     // IF not auto-relation given ... then check if current view / layout can use ADD button
     $view = JRequest::getVar('view');
     $layout = JRequest::getVar('layout', 'default');
     if (!$auto_relations) {
         if ($view != 'category' || $layout == 'author') {
             return '';
         }
     }
     // *********************************************************************
     // Check if user can ADD to (a) given category or to (b) at any category
     // *********************************************************************
     // (a) Given category
     if ($submit_cat && $submit_cat->id) {
         $canAdd = $user->authorise('core.create', 'com_content.category.' . $submit_cat->id);
     } else {
         // Given CATEGORY VIEW OBJECT may limit to specific category ids
         $canAdd = $user->authorise('core.create', 'com_flexicontent');
         if ($canAdd === NULL && $user->id) {
             // Perfomance concern (NULL for $canAdd) means SOFT DENY, also check for logged user
             // thus to avoid checking some/ALL categories for "create" privelege for unlogged users
             $specific_catids = $submit_cat ? @$submit_cat->ids : false;
             if ($specific_catids && count($specific_catids) > 3) {
                 $specific_catids = false;
             }
             $allowedcats = FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.create'), $require_all = true, $check_published = true, $specific_catids, $find_first = true);
             $canAdd = count($allowedcats);
         }
     }
     if (!$canAdd && !$ignore_unauthorized) {
         return '';
     }
     // ******************************
     // Create submit button/icon text
     // ******************************
     if ($submit_text) {
         $submit_lbl = JText::_($submit_text);
     } else {
         $submit_lbl = JText::_($submit_cat && $submit_cat->id ? 'FLEXI_ADD_NEW_CONTENT_TO_CURR_CAT' : 'FLEXI_ADD_NEW_CONTENT_TO_LIST');
     }
     // ***********
     // Create link
     // ***********
     // Add Itemid (if given) and do SEF URL routing it --before-- appending more variables, so that
     // ... menu item URL variables from given menu item ID will be appended if SEF URLs are OFF
     $menu_itemid = $menu_itemid ? $menu_itemid : (int) $params->get('addbutton_menu_itemid', 0);
     $link = 'index.php?option=com_flexicontent';
     $link .= $menu_itemid ? '&Itemid=' . $menu_itemid : '&view=' . FLEXI_ITEMVIEW . '&task=add';
     $link = JRoute::_($link);
     // Add main category ID (if given)
     if ($submit_cat && $submit_cat->id) {
         $link .= (strstr($link, '?') ? '&' : '?') . 'maincat=' . $submit_cat->id;
     }
     // Append autorelate information to the URL (if given)
     if ($auto_relations) {
         foreach ($auto_relations as $auto_relation) {
             $link .= (strstr($link, '?') ? '&' : '?') . 'autorelation_' . $auto_relation->fieldid . '=' . $auto_relation->itemid;
         }
     }
     // ***************************************
     // Finally create the submit icon / button
     // ***************************************
     $overlib = $submit_lbl;
     $text = JText::_('FLEXI_ADD');
     $show_icons = 2;
     //$params->get('show_icons');
     if ($show_icons && !$auto_relations) {
         $attribs = '';
         $image = JHTML::image('components/com_flexicontent/assets/images/' . 'plus-button.png', $submit_lbl, $attribs);
     } else {
         $image = '';
     }
     $button_classes = 'fc_addbutton';
     if ($show_icons == 1 && !$auto_relations) {
         $caption = '';
         $button_classes .= '';
     } else {
         $caption = $text;
         $button_classes .= (FLEXI_J30GE ? ' btn btn-small' : ' fc_button fcsimple fcsmall') . ($auto_relations ? ' btn-success' : '');
     }
     $button_classes .= FLEXI_J30GE ? ' hasTooltip' : ' hasTip';
     $tooltip_title = flexicontent_html::getToolTip($text, $overlib, 0);
     $output = '<a href="' . $link . '" class="' . $button_classes . '" title="' . $tooltip_title . '">' . $image . $caption . '</a>';
     if (!$auto_relations) {
         $output = JText::_('FLEXI_ICON_SEP') . $output . JText::_('FLEXI_ICON_SEP');
     }
     return $output;
 }
Example #8
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);
    }
 /**
  * Method to store the item
  *
  * @access	public
  * @return	boolean	True on success
  * @since	1.0
  */
 function store($data)
 {
     // Check for request forgeries
     if (!JFactory::getApplication()->isAdmin()) {
         // For flexible usage, e.g. when it is called by the new IMPORT TASK
         //JRequest::checkToken() or jexit( 'Invalid Token' );
     }
     // ****************************
     // Initialize various variables
     // ****************************
     $db = $this->_db;
     $app = JFactory::getApplication();
     $user = JFactory::getUser();
     $dispatcher = JDispatcher::getInstance();
     $cparams = $this->_cparams;
     $nullDate = $this->_db->getNullDate();
     $view = JRequest::getVar('view', false);
     JRequest::setVar("isflexicontent", "yes");
     $use_versioning = $cparams->get('use_versioning', 1);
     $print_logging_info = $cparams->get('print_logging_info');
     if ($print_logging_info) {
         global $fc_run_times;
         $start_microtime = microtime(true);
     }
     // Dates displayed in the item form, are in user timezone for J2.5, and in site's default timezone for J1.5
     $site_zone = $app->getCfg('offset');
     $user_zone = $user->getParam('timezone', $site_zone);
     $tz_offset = FLEXI_J16GE ? $user_zone : $site_zone;
     // Sanitize id and approval flag as integers
     $data['vstate'] = (int) $data['vstate'];
     $data['id'] = (int) $data['id'];
     $isnew = !$data['id'];
     // *****************************************
     // Get an item object and load existing item
     // *****************************************
     // Get an empty item model (with default values)
     $item = $this->getTable('flexicontent_items', '');
     // ... existing items
     if (!$isnew) {
         // Load existing item into the empty item model
         $item->load($data['id']);
         // Get item's assigned categories
         $query = 'SELECT DISTINCT catid FROM #__flexicontent_cats_item_relations WHERE itemid = ' . (int) $this->_id;
         $db->setQuery($query);
         $item->categories = FLEXI_J16GE ? $db->loadColumn() : $db->loadResultArray();
         // We need to fake joomla's states ... when triggering the before save content event
         $fc_state = $item->state;
         if (in_array($fc_state, array(1, -5))) {
             $jm_state = 1;
         } else {
             if (in_array($fc_state, array(0, -3, -4))) {
                 $jm_state = 0;
             } else {
                 $jm_state = $fc_state;
             }
         }
         // trashed & archive states
         // Frontend SECURITY concern: ONLY allow to set item type for new items !!! ... or for items without type ?!
         if (!$app->isAdmin() && $item->type_id) {
             unset($data['type_id']);
         }
     } else {
         $item->categories = array();
     }
     // *********************************
     // Check and correct given item DATA
     // *********************************
     // tags and cats will need some manipulation so we retieve them
     $tags = $this->formatToArray(@$data['tag']);
     $cats = $this->formatToArray(@$data['cid']);
     $featured_cats = $this->formatToArray(@$data['featured_cid']);
     unset($data['tag']);
     unset($data['cid']);
     unset($data['featured_cid']);
     // Make tags unique
     $tags = array_unique($tags);
     // Auto-assign a not set main category, to be the first out of secondary categories,
     if (empty($data['catid']) && !empty($cats[0])) {
         $data['catid'] = $cats[0];
     }
     $cats_indexed = array_flip($cats);
     // Add the primary cat to the array if it's not already in
     if (@$data['catid'] && !isset($cats_indexed[$data['catid']])) {
         $cats[] = $data['catid'];
     }
     // Add the primary cat to the array if it's not already in
     if (!empty($featured_cats)) {
         foreach ($featured_cats as $featured_cat) {
             if (@$featured_cat && !isset($cats_indexed[$featured_cat])) {
                 $cats[] = $featured_cat;
             }
         }
     }
     // *****************************
     // 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);
     }
     // At least one category needs to be assigned
     if (!is_array($cats) || count($cats) < 1) {
         $this->setError(JText::_('FLEXI_OPERATION_FAILED') . ", " . JText::_('FLEXI_REASON') . ": " . JText::_('FLEXI_SELECT_CATEGORY'));
         return false;
         // Check more than allowed categories
     } else {
         // Get author's maximum allowed categories per item and set js limitation
         $max_cat_assign = !$authorparams ? 0 : intval($authorparams->get('max_cat_assign', 0));
         // Verify category limitation for current author
         if ($max_cat_assign) {
             if (count($cats) > $max_cat_assign) {
                 if (count($cats) <= count($item->categories)) {
                     $existing_only = true;
                     // Maximum number of categories is exceeded, but do not abort if only using existing categories
                     foreach ($cats as $newcat) {
                         $existing_only = $existing_only && in_array($newcat, $item->categories);
                     }
                 } else {
                     $existing_only = false;
                 }
                 if (!$existing_only) {
                     $this->setError(JText::_('FLEXI_OPERATION_FAILED') . ", " . JText::_('FLEXI_REASON') . ": " . JText::_('FLEXI_TOO_MANY_ITEM_CATEGORIES') . $max_cat_assign);
                     return false;
                 }
             }
         }
     }
     // Set back the altered categories and tags to the form data
     $data['categories'] = $cats;
     // Set it to real name of field: 'categories' INSTEAD OF 'cid'
     $data['tags'] = $tags;
     // Set it to real name of field: 'tags'       INSTEAD OF 'tag'
     // Reconstruct (main)text field if it has splitted up e.g. to seperate editors per tab
     if (@$data['text'] && is_array($data['text'])) {
         $data['text'][0] .= preg_match('#<hr\\s+id=("|\')system-readmore("|\')\\s*\\/*>#i', $data['text'][0]) == 0 ? "\n" . '<hr id="system-readmore" />' : "";
         $tabs_text = '';
         foreach ($data['text'] as $tab_text) {
             $tabs_text .= $tab_text;
         }
         $data['text'] =& $tabs_text;
     }
     // The text field is stored in the db as to seperate fields: introtext & fulltext
     // So we search for the {readmore} tag and split up the text field accordingly.
     $pattern = '#<hr\\s+id=("|\')system-readmore("|\')\\s*\\/*>#i';
     $tagPos = preg_match($pattern, @$data['text']);
     if ($tagPos == 0) {
         $data['introtext'] = @$data['text'];
         $data['fulltext'] = '';
     } else {
         list($data['introtext'], $data['fulltext']) = preg_split($pattern, $data['text'], 2);
         $data['fulltext'] = JString::strlen(trim($data['fulltext'])) ? $data['fulltext'] : '';
     }
     // ***************************************************************************************
     // Handle Parameters: attribs & metadata, merging POST values into existing values,
     // IF these were not set at all then there will be no need to merge,
     // BUT part of them may have been displayed, so we use mergeAttributes() instead of bind()
     // Keys that are not set will not be set, thus the previous value is maintained
     // ***************************************************************************************
     // Retrieve (a) item parameters (array PARAMS or ATTRIBS ) and (b) item metadata (array METADATA or META )
     if (!FLEXI_J16GE) {
         $params = $this->formatToArray(@$data['params']);
         $metadata = $this->formatToArray(@$data['meta']);
         unset($data['params']);
         unset($data['meta']);
     } else {
         $params = $this->formatToArray(@$data['attribs']);
         $metadata = $this->formatToArray(@$data['metadata']);
         unset($data['attribs']);
         unset($data['metadata']);
     }
     // Merge (form posted) item attributes and metadata parameters INTO EXISTING DATA (see above for explanation)
     $this->mergeAttributes($item, $params, $metadata);
     // *******************************************************
     // Retrieve submit configuration for new items in frontend
     // *******************************************************
     if ($app->isSite() && $isnew && !empty($data['submit_conf'])) {
         $h = $data['submit_conf'];
         $session = JFactory::getSession();
         $item_submit_conf = $session->get('item_submit_conf', array(), 'flexicontent');
         $submit_conf = @$item_submit_conf[$h];
         $autopublished = @$submit_conf['autopublished'];
         $overridecatperms = @$submit_conf['overridecatperms'];
         if ($autopublished) {
             // Dates forced during autopublishing
             if (@$submit_conf['autopublished_up_interval']) {
                 if (FLEXI_J16GE) {
                     $publish_up_date = JFactory::getDate();
                     // Gives editor's timezone by default
                     $publish_up_date->modify('+ ' . $submit_conf['autopublished_up_interval'] . ' minutes');
                     $publish_up_forced = $publish_up_date->toSql();
                 } else {
                     $publish_up_date = new DateTime(JHTML::_('date', JFactory::getDate()->toFormat(), '%Y-%m-%d %H:%M:%S'));
                     $publish_up_date->modify('+ ' . $submit_conf['autopublished_up_interval'] . ' minutes');
                     $publish_up_forced = $publish_up_date->format('Y-m-d H:i:s');
                 }
             }
             if (@$submit_conf['autopublished_down_interval']) {
                 if (FLEXI_J16GE) {
                     $publish_down_date = JFactory::getDate();
                     // Gives editor's timezone by default
                     $publish_down_date->modify('+ ' . $submit_conf['autopublished_down_interval'] . ' minutes');
                     $publish_down_forced = $publish_down_date->toSql();
                 } else {
                     $publish_down_date = new DateTime(JHTML::_('date', JFactory::getDate()->toFormat(), '%Y-%m-%d %H:%M:%S'));
                     $publish_down_date->modify('+ ' . $submit_conf['autopublished_down_interval'] . ' minutes');
                     $publish_down_forced = $publish_down_date->format('Y-m-d H:i:s');
                 }
             }
         }
     } else {
         $autopublished = 0;
         $overridecatperms = 0;
     }
     // ***********************************************************
     // SECURITY concern: Check form tampering of categories, of:
     // (a) menu overridden categories for frontent item submit
     // (b) or check user has 'create' privilege in item categories
     // ***********************************************************
     if ($overridecatperms) {
         $allowed_cid = @$submit_conf['cids'];
     } else {
         if (FLEXI_J16GE || FLEXI_ACCESS) {
             $allowed_cid = FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.create'), $require_all = true);
         }
     }
     if (isset($allowed_cid)) {
         // Add existing item's categories into the user allowed categories
         $allowed_cid = array_merge($allowed_cid, $item->categories);
         // Check main category tampering
         if (!in_array($data['catid'], $allowed_cid) && $data['catid'] != $item->catid) {
             $this->setError('main category is not in allowed list (form tampered ?)');
             return false;
         }
         // Check multi category tampering
         $postcats = @$submit_conf['postcats'];
         if (!$isnew || !$overridecatperms || $postcats == 2) {
             $data['categories'] = array_intersect($data['categories'], $allowed_cid);
         } else {
             if ($postcats == 0) {
                 $data['categories'] = $allowed_cid;
             } else {
                 if ($postcats == 1) {
                     $data['categories'] = array($data['catid']);
                 }
             }
         }
     }
     // *****************************************************************
     // SECURITY concern: Check form tampering of state related variables
     // *****************************************************************
     // Save old main category & creator (owner)
     $old_created_by = $item->created_by;
     $old_catid = $item->catid;
     // New or Existing item must use the current user + new main category to calculate 'Edit State' privelege
     $item->created_by = $user->get('id');
     $item->catid = $data['catid'];
     $canEditState = $this->canEditState($item, $check_cat_perm = true);
     // Restore old main category & creator (owner) (in case following code chooses to keep them)
     $item->created_by = $old_created_by;
     $item->catid = $old_catid;
     // If cannot edit state prevent user from changing state related parameters
     if (!$canEditState) {
         $data['vstate'] = 1;
         if (!FLEXI_J16GE) {
             // Behaviour is different in J1.5, it requires edit instead of edit state
             //unset( $data['details']['publish_up'] );
             //unset( $data['details']['publish_down'] );
             //unset( $data['ordering'] );
         } else {
             unset($data['featured']);
             unset($data['publish_up']);
             unset($data['publish_down']);
             unset($data['ordering']);
         }
         // Check for publish up/down dates forced during auto-publishing
         if (@$publish_up_forced) {
             $data['publish_up'] = $publish_up_forced;
         }
         if (@$publish_down_forced) {
             $data['publish_down'] = $publish_down_forced;
         }
         $pubished_state = 1;
         $draft_state = -4;
         $pending_approval_state = -3;
         if (!$isnew) {
             // Prevent changing state of existing items by users that cannot publish
             $catid_changed = $old_catid != $data['catid'];
             if ($catid_changed && !$use_versioning) {
                 $data['state'] = $pending_approval_state;
                 $app->enqueueMessage('You have changed category for this content item to be a category in which you cannot publish, you content item is now in "Pending Approval" State, you will have to wait for it to be re-approved', 'warning');
             } else {
                 $data['state'] = $item->state;
             }
         } else {
             if ($autopublished) {
                 // Autopublishing new item via menu configuration
                 $data['state'] = $pubished_state;
             } else {
                 // The preselected forced state of -NEW- items for users that CANNOT publish, and autopublish via menu item is disabled
                 if ($app->isAdmin()) {
                     $data['state'] = $cparams->get('non_publishers_item_state', $draft_state);
                     // Use the configured setting for backend items
                 } else {
                     $data['state'] = $cparams->get('non_publishers_item_state_fe', $pending_approval_state);
                     // Use the configured setting for frontend items
                 }
             }
         }
     }
     $isSuperAdmin = FLEXI_J16GE ? $user->authorise('core.admin', 'root.1') : $user->gid >= 25;
     // Prevent frontend user from changing the item owner and creation date unless they are super admin
     if ($app->isSite() && !$isSuperAdmin) {
         if (!FLEXI_J16GE) {
             if ($isnew) {
                 $data['details']['created_by'] = $user->get('id');
             } else {
                 unset($data['details']['created_by']);
             }
             unset($data['details']['created']);
             unset($data['details']['created_by_alias']);
         } else {
             if ($isnew) {
                 $data['created_by'] = $user->get('id');
             } else {
                 unset($data['created_by']);
             }
             if (!$user->authorise('flexicontent.editcreationdate', 'com_flexicontent')) {
                 unset($data['created']);
             }
             unset($data['created_by_alias']);
         }
     }
     // ***********************************************************
     // SECURITY concern: Check form tampering of 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;
     }
     if ($allowed_langs && isset($data['language']) && !in_array($data['language'], $allowed_langs)) {
         $app->enqueueMessage('You are not allowed to assign language: ' . $data['language'] . ' to Content Items', 'warning');
         unset($data['language']);
         if ($isnew) {
             return false;
         }
     }
     if ($app->isSite() && $cparams->get('uselang_fe', 1) != 1 && isset($data['language'])) {
         $app->enqueueMessage('You are not allowed to set language to this content items', 'warning');
         unset($data['language']);
         if ($isnew) {
             return false;
         }
     }
     // ************************************************
     // Bind given item DATA and PARAMETERS to the model
     // ************************************************
     // Bind the given data to the items
     if (!$item->bind($data)) {
         $this->setError($this->_db->getErrorMsg());
         return false;
     }
     // Bind posted publication details (parameters) to the model for J1.5
     if (!FLEXI_J16GE) {
         $details = $this->formatToArray(@$data['details']);
         $item->bind($details);
     }
     // **************************************
     // Check and correct core item properties
     // **************************************
     // -- Modification Date and Modifier, (a) new item gets null modification date and (b) existing item get the current date
     if ($isnew) {
         $item->modified = $nullDate;
         $item->modified_by = 0;
     } else {
         $datenow = JFactory::getDate();
         $item->modified = FLEXI_J16GE ? $datenow->toSql() : $datenow->toMySQL();
         $item->modified_by = $user->get('id');
     }
     // -- Creator, if this is not already set, will be the current user or administrator if current user is not logged
     if (!$item->created_by) {
         $item->created_by = $user->get('id') ? $user->get('id') : JFactory::getUser('admin')->get('id');
     }
     // -- Creation Date
     if ($item->created && JString::strlen(trim($item->created)) <= 10) {
         $item->created .= ' 00:00:00';
     }
     if (FLEXI_J16GE) {
         $date = JFactory::getDate($item->created);
         $date->setTimeZone(new DateTimeZone($tz_offset));
         // J2.5: Date from form field is in user's timezone
     } else {
         $date = JFactory::getDate($item->created, $tz_offset);
         // J1.5: Date from form field is in site's default timezone
     }
     $item->created = FLEXI_J16GE ? $date->toSql() : $date->toMySQL();
     // -- Publish UP Date
     if ($item->publish_up && JString::strlen(trim($item->publish_up)) <= 10) {
         $item->publish_up .= ' 00:00:00';
     }
     if (FLEXI_J16GE) {
         $date = JFactory::getDate($item->publish_up);
         $date->setTimeZone(new DateTimeZone($tz_offset));
         // J2.5: Date from form field is in user's timezone
     } else {
         $date = JFactory::getDate($item->publish_up, $tz_offset);
         // J1.5: Date from form field is in site's default timezone
     }
     $item->publish_up = FLEXI_J16GE ? $date->toSql() : $date->toMySQL();
     // -- Publish Down Date
     if (trim($item->publish_down) == JText::_('FLEXI_NEVER') || trim($item->publish_down) == '') {
         $item->publish_down = $nullDate;
     } else {
         if ($item->publish_down != $nullDate) {
             if (JString::strlen(trim($item->publish_down)) <= 10) {
                 $item->publish_down .= ' 00:00:00';
             }
             if (FLEXI_J16GE) {
                 $date = JFactory::getDate($item->publish_down);
                 $date->setTimeZone(new DateTimeZone($tz_offset));
                 // J2.5: Date from form field is in user's timezone
             } else {
                 $date = JFactory::getDate($item->publish_down, $tz_offset);
                 // J1.5: Date from form field is in site's default timezone
             }
             $item->publish_down = FLEXI_J16GE ? $date->toSql() : $date->toMySQL();
         }
     }
     // auto assign the section
     if (!FLEXI_J16GE) {
         $item->sectionid = FLEXI_SECTION;
     }
     // For new items get next available ordering number
     if ($isnew) {
         $item->ordering = $item->getNextOrder();
     }
     // Auto assign the default language if not set, (security of allowing language usage and of language in user's allowed languages was checked above)
     $item->language = $item->language ? $item->language : ($app->isSite() ? $cparams->get('default_language_fe', '*') : (FLEXI_J16GE ? '*' : flexicontent_html::getSiteDefaultLang()));
     // Ignore language parent id if item language is site's (content) default language, and for language 'ALL'
     if (substr($item->language, 0, 2) == substr(flexicontent_html::getSiteDefaultLang(), 0, 2) || $item->language == '*') {
         $lang_parent_id = $item->lang_parent_id;
         $item->lang_parent_id = $isnew ? 0 : $item->id;
         if ($item->lang_parent_id != $lang_parent_id && $lang_parent_id) {
             $app->enqueueMessage(JText::_('FLEXI_ORIGINAL_CONTENT_WAS_IGNORED'), 'message');
         }
     }
     // ****************************************************************************************************************
     // Get version info, force version approval ON is versioning disabled, and decide new item's current version number
     // ****************************************************************************************************************
     $last_version = FLEXIUtilities::getLastVersions($item->id, true);
     $current_version = FLEXIUtilities::getCurrentVersions($item->id, true);
     // (a) Force item approval when versioning disabled
     $data['vstate'] = !$use_versioning ? 2 : $data['vstate'];
     // (b) Force item approval when item is not yet visible (is in states (a) Draft or (b) Pending Approval)
     $data['vstate'] = $item->state == -3 || $item->state == -4 ? 2 : $data['vstate'];
     // Decide new current version for the item, this depends if versioning is ON and if versioned is approved
     if (!$use_versioning) {
         // not using versioning, increment current version numbering
         $item->version = $isnew ? 1 : $current_version + 1;
     } else {
         // using versioning, increment last version numbering, or keep current version number if new version was not approved
         $item->version = $isnew ? 1 : ($data['vstate'] == 2 ? $last_version + 1 : $current_version);
     }
     // *** Item version should be zero when form was loaded with no type id,
     // *** thus next item form load will load default values of custom fields
     $item->version = $isnew && !empty($data['type_id_not_set']) ? 0 : $item->version;
     if ($print_logging_info) {
         @($fc_run_times['item_store_prepare'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
     }
     // *********************************************************************************************
     // Make sure we import flexicontent AND content plugins since we will be triggering their events
     // *********************************************************************************************
     JPluginHelper::importPlugin('flexicontent');
     JPluginHelper::importPlugin('content');
     // **************************************************************************************************
     // Trigger Event 'onBeforeSaveItem' of FLEXIcontent plugins (such plugin is the 'flexinotify' plugin)
     // **************************************************************************************************
     if ($print_logging_info) {
         $start_microtime = microtime(true);
     }
     $result = $dispatcher->trigger('onBeforeSaveItem', array(&$item, $isnew));
     if (count($result) > 0 && in_array(false, $result, true)) {
         return false;
     }
     // cancel item save
     if ($print_logging_info) {
         $fc_run_times['onBeforeSaveItem_event'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
     }
     // ******************************************************************************************************
     // Trigger Event 'OnBeforeContentSave' (J1.5) or 'onContentBeforeSave' (J2.5) of Joomla's Content plugins
     // ******************************************************************************************************
     // Some compatibility steps
     if (!$isnew) {
         $db->setQuery('UPDATE #__content SET state = ' . $jm_state . ' WHERE id = ' . $item->id);
         $db->query();
     }
     JRequest::setVar('view', 'article');
     JRequest::setVar('option', 'com_content');
     if ($print_logging_info) {
         $start_microtime = microtime(true);
     }
     if (FLEXI_J16GE) {
         $result = $dispatcher->trigger($this->event_before_save, array('com_content.article', &$item, $isnew));
     } else {
         $result = $dispatcher->trigger('onBeforeContentSave', array(&$item, $isnew));
     }
     if ($print_logging_info) {
         $fc_run_times['onContentBeforeSave_event'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
     }
     // Reverse compatibility steps
     if (!$isnew) {
         $db->setQuery('UPDATE #__content SET state = ' . $fc_state . ' WHERE id = ' . $item->id);
         $db->query();
     }
     JRequest::setVar('view', $view);
     JRequest::setVar('option', 'com_flexicontent');
     if (in_array(false, $result, true)) {
         $this->setError($item->getError());
         return false;
     }
     // cancel item save
     // ************************************************************************************************************
     // IF new item, create it before saving the fields (and constructing the search_index out of searchable fields)
     // ************************************************************************************************************
     if ($print_logging_info) {
         $start_microtime = microtime(true);
     }
     if ($isnew) {
         $this->applyCurrentVersion($item, $data, $createonly = true);
     } else {
         // Make sure the data of the model are correct,
         // e.g. a getForm() used to validate input data may have set an empty item and empty id
         // e.g. type_id of item may have been altered by authorized users
         $this->_id = $item->id;
         $this->_item =& $item;
     }
     if ($print_logging_info) {
         $fc_run_times['item_store_core'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
     }
     // ****************************************************************************
     // Save fields values to appropriate tables (versioning table or normal tables)
     // NOTE: This allow canceling of item save operation, if 'abort' is returned
     // ****************************************************************************
     $files = JRequest::get('files', JREQUEST_ALLOWRAW);
     $result = $this->saveFields($isnew, $item, $data, $files);
     $version_approved = $isnew || $data['vstate'] == 2;
     if ($result === 'abort') {
         if ($isnew) {
             if (FLEXI_J16GE) {
                 $db->setQuery('DELETE FROM #__assets WHERE id = (SELECT asset_id FROM #__content WHERE id=' . $item->id . ')');
                 $db->query();
             } else {
                 if (FLEXI_ACCESS) {
                     $db->setQuery('DELETE FROM #__flexiaccess_acl WHERE acosection = `com_content` AND axosection = `item` AND axo =' . $item->id);
                     $db->query();
                 }
             }
             $db->setQuery('DELETE FROM #__content WHERE id =' . $item->id);
             $db->query();
             $db->setQuery('DELETE FROM #__flexicontent_items_ext WHERE item_id=' . $item->id);
             $db->query();
             $this->setId(0);
             $this->setError($this->getError() . ' ' . JText::_('FLEXI_NEW_ITEM_NOT_CREATED'));
         } else {
             $this->setError($this->getError() . ' ' . JText::_('FLEXI_EXISTING_ITEM_NOT_SAVED'));
         }
         // Set form to reload posted data
         /*$session = JFactory::getSession();
         		$session->set('item_edit_postdata', $data, 'flexicontent');*/
         return false;
     }
     // ***************************************************************
     // ITEM DATA SAVED:  EITHER new, OR approving current item version
     // ***************************************************************
     if ($version_approved) {
         // *****************************
         // Save item to #__content table
         // *****************************
         if ($print_logging_info) {
             $start_microtime = microtime(true);
         }
         if (!$this->applyCurrentVersion($item, $data)) {
             return false;
         }
         if ($print_logging_info) {
             @($fc_run_times['item_store_core'] += round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
         }
         //echo "<pre>"; var_dump($data); exit();
         // ***************************
         // Update Joomla Featured FLAG
         // ***************************
         if (FLEXI_J16GE) {
             $this->featured(array($item->id), $item->featured);
         }
         // *****************************************************************************************************
         // Trigger Event 'onAfterContentSave' (J1.5) OR 'onContentAfterSave' (J2.5 ) of Joomla's Content plugins
         // *****************************************************************************************************
         if ($print_logging_info) {
             $start_microtime = microtime(true);
         }
         // Some compatibility steps
         JRequest::setVar('view', 'article');
         JRequest::setVar('option', 'com_content');
         if (FLEXI_J16GE) {
             $dispatcher->trigger($this->event_after_save, array('com_content.article', &$item, $isnew));
         } else {
             $dispatcher->trigger('onAfterContentSave', array(&$item, $isnew));
         }
         // Reverse compatibility steps
         JRequest::setVar('view', $view);
         JRequest::setVar('option', 'com_flexicontent');
         if ($print_logging_info) {
             @($fc_run_times['onContentAfterSave_event'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
         }
     }
     // *************************************************************************************************
     // Trigger Event 'onAfterSaveItem' of FLEXIcontent plugins (such plugin is the 'flexinotify' plugin)
     // *************************************************************************************************
     if ($print_logging_info) {
         $start_microtime = microtime(true);
     }
     $results = $dispatcher->trigger('onAfterSaveItem', array(&$item, &$data));
     if ($print_logging_info) {
         @($fc_run_times['onAfterSaveItem_event'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
     }
     // *********************************************************************
     // ITEM DATA NOT SAVED:  NEITHER new, NOR approving current item version
     // *********************************************************************
     if (!$version_approved) {
         // Warn editor that his/her changes will need approval to before becoming visible
         if ($canEditState) {
             JError::raiseNotice(11, JText::_('FLEXI_SAVED_VERSION_WAS_NOT_APPROVED_NOTICE'));
         } else {
             JError::raiseNotice(10, JText::_('FLEXI_SAVED_VERSION_MUST_BE_APPROVED_NOTICE'));
         }
         // Set modifier and modification time (as if item has been saved), so that we can use this information for updating the versioning tables
         $datenow = JFactory::getDate();
         $item->modified = FLEXI_J16GE ? $datenow->toSql() : $datenow->toMySQL();
         $item->modified_by = $user->get('id');
     }
     // *********************************************
     // Create and store version METADATA information
     // *********************************************
     if ($print_logging_info) {
         $start_microtime = microtime(true);
     }
     if ($use_versioning) {
         $v = new stdClass();
         $v->item_id = (int) $item->id;
         $v->version_id = $isnew && !empty($data['type_id_not_set']) ? 0 : (int) $last_version + 1;
         $v->created = $item->created;
         $v->created_by = $item->created_by;
         if ($item->modified != $nullDate) {
             // NOTE: We set modifier as creator of the version, and modication date as creation date of the version
             $v->created = $item->modified;
             $v->created_by = $item->modified_by;
         }
         $v->comment = isset($data['versioncomment']) ? htmlspecialchars($data['versioncomment'], ENT_QUOTES) : '';
         $this->_db->insertObject('#__flexicontent_versions', $v);
     }
     // *************************************************************
     // Delete old versions that are above the limit of kept versions
     // *************************************************************
     $vcount = FLEXIUtilities::getVersionsCount($item->id);
     $vmax = $cparams->get('nr_versions', 10);
     if ($vcount > $vmax) {
         $deleted_version = FLEXIUtilities::getFirstVersion($item->id, $vmax, $current_version);
         $query = 'DELETE' . ' FROM #__flexicontent_items_versions' . ' WHERE item_id = ' . (int) $item->id . ' AND version <=' . $deleted_version . ' AND version!=' . (int) $current_version;
         $this->_db->setQuery($query);
         $this->_db->query();
         $query = 'DELETE' . ' FROM #__flexicontent_versions' . ' WHERE item_id = ' . (int) $item->id . ' AND version_id <=' . $deleted_version . ' AND version_id!=' . (int) $current_version;
         $this->_db->setQuery($query);
         $this->_db->query();
     }
     if ($print_logging_info) {
         @($fc_run_times['ver_cleanup_ver_metadata'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
     }
     // ****************************************************************************************************
     // Trigger Event 'onCompleteSaveItem' of FLEXIcontent plugins (such plugin is the 'flexinotify' plugin)
     // ****************************************************************************************************
     if ($print_logging_info) {
         $start_microtime = microtime(true);
     }
     $results = $dispatcher->trigger('onCompleteSaveItem', array(&$item, &$fields));
     if ($print_logging_info) {
         @($fc_run_times['onCompleteSaveItem_event'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
     }
     return true;
 }
 function display($tpl = null)
 {
     global $globalcats;
     $app = JFactory::getApplication();
     $user = JFactory::getUser();
     $document = JFactory::getDocument();
     JFactory::getLanguage()->load('com_categories', JPATH_ADMINISTRATOR, 'en-GB', true);
     JFactory::getLanguage()->load('com_categories', JPATH_ADMINISTRATOR, null, true);
     // ***********************************************************
     // Get category data, and check if item is already checked out
     // ***********************************************************
     // Get data from the model
     $model = $this->getModel();
     if (FLEXI_J16GE) {
         $row = $this->get('Item');
         $form = $this->get('Form');
     } else {
         $row = $this->get('Category');
     }
     $catparams = new JRegistry($row->params);
     $cid = $row->id;
     $isnew = !$cid;
     // Check category is checked out by different editor / administrator
     if (!$isnew && $model->isCheckedOut($user->get('id'))) {
         JError::raiseWarning('SOME_ERROR_CODE', $row->title . ' ' . JText::_('FLEXI_EDITED_BY_ANOTHER_ADMIN'));
         $app->redirect('index.php?option=com_flexicontent&view=categories');
     }
     // ***************************************************************************
     // Currently access checking for category add/edit form , it is done here, for
     // most other views we force going though the controller and checking it there
     // ***************************************************************************
     // *********************************************************************************************
     // Global Permssions checking (needed because this view can be called without a controller task)
     // *********************************************************************************************
     // Get global permissions
     $perms = FlexicontentHelperPerm::getPerm();
     // handles super admins correctly
     // Check no access to categories management (Global permission)
     if (!$perms->CanCats) {
         $app->redirect('index.php?option=com_flexicontent', JText::_('FLEXI_NO_ACCESS'));
     }
     // Check no privilege to create new categories (Global permission)
     if ($isnew && !$perms->CanAddCats) {
         JError::raiseWarning(403, JText::_('FLEXI_NO_ACCESS_CREATE'));
         $app->redirect('index.php?option=com_flexicontent');
     }
     // ************************************************************************************
     // Record Permssions (needed because this view can be called without a controller task)
     // ************************************************************************************
     // Get edit privilege for current category
     if (!$isnew) {
         if (FLEXI_J16GE) {
             $isOwner = $row->get('created_by') == $user->id;
             $rights = FlexicontentHelperPerm::checkAllItemAccess($user->id, 'category', $cid);
             $canedit_cat = in_array('edit', $rights) || in_array('edit.own', $rights) && $isOwner;
         } else {
             if (FLEXI_ACCESS) {
                 $rights = FAccess::checkAllItemAccess('com_content', 'users', $user->gmid, 0, $row->id);
                 $canedit_cat = $user->gid < 25 ? in_array('edit', $rights) || in_array('editown', $rights) : 1;
             } else {
                 $canedit_cat = true;
             }
         }
     }
     // Get if we can create inside at least one (com_content) category
     if ($user->authorise('core.create', 'com_flexicontent')) {
         $cancreate_cat = true;
     } else {
         $usercats = FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.create'), $require_all = true, $check_published = true, $specific_catids = false, $find_first = true);
         $cancreate_cat = count($usercats) > 0;
     }
     // Creating new category: Check if user can create inside any existing category
     if ($isnew && !$cancreate_cat) {
         $acc_msg = JText::_('FLEXI_NO_ACCESS_CREATE') . "<br/>" . (FLEXI_J16GE ? JText::_('FLEXI_CANNOT_ADD_CATEGORY_REASON') : "");
         JError::raiseWarning(403, $acc_msg);
         $app->redirect('index.php?option=com_flexicontent&view=categories');
     }
     // Editing existing category: Check if user can edit existing (current) category
     if (!$isnew && !$canedit_cat) {
         $acc_msg = JText::_('FLEXI_NO_ACCESS_EDIT') . "<br/>" . JText::_('FLEXI_CANNOT_EDIT_CATEGORY_REASON');
         JError::raiseWarning(403, $acc_msg);
         $app->redirect('index.php?option=com_flexicontent&view=categories');
     }
     // **************************************************
     // Include needed files and add needed 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);
     // Add JS frameworks
     flexicontent_html::loadFramework('select2');
     // Add js function to overload the joomla submitform validation
     JHTML::_('behavior.formvalidation');
     // load default validation JS to make sure it is overriden
     $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/admin.js', FLEXI_VERSION);
     $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/validate.js', FLEXI_VERSION);
     //Load pane behavior
     jimport('joomla.html.pane');
     // ********************
     // Initialise variables
     // ********************
     $editor_name = $user->getParam('editor', $app->getCfg('editor'));
     $editor = JFactory::getEditor($editor_name);
     $cparams = JComponentHelper::getParams('com_flexicontent');
     $categories = $globalcats;
     $bar = JToolBar::getInstance('toolbar');
     $tip_class = FLEXI_J30GE ? ' hasTooltip' : ' hasTip';
     // ******************
     // Create the toolbar
     // ******************
     // Create Toolbar title and add the preview button
     if (!$isnew) {
         JToolBarHelper::title(JText::_('FLEXI_EDIT_CATEGORY'), 'fc_categoryedit');
     } else {
         JToolBarHelper::title(JText::_('FLEXI_NEW_CATEGORY'), 'fc_categoryadd');
     }
     // Add apply and save buttons
     JToolBarHelper::apply('category.apply', 'FLEXI_APPLY');
     /*if ( !$isnew ) flexicontent_html::addToolBarButton(
     		'FLEXI_FAST_APPLY', $btn_name='apply_ajax', $full_js="Joomla.submitbutton('category.apply_ajax')", $msg_alert='', $msg_confirm='',
     		$btn_task='category.apply_ajax', $extra_js='', $btn_list=false, $btn_menu=true, $btn_confirm=false, $btn_class="", $btn_icon="icon-loop");*/
     JToolBarHelper::save('category.save');
     // Add a save and new button, if user can create inside at least one (com_content) category
     if ($cancreate_cat) {
         JToolBarHelper::save2new('category.save2new');
     }
     // Add a save as copy button, if editing an existing category (J2.5 only)
     if (!$isnew && $cancreate_cat) {
         JToolBarHelper::save2copy('category.save2copy');
     }
     // Add a cancel or close button
     if ($isnew) {
         JToolBarHelper::cancel('category.cancel');
     } else {
         JToolBarHelper::cancel('category.cancel', 'JTOOLBAR_CLOSE');
     }
     // ******************
     // Add preview button
     // ******************
     if (!$isnew) {
         JToolBarHelper::divider();
         $autologin = '';
         //$cparams->get('autoflogin', 1) ? '&fcu='.$user->username . '&fcp='.$user->password : '';
         $previewlink = JRoute::_(JURI::root() . FlexicontentHelperRoute::getCategoryRoute($categories[$cid]->slug)) . $autologin;
         // Add a preview button
         $bar->appendButton('Custom', '<a class="preview btn btn-small btn-info spaced-btn" href="' . $previewlink . '" target="_blank" ><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('Preview') . '</a>', 'preview');
     }
     // ************************
     // Add modal layout editing
     // ************************
     if (!$isnew && $perms->CanTemplates) {
         $inheritcid_comp = $cparams->get('inheritcid', -1);
         $inheritcid = $catparams->get('inheritcid', '');
         $inherit_parent = $inheritcid === '-1' || $inheritcid === '' && $inheritcid_comp;
         if (!$inherit_parent || $row->parent_id === '1') {
             $row_clayout = $catparams->get('clayout', $cparams->get('clayout', 'blog'));
         } else {
             $row_clayout = $catparams->get('clayout', '');
             if (!$row_clayout) {
                 $_ancestors = $this->getModel()->getParentParams($row->id);
                 // This is ordered by level ASC
                 $row_clayout = $cparams->get('clayout', 'blog');
                 $cats_params = array();
                 foreach ($_ancestors as $_cid => $_cat) {
                     $cats_params = new JRegistry($_cat->params);
                     $row_clayout = $cats_params->get('clayout', '') ? $cats_params->get('clayout', '') : $row_clayout;
                 }
             }
         }
         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=category&amp;tmpl=component&amp;ismodal=1&amp;folder=' . $row_clayout . '" title="Edit the display layout of this category. <br/><br/>Note: this layout maybe assigned to other categories, thus changing it will effect them too"');
     }
     // *******************************************
     // Prepare data to pass to the form's template
     // *******************************************
     if (!FLEXI_J16GE) {
         //clean data
         JFilterOutput::objectHTMLSafe($row, ENT_QUOTES, 'description');
         // Create the form
         $form = new JParameter($row->params, JPATH_COMPONENT . DS . 'models' . DS . 'category.xml');
         //$form->loadINI($row->attribs);
         //echo "<pre>"; print_r($form->_xml['templates']->_children[0]);  echo "<pre>"; print_r($form->_xml['templates']->param[0]); exit;
         foreach ($form->_xml['templates']->_children as $i => $child) {
             if (isset($child->_attributes['enableparam']) && !$cparams->get($child->_attributes['enableparam'])) {
                 unset($form->_xml['templates']->_children[$i]);
                 unset($form->_xml['templates']->param[$i]);
             }
         }
         foreach ($form->_xml['special']->_children as $i => $child) {
             if (isset($child->_attributes['enableparam']) && !$cparams->get($child->_attributes['enableparam'])) {
                 unset($form->_xml['special']->_children[$i]);
                 unset($form->_xml['special']->param[$i]);
             }
         }
     }
     // **********************************************************************************
     // Get Templates and apply Template Parameters values into the form fields structures
     // **********************************************************************************
     $themes = flexicontent_tmpl::getTemplates();
     $tmpls = $themes->category;
     foreach ($tmpls as $tmpl) {
         $jform = new JForm('com_flexicontent.template.category', array('control' => 'jform', 'load_data' => true));
         $jform->load($tmpl->params);
         $tmpl->params = $jform;
         // ... values applied at the template form file
     }
     //build selectlists
     $Lists = array();
     if (!FLEXI_J16GE) {
         $javascript = "onchange=\"javascript:if (document.forms[0].image.options[selectedIndex].value!='') {document.imagelib.src='../images/stories/' + document.forms[0].image.options[selectedIndex].value} else {document.imagelib.src='../images/blank.png'}\"";
         $Lists['imagelist'] = JHTML::_('list.images', 'image', $row->image, $javascript, '/images/stories/');
         $Lists['access'] = JHTML::_('list.accesslevel', $row);
         // build granular access list
         if (FLEXI_ACCESS) {
             $Lists['access'] = FAccess::TabGmaccess($row, 'category', 1, 1, 1, 1, 1, 1, 1, 1, 1);
         }
     }
     $check_published = false;
     $check_perms = true;
     $actions_allowed = array('core.create');
     $fieldname = FLEXI_J16GE ? 'jform[parent_id]' : 'parent_id';
     $Lists['parent_id'] = flexicontent_cats::buildcatselect($categories, $fieldname, $row->parent_id, $top = 1, 'class="use_select2_lib"', $check_published, $check_perms, $actions_allowed, $require_all = true, $skip_subtrees = array(), $disable_subtrees = array($row->id));
     $check_published = false;
     $check_perms = true;
     $actions_allowed = array('core.edit', 'core.edit.own');
     $fieldname = FLEXI_J16GE ? 'jform[copycid]' : 'copycid';
     $Lists['copycid'] = flexicontent_cats::buildcatselect($categories, $fieldname, '', $top = 2, 'class="use_select2_lib"', $check_published, $check_perms, $actions_allowed, $require_all = false);
     $custom_options[''] = 'FLEXI_USE_GLOBAL';
     $custom_options['0'] = 'FLEXI_COMPONENT_ONLY';
     $custom_options['-1'] = 'FLEXI_PARENT_CAT_MULTI_LEVEL';
     $check_published = false;
     $check_perms = true;
     $actions_allowed = array('core.edit', 'core.edit.own');
     $fieldname = FLEXI_J16GE ? 'jform[special][inheritcid]' : 'params[inheritcid]';
     $Lists['inheritcid'] = flexicontent_cats::buildcatselect($categories, $fieldname, $catparams->get('inheritcid', ''), $top = false, 'class="use_select2_lib"', $check_published, $check_perms, $actions_allowed, $require_all = false, $skip_subtrees = array(), $disable_subtrees = array(), $custom_options);
     // ************************
     // Assign variables to view
     // ************************
     $this->assignRef('document', $document);
     $this->assignRef('Lists', $Lists);
     $this->assignRef('row', $row);
     $this->assignRef('form', $form);
     $this->assignRef('perms', $perms);
     $this->assignRef('editor', $editor);
     $this->assignRef('tmpls', $tmpls);
     $this->assignRef('cparams', $cparams);
     parent::display($tpl);
 }
Example #11
0
 /**
  * Method to build the where clause of the query for the Items
  *
  * @access private
  * @return string
  * @since 1.0
  */
 function _buildContentWhere(&$extra_joins = "")
 {
     $app = JFactory::getApplication();
     $option = JRequest::getVar('option');
     $session = JFactory::getSession();
     $user = JFactory::getUser();
     $cparams = JComponentHelper::getParams('com_flexicontent');
     $perms = FlexicontentHelperPerm::getPerm();
     // ***********************************
     // FLAGs to decide which items to list
     // ***********************************
     $allitems = $perms->DisplayAllItems;
     $viewable_items = $cparams->get('iman_viewable_items', 1);
     $editable_items = $cparams->get('iman_editable_items', 0);
     // ************************************************************************
     // SPECIAL item listing CASES, item ids are already calculated and provided,
     // in such a case WHERE clause limits to the given item ids
     // ************************************************************************
     // CASE 1: listing items using a file
     $filter_fileid = JRequest::getInt('filter_fileid', 0);
     if ($filter_fileid) {
         $fileid_to_itemids = $session->get('fileid_to_itemids', array(), 'flexicontent');
         $itemids = $fileid_to_itemids[$filter_fileid];
         if (empty($itemids)) {
             return ' WHERE 0 ';
         } else {
             return ' WHERE i.id IN (' . implode(',', $itemids) . ') ';
         }
     }
     // *********************
     // Get item list filters
     // *********************
     $filter_type = $app->getUserStateFromRequest($option . '.items.filter_type', 'filter_type', '', 'int');
     $filter_cats = $app->getUserStateFromRequest($option . '.items.filter_cats', 'filter_cats', '', 'int');
     $filter_subcats = $app->getUserStateFromRequest($option . '.items.filter_subcats', 'filter_subcats', 1, 'int');
     $filter_catsinstate = $app->getUserStateFromRequest($option . '.items.filter_catsinstate', 'filter_catsinstate', 1, 'int');
     $filter_state = $app->getUserStateFromRequest($option . '.items.filter_state', 'filter_state', '', 'word');
     $filter_stategrp = $app->getUserStateFromRequest($option . '.items.filter_stategrp', 'filter_stategrp', '', 'word');
     $filter_id = $app->getUserStateFromRequest($option . '.items.filter_id', 'filter_id', '', 'int');
     if (FLEXI_FISH || FLEXI_J16GE) {
         $filter_lang = $app->getUserStateFromRequest($option . '.items.filter_lang', 'filter_lang', '', 'string');
     }
     $filter_authors = $app->getUserStateFromRequest($option . '.items.filter_authors', 'filter_authors', '', 'int');
     $scope = $app->getUserStateFromRequest($option . '.items.scope', 'scope', '', 'int');
     $search = $app->getUserStateFromRequest($option . '.items.search', 'search', '', 'string');
     $search = trim(JString::strtolower($search));
     $date = $app->getUserStateFromRequest($option . '.items.date', 'date', 1, 'int');
     $startdate = $app->getUserStateFromRequest($option . '.items.startdate', 'startdate', '', 'cmd');
     if ($startdate == JText::_('FLEXI_FROM')) {
         $startdate = $app->setUserState($option . '.items.startdate', '');
     }
     $startdate = trim(JString::strtolower($startdate));
     $enddate = $app->getUserStateFromRequest($option . '.items.enddate', 'enddate', '', 'cmd');
     if ($enddate == JText::_('FLEXI_TO')) {
         $enddate = $app->setUserState($option . '.items.enddate', '');
     }
     $enddate = trim(JString::strtolower($enddate));
     // ********************************************
     // Start building the AND parts of where clause
     // ********************************************
     $where = array();
     if (FLEXI_J16GE) {
         // Limit items to the children of the FLEXI_CATEGORY, currently FLEXI_CATEGORY is root category (id:1) ...
         $where[] = ' (cat.lft > ' . $this->_db->Quote(FLEXI_LFT_CATEGORY) . ' AND cat.rgt < ' . $this->_db->Quote(FLEXI_RGT_CATEGORY) . ')';
         $where[] = ' cat.extension = ' . $this->_db->Quote(FLEXI_CAT_EXTENSION);
     } else {
         // Limit items to FLEXIcontent Section
         $where[] = ' i.sectionid = ' . $this->_db->Quote(FLEXI_SECTION);
     }
     // *************************************
     // IF items viewable: default is enabled
     // *************************************
     $joinaccess = "";
     if (!$allitems && $viewable_items) {
         if (FLEXI_J16GE) {
             $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
             $aid_list = implode(",", $aid_arr);
             $where[] = ' t.access IN (0,' . $aid_list . ')';
             $where[] = ' c.access IN (0,' . $aid_list . ')';
             $where[] = ' i.access IN (0,' . $aid_list . ')';
         } else {
             $aid = (int) $user->get('aid');
             if (FLEXI_ACCESS) {
                 $joinaccess .= ' LEFT JOIN #__flexiaccess_acl AS gt ON  t.id = gt.axo AND gt.aco = "read" AND gt.axosection = "type"';
                 $joinaccess .= ' LEFT JOIN #__flexiaccess_acl AS gc ON  c.id = gc.axo AND gc.aco = "read" AND gc.axosection = "category"';
                 $joinaccess .= ' LEFT JOIN #__flexiaccess_acl AS gi ON  i.id = gi.axo AND gi.aco = "read" AND gi.axosection = "item"';
                 $where[] = ' (gt.aro IN ( ' . $user->gmid . ' ) OR  t.access <= ' . $aid . ')';
                 $where[] = ' (gc.aro IN ( ' . $user->gmid . ' ) OR  c.access <= ' . $aid . ')';
                 $where[] = ' (gi.aro IN ( ' . $user->gmid . ' ) OR  i.access <= ' . $aid . ')';
             } else {
                 $where[] = '  t.access <= ' . $aid;
                 $where[] = '  c.access <= ' . $aid;
                 $where[] = '  i.access <= ' . $aid;
             }
         }
     }
     $extra_joins .= $joinaccess;
     // ************************************************************
     // IF items in an editable (main) category: default is disabled
     // ************************************************************
     $allowedcats = false;
     $allowedcats_own = false;
     if (!$allitems && $editable_items) {
         if (FLEXI_J16GE || FLEXI_ACCESS) {
             $allowedcats = FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.edit'), $require_all = true, $check_published = false, false, $find_first = false);
             $allowedcats_own = FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.edit.own'), $require_all = true, $check_published = false, false, $find_first = false);
         } else {
             // In J1.5 without FLEXIaccess, the backend users can edit all files by default,
             // since they belong to at least the managers user-group
             // and ... listing only editable items is too slow in large websites, disable it
             //if (FLEXI_ACCESS)  $this->faccess_items_editable_where($where);
         }
         if ($allowedcats || $allowedcats_own) {
             $_edit_where = '( ';
             if ($allowedcats) {
                 $_edit_where .= '( i.catid IN (' . implode(', ', $allowedcats) . ') )';
             }
             if ($allowedcats && $allowedcats_own) {
                 $_edit_where .= ' OR ';
             }
             if ($allowedcats_own) {
                 $_edit_where .= '( i.catid IN (' . implode(', ', $allowedcats_own) . ') AND i.created_by=' . $user->id . ')';
             }
             $where[] = $_edit_where . ' )';
         }
     }
     // *******************************
     // Limit using the category filter
     // *******************************
     if ($filter_cats) {
         // CURRENTLY in main or secondary category.  -TODO-  maybe add limiting by main category, if ... needed
         $cat_type = 'rel.catid';
         // $filter_maincat ? 'i.catid' : 'rel.catid';
         if ($filter_subcats) {
             global $globalcats;
             $_sub_cids = array();
             if ($filter_catsinstate == 99) {
                 $_sub_cids = $globalcats[$filter_cats]->descendantsarray;
             } else {
                 foreach ($globalcats[$filter_cats]->descendantsarray as $_dcatid) {
                     if ($globalcats[$_dcatid]->published == $filter_catsinstate) {
                         $_sub_cids[] = $_dcatid;
                     }
                 }
             }
             if (empty($_sub_cids)) {
                 $where[] = ' FALSE  ';
             } else {
                 $where[] = '(' . $cat_type . ' IN (' . implode(', ', $_sub_cids) . ')' . ' OR ' . 'c.id IN (' . implode(', ', $_sub_cids) . '))';
             }
         } else {
             $where[] = $cat_type . ' = ' . $filter_cats;
         }
     } else {
         if ($filter_catsinstate != 99) {
             // if not showing items in any category state
             $where[] = '(rel.catid IN ( SELECT id FROM #__categories WHERE published=' . $filter_catsinstate . ' )' . ' OR ' . 'c.published = ' . $filter_catsinstate . ')';
         }
     }
     // ************************************************************
     // Limit using state or group of states (e.g. published states)
     // ************************************************************
     if ($filter_stategrp == 'all') {
         // no limitations
     } else {
         if ($filter_stategrp == 'published') {
             $where[] = 'i.state IN (1,-5)';
         } else {
             if ($filter_stategrp == 'unpublished') {
                 $where[] = 'i.state IN (0,-3,-4)';
             } else {
                 if ($filter_stategrp == 'trashed') {
                     $where[] = 'i.state = -2';
                 } else {
                     if ($filter_stategrp == 'archived') {
                         $where[] = 'i.state = ' . (FLEXI_J16GE ? 2 : -1);
                     } else {
                         if ($filter_stategrp == 'orphan') {
                             $where[] = 'i.state NOT IN (' . (FLEXI_J16GE ? 2 : -1) . ',-2,1,0,-3,-4,-5)';
                         } else {
                             $where[] = 'i.state <> -2';
                             $where[] = 'i.state <> ' . (FLEXI_J16GE ? 2 : -1);
                             if ($filter_state) {
                                 if ($filter_state == 'P') {
                                     $where[] = 'i.state = 1';
                                 } else {
                                     if ($filter_state == 'U') {
                                         $where[] = 'i.state = 0';
                                     } else {
                                         if ($filter_state == 'PE') {
                                             $where[] = 'i.state = -3';
                                         } else {
                                             if ($filter_state == 'OQ') {
                                                 $where[] = 'i.state = -4';
                                             } else {
                                                 if ($filter_state == 'IP') {
                                                     $where[] = 'i.state = -5';
                                                 } else {
                                                     if ($filter_state == 'RV') {
                                                         $where[] = 'i.state = 1 OR i.state = -5';
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     // ***********************************************************************
     // Limit using simpler filtering, (item) type, author, (item) id, language
     // ***********************************************************************
     if ($filter_type) {
         $where[] = 'i.type_id = ' . $filter_type;
     }
     if ($filter_authors) {
         $where[] = 'i.created_by = ' . $filter_authors;
     }
     if ($filter_id) {
         $where[] = 'i.id = ' . $filter_id;
     }
     if ((FLEXI_FISH || FLEXI_J16GE) && $filter_lang) {
         $where[] = 'i.language = ' . $this->_db->Quote($filter_lang);
     }
     // *********************
     // TEXT search filtering
     // *********************
     if ($search) {
         $escaped_search = FLEXI_J16GE ? $this->_db->escape($search, true) : $this->_db->getEscaped($search, true);
     }
     if ($search && $scope == 1) {
         $where[] = ' LOWER(i.title) LIKE ' . $this->_db->Quote('%' . $escaped_search . '%', false);
     }
     if ($search && $scope == 2) {
         $where[] = ' LOWER(i.introtext) LIKE ' . $this->_db->Quote('%' . $escaped_search . '%', false);
     }
     if ($search && $scope == 4) {
         $where[] = ' MATCH (ie.search_index) AGAINST (' . $this->_db->Quote($escaped_search . '*', false) . ' IN BOOLEAN MODE)';
     }
     // ***************************************************
     // Date range filtering (creation and/or modification)
     // ***************************************************
     $nullDate = $this->_db->getNullDate();
     if ($date == 1) {
         if ($startdate && !$enddate) {
             // from only
             $where[] = ' i.created >= ' . $this->_db->Quote($startdate);
         }
         if (!$startdate && $enddate) {
             // to only
             $where[] = ' i.created <= ' . $this->_db->Quote($enddate);
         }
         if ($startdate && $enddate) {
             // date range
             $where[] = '( i.created >= ' . $this->_db->Quote($startdate) . ' AND i.created <= ' . $this->_db->Quote($enddate) . ' )';
         }
     }
     if ($date == 2) {
         if ($startdate && !$enddate) {
             // from only
             $where[] = '( i.modified >= ' . $this->_db->Quote($startdate) . ' OR ( i.modified = ' . $this->_db->Quote($nullDate) . ' AND i.created >= ' . $this->_db->Quote($startdate) . '))';
         }
         if (!$startdate && $enddate) {
             // to only
             $where[] = '( i.modified <= ' . $this->_db->Quote($enddate) . ' OR ( i.modified = ' . $this->_db->Quote($nullDate) . ' AND i.created <= ' . $this->_db->Quote($enddate) . '))';
         }
         if ($startdate && $enddate) {
             // date range
             $where[] = '(( i.modified >= ' . $this->_db->Quote($startdate) . ' OR ( i.modified = ' . $this->_db->Quote($nullDate) . ' AND i.created >= ' . $this->_db->Quote($startdate) . ')) AND ( i.modified <= ' . $this->_db->Quote($enddate) . ' OR ( i.modified = ' . $this->_db->Quote($nullDate) . ' AND i.created <= ' . $this->_db->Quote($enddate) . ')))';
         }
     }
     // *************************************************
     // Finally create the AND clause of the WHERE clause
     // *************************************************
     $where = count($where) ? ' WHERE ' . implode(' AND ', $where) : '';
     return $where;
 }
Example #12
0
 function display($tpl = null)
 {
     // ********************
     // Initialise variables
     // ********************
     global $globalcats;
     $app = JFactory::getApplication();
     $cparams = JComponentHelper::getParams('com_flexicontent');
     $user = JFactory::getUser();
     $db = JFactory::getDBO();
     $document = JFactory::getDocument();
     $option = JRequest::getCmd('option');
     $view = JRequest::getVar('view');
     $order_property = 'c.lft';
     // Get model
     $model = $this->getModel();
     $print_logging_info = $cparams->get('print_logging_info');
     if ($print_logging_info) {
         global $fc_run_times;
     }
     // ***********
     // Get filters
     // ***********
     $count_filters = 0;
     // various filters
     $filter_state = $model->getState('filter_state');
     $filter_cats = $model->getState('filter_cats');
     $filter_level = $model->getState('filter_level');
     $filter_access = $model->getState('filter_access');
     $filter_language = $model->getState('filter_language');
     if ($filter_state) {
         $count_filters++;
     }
     if ($filter_cats) {
         $count_filters++;
     }
     if ($filter_level) {
         $count_filters++;
     }
     if ($filter_access) {
         $count_filters++;
     }
     if ($filter_language) {
         $count_filters++;
     }
     // Item ID filter
     $filter_id = $model->getState('filter_id');
     if ($filter_id) {
         $count_filters++;
     }
     // text search
     $search = $model->getState('search');
     $search = $db->escape(trim(JString::strtolower($search)));
     // ordering
     $filter_order = $model->getState('filter_order');
     $filter_order_Dir = $model->getState('filter_order_Dir');
     // **************************
     // Add css and js to document
     // **************************
     flexicontent_html::loadFramework('select2');
     //JHTML::_('behavior.tooltip');
     $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontentbackend.css', FLEXI_VHASH);
     $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/j3x.css', FLEXI_VHASH);
     // *****************************
     // Get user's global permissions
     // *****************************
     $perms = FlexicontentHelperPerm::getPerm();
     // ************************
     // Create Submenu & Toolbar
     // ************************
     // Create Submenu (and also check access to current view)
     FLEXISubmenu('CanCats');
     // Create document/toolbar titles
     $doc_title = JText::_('FLEXI_CATEGORIES');
     $site_title = $document->getTitle();
     JToolBarHelper::title($doc_title, 'fc_categories');
     $document->setTitle($doc_title . ' - ' . $site_title);
     $js = "jQuery(document).ready(function(){";
     $contrl = "categories.";
     $contrl_singular = "category.";
     $toolbar = JToolBar::getInstance('toolbar');
     // Copy Parameters
     $btn_task = '';
     $popup_load_url = JURI::base() . 'index.php?option=com_flexicontent&view=categories&layout=params&tmpl=component';
     if (FLEXI_J30GE || !FLEXI_J16GE) {
         // Layout of Popup button broken in J3.1, add in J1.5 it generates duplicate HTML tag id (... just for validation), so add manually
         $js .= "\n\t\t\t\tjQuery('#toolbar-params a.toolbar, #toolbar-params button')\n\t\t\t\t\t.attr('onclick', 'javascript:;')\n\t\t\t\t\t.attr('href', '" . $popup_load_url . "')\n\t\t\t\t\t.attr('rel', '{handler: \\'iframe\\', size: {x: 600, y: 440}, onClose: function() {}}');\n\t\t\t";
         JToolBarHelper::custom($btn_task, 'params.png', 'params_f2.png', 'FLEXI_COPY_PARAMS', false);
         JHtml::_('behavior.modal', '#toolbar-params a.toolbar, #toolbar-params button');
     } else {
         $toolbar->appendButton('Popup', 'params', JText::_('FLEXI_COPY_PARAMS'), str_replace('&', '&amp;', $popup_load_url), 600, 440);
     }
     //$toolbar->appendButton('Popup', 'move', JText::_('FLEXI_BATCH'), JURI::base().'index.php?option=com_flexicontent&amp;view=categories&amp;layout=batch&amp;tmpl=component', 800, 440);
     JToolBarHelper::divider();
     $add_divider = false;
     if ($user->authorise('core.create', 'com_flexicontent')) {
         $cancreate_cat = true;
     } else {
         $usercats = FlexicontentHelperPerm::getAllowedCats($user, $actions_allowed = array('core.create'), $require_all = true, $check_published = true, $specific_catids = false, $find_first = true);
         $cancreate_cat = count($usercats) > 0;
     }
     if ($cancreate_cat) {
         JToolBarHelper::addNew($contrl_singular . 'add');
         $add_divider = true;
     }
     if ($user->authorise('core.edit', 'com_flexicontent') || $user->authorise('core.edit.own', 'com_flexicontent')) {
         JToolBarHelper::editList($contrl_singular . 'edit');
         $add_divider = true;
     }
     $add_divider = false;
     if ($user->authorise('core.edit.state', 'com_flexicontent') || $user->authorise('core.edit.state.own', 'com_flexicontent')) {
         JToolBarHelper::publishList($contrl . 'publish');
         JToolBarHelper::unpublishList($contrl . 'unpublish');
         JToolBarHelper::divider();
         JToolBarHelper::archiveList($contrl . 'archive');
     }
     $add_divider = false;
     if ($filter_state == -2 && $user->authorise('core.delete', 'com_flexicontent')) {
         //JToolBarHelper::deleteList(JText::_('FLEXI_ARE_YOU_SURE'), $contrl.'remove');
         // This will work in J2.5+ too and is offers more options (above a little bogus in J1.5, e.g. bad HTML id tag)
         $msg_alert = JText::sprintf('FLEXI_SELECT_LIST_ITEMS_TO', JText::_('FLEXI_DELETE'));
         $msg_confirm = JText::_('FLEXI_ARE_YOU_SURE');
         $btn_task = $contrl . 'remove';
         $extra_js = "";
         flexicontent_html::addToolBarButton('FLEXI_DELETE', 'delete', '', $msg_alert, $msg_confirm, $btn_task, $extra_js, $btn_list = true, $btn_menu = true, $btn_confirm = true);
         $add_divider = true;
     } elseif ($user->authorise('core.edit.state', 'com_flexicontent')) {
         JToolBarHelper::trash($contrl . 'trash');
         $add_divider = true;
     }
     if ($add_divider) {
         JToolBarHelper::divider();
     }
     // Checkin
     JToolBarHelper::checkin($contrl . 'checkin');
     $appsman_path = JPATH_COMPONENT_ADMINISTRATOR . DS . 'views' . DS . 'appsman';
     if (file_exists($appsman_path)) {
         $btn_icon = 'icon-download';
         $btn_name = 'download';
         $btn_task = 'appsman.exportxml';
         $extra_js = " var f=document.getElementById('adminForm'); f.elements['view'].value='appsman'; jQuery('<input>').attr({type: 'hidden', name: 'table', value: 'categories'}).appendTo(jQuery(f));";
         flexicontent_html::addToolBarButton('Export now', $btn_name, $full_js = '', $msg_alert = '', $msg_confirm = 'Export now as XML', $btn_task, $extra_js, $btn_list = false, $btn_menu = true, $btn_confirm = true, $btn_class = "btn-warning", $btn_icon);
         $btn_icon = 'icon-box-add';
         $btn_name = 'box-add';
         $btn_task = 'appsman.addtoexport';
         $extra_js = " var f=document.getElementById('adminForm'); f.elements['view'].value='appsman'; jQuery('<input>').attr({type: 'hidden', name: 'table', value: 'categories'}).appendTo(jQuery(f));";
         flexicontent_html::addToolBarButton('Add to export', $btn_name, $full_js = '', $msg_alert = '', $msg_confirm = 'Add to export list', $btn_task, $extra_js, $btn_list = false, $btn_menu = true, $btn_confirm = true, $btn_class = "btn-warning", $btn_icon);
     }
     if ($perms->CanConfig) {
         //JToolBarHelper::custom($contrl.'rebuild', 'refresh.png', 'refresh_f2.png', 'JTOOLBAR_REBUILD', false);
         $session = JFactory::getSession();
         $fc_screen_width = (int) $session->get('fc_screen_width', 0, 'flexicontent');
         $_width = $fc_screen_width && $fc_screen_width - 84 > 940 ? $fc_screen_width - 84 > 1400 ? 1400 : $fc_screen_width - 84 : 940;
         $fc_screen_height = (int) $session->get('fc_screen_height', 0, 'flexicontent');
         $_height = $fc_screen_height && $fc_screen_height - 128 > 550 ? $fc_screen_height - 128 > 1000 ? 1000 : $fc_screen_height - 128 : 550;
         JToolBarHelper::preferences('com_flexicontent', $_height, $_width, 'Configuration');
     }
     $js .= "});";
     $document->addScriptDeclaration($js);
     // Get data from the model
     if ($print_logging_info) {
         $start_microtime = microtime(true);
     }
     $rows = $this->get('Items');
     if ($print_logging_info) {
         @($fc_run_times['execute_main_query'] += round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
     }
     // Get assigned items
     $rowids = array();
     foreach ($rows as $row) {
         $rowids[] = $row->id;
     }
     if ($print_logging_info) {
         $start_microtime = microtime(true);
     }
     //$rowtotals = $model->getAssignedItems($rowids);
     $byStateTotals = $model->countItemsByState($rowids);
     if ($print_logging_info) {
         @($fc_run_times['execute_sec_queries'] += round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
     }
     foreach ($rows as $row) {
         //$row->nrassigned = isset($rowtotals[$row->id]) ? $rowtotals[$row->id]->nrassigned : 0;
         $row->byStateTotals = isset($byStateTotals[$row->id]) ? $byStateTotals[$row->id] : array();
     }
     // Parse configuration for every category
     foreach ($rows as $cat) {
         $cat->config = new JRegistry($cat->config);
     }
     $this->state = $this->get('State');
     // Preprocess the list of items to find ordering divisions.
     foreach ($rows as &$item) {
         $this->ordering[$item->parent_id][] = $item->id;
     }
     unset($item);
     // unset the variable reference to avoid trouble if variable is reused, thus overwritting last pointed variable
     $pagination = $this->get('Pagination');
     $categories =& $globalcats;
     $lists['copyid'] = flexicontent_cats::buildcatselect($categories, 'copycid', '', 2, 'class="use_select2_lib"', false, true, $actions_allowed = array('core.edit'));
     $lists['destid'] = flexicontent_cats::buildcatselect($categories, 'destcid[]', '', false, 'class="use_select2_lib" size="10" multiple="true"', false, true, $actions_allowed = array('core.edit'));
     // *******************
     // Create Form Filters
     // *******************
     // filter by a category (it's subtree will be displayed)
     $categories = $globalcats;
     $lists['cats'] = ($filter_cats || 1 ? '<label class="label">' . JText::_('FLEXI_CATEGORY') . '</label>' : '') . flexicontent_cats::buildcatselect($categories, 'filter_cats', $filter_cats, '-', 'class="use_select2_lib" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', $check_published = true, $check_perms = false);
     // filter depth level
     $options = array();
     $options[] = JHtml::_('select.option', '', '-');
     for ($i = 1; $i <= 10; $i++) {
         $options[] = JHtml::_('select.option', $i, $i);
     }
     $fieldname = $elementid = 'filter_level';
     $attribs = 'class="use_select2_lib" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"';
     $lists['level'] = ($filter_level || 1 ? '<label class="label">' . JText::_('FLEXI_MAX_DEPTH') . '</label>' : '') . JHTML::_('select.genericlist', $options, $fieldname, $attribs, 'value', 'text', $filter_level, $elementid, $translate = true);
     // filter publication state
     $options = JHtml::_('jgrid.publishedOptions');
     array_unshift($options, JHtml::_('select.option', '', '-'));
     $fieldname = $elementid = 'filter_state';
     $attribs = 'class="use_select2_lib" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"';
     $lists['state'] = ($filter_state || 1 ? '<label class="label">' . JText::_('FLEXI_STATE') . '</label>' : '') . JHTML::_('select.genericlist', $options, $fieldname, $attribs, 'value', 'text', $filter_state, $elementid, $translate = true);
     // filter access level
     $options = JHtml::_('access.assetgroups');
     array_unshift($options, JHtml::_('select.option', '', '-'));
     $fieldname = $elementid = 'filter_access';
     $attribs = 'class="use_select2_lib" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"';
     $lists['access'] = ($filter_access || 1 ? '<label class="label">' . JText::_('FLEXI_ACCESS') . '</label>' : '') . JHTML::_('select.genericlist', $options, $fieldname, $attribs, 'value', 'text', $filter_access, $elementid, $translate = true);
     // filter language
     $lists['language'] = ($filter_language || 1 ? '<label class="label">' . JText::_('FLEXI_LANGUAGE') . '</label>' : '') . flexicontent_html::buildlanguageslist('filter_language', 'class="use_select2_lib" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', $filter_language, '-');
     // filter search word
     $lists['search'] = $search;
     // search id
     $lists['filter_id'] = $filter_id;
     // table ordering
     $lists['order_Dir'] = $filter_order_Dir;
     $lists['order'] = $filter_order;
     $orderingx = $lists['order'] == $order_property && strtolower($lists['order_Dir']) == 'asc' ? $order_property : '';
     //assign data to template
     $this->assignRef('CanTemplates', $perms->CanTemplates);
     $this->assignRef('count_filters', $count_filters);
     $this->assignRef('lists', $lists);
     $this->assignRef('rows', $rows);
     $this->assignRef('perms', $perms);
     $this->assignRef('orderingx', $orderingx);
     $this->assignRef('pagination', $pagination);
     $this->assignRef('user', $user);
     $this->assignRef('option', $option);
     $this->assignRef('view', $view);
     $this->sidebar = FLEXI_J30GE ? JHtmlSidebar::render() : null;
     parent::display($tpl);
 }